diff --git a/dist/index.js b/dist/index.js index 6d715cb..25d49a3 100644 --- a/dist/index.js +++ b/dist/index.js @@ -1,7 +1,34 @@ require('./sourcemap-register.js');/******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ -/***/ 536: +/***/ 5850: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.writeText = void 0; +const fs_1 = __importDefault(__nccwpck_require__(7147)); +const writeText = async (path, textFilePath) => { + //Add text to first of line + const text = fs_1.default.readFileSync(textFilePath, 'utf8'); + const content = await fs_1.default.readFileSync(path, 'utf8'); + const lines = content.split('\n'); + const firstLine = lines[0]; + let newContent = `${text}\n${firstLine}`; + newContent += lines.slice(1).join('\n'); + newContent = newContent.replace(/\n/g, '\n//'); + return await fs_1.default.writeFileSync(path, newContent, 'utf8'); +}; +exports.writeText = writeText; + + +/***/ }), + +/***/ 147: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -29,20 +56,147 @@ var __importStar = (this && this.__importStar) || function (mod) { __setModuleDefault(result, mod); return result; }; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; Object.defineProperty(exports, "__esModule", ({ value: true })); -const core = __importStar(__nccwpck_require__(186)); -const run_1 = __nccwpck_require__(995); -const main = async () => { - await (0, run_1.run)({ - name: core.getInput('name', { required: true }), +exports.compositeYan = void 0; +const core = __importStar(__nccwpck_require__(2186)); +const jimp_1 = __importDefault(__nccwpck_require__(3794)); +const compositeYan = async (imgSrc, yanSrc) => { + const image = await jimp_1.default.read(imgSrc); + const yan = await jimp_1.default.read(yanSrc); + const xMargin = (image.bitmap.width * 5) / 100; + const yMargin = (image.bitmap.width * 5) / 100; + const X = image.bitmap.width - yan.bitmap.width - xMargin; + const Y = image.bitmap.height - yan.bitmap.height - yMargin; + core.info(`writing image : ${imgSrc}`); + const img = image.composite(yan, X, Y); + img.write(imgSrc); + return img; +}; +exports.compositeYan = compositeYan; + + +/***/ }), + +/***/ 1886: +/***/ (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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const path_1 = __importDefault(__nccwpck_require__(1017)); +const fs_1 = __importDefault(__nccwpck_require__(7147)); +const axios_1 = __importDefault(__nccwpck_require__(6545)); +const core = __importStar(__nccwpck_require__(2186)); +const defaultAssetURL = { + assci: 'https://raw.githubusercontent.com/ST4RCHASER/monk-action/main/assets/ascii.txt', + image: 'https://raw.githubusercontent.com/ST4RCHASER/monk-action/main/assets/image.png', + audio: 'https://raw.githubusercontent.com/ST4RCHASER/monk-action/main/assets/audio.mp3', +}; +const loadDefaultAsset = async () => { + return new Promise(async (resolve) => { + const base = path_1.default.resolve(__dirname, '../../.monk'); + core.info(`base: ${base}`); + const loc = { + assci: path_1.default.join(base, 'ascii.txt'), + image: path_1.default.join(base, 'image.png'), + audio: path_1.default.join(base, 'audio.mp3'), + }; + //Check if base folder not exist create it + if (!fs_1.default.existsSync(base)) { + fs_1.default.mkdirSync(base); + } + //Check if assci file not exist download it + if (!fs_1.default.existsSync(loc.assci)) { + const response = await axios_1.default.get(defaultAssetURL.assci); + fs_1.default.writeFileSync(loc.assci, response.data); + } + //Check if image file not exist download it + if (!fs_1.default.existsSync(loc.image)) { + const response = await axios_1.default.get(defaultAssetURL.image); + fs_1.default.writeFileSync(loc.image, response.data); + } + //Check if audio file not exist download it + if (!fs_1.default.existsSync(loc.audio)) { + const response = await axios_1.default.get(defaultAssetURL.audio); + fs_1.default.writeFileSync(loc.audio, response.data); + } + resolve(loc); }); }; +exports["default"] = loadDefaultAsset; + + +/***/ }), + +/***/ 9536: +/***/ (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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const core = __importStar(__nccwpck_require__(2186)); +const run_1 = __nccwpck_require__(3995); +const main = async () => { + await (0, run_1.run)({ path: core.getInput('path') }); +}; main().catch((e) => core.setFailed(e instanceof Error ? e.message : JSON.stringify(e))); /***/ }), -/***/ 995: +/***/ 3995: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -70,19 +224,60 @@ var __importStar = (this && this.__importStar) || function (mod) { __setModuleDefault(result, mod); return result; }; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.run = void 0; -const core = __importStar(__nccwpck_require__(186)); +const core = __importStar(__nccwpck_require__(2186)); +const fs_1 = __nccwpck_require__(7147); +const ignore_walk_1 = __importDefault(__nccwpck_require__(6296)); +const path_1 = __importDefault(__nccwpck_require__(1017)); +const ascii_1 = __nccwpck_require__(5850); +const image_1 = __nccwpck_require__(147); +const loadDefaultAsset_1 = __importDefault(__nccwpck_require__(1886)); // eslint-disable-next-line @typescript-eslint/require-await -const run = async (inputs) => { - core.info(`my name is ${inputs.name}`); +const run = async (input) => { + try { + const filePath = path_1.default.resolve(input.path); + const files = await (0, ignore_walk_1.default)({ + path: filePath, + includeEmpty: false, + ignoreFiles: ['.gitignore', '.prettierignore'], + }); + const filteredFiles = files.filter((i) => i.indexOf('.git/') === -1).filter((i) => i.indexOf('.monk/') === -1).filter((i) => i.indexOf('.github/') === -1); + const lists = filteredFiles.map((i) => path_1.default.join(filePath, i)); + const loc = await (0, loadDefaultAsset_1.default)(); + const promises = Promise.all(lists.map(async (i) => { + //Check if file size not zero and less than 5MB + const stats = await fs_1.promises.stat(i); + if (stats.size > 0 && stats.size < 5242880) { + const fileExtension = path_1.default.extname(i); + switch (fileExtension) { + case '.jpg': + case '.png': + case '.gif': + case '.jepg': + await (0, image_1.compositeYan)(i, loc.image); + break; + default: + await (0, ascii_1.writeText)(i, loc.assci); + break; + } + } + })); + core.info(`Results: ${JSON.stringify(lists)}`); + } + catch (err) { + core.error(`sumting wrong with something: ${err}`); + } }; exports.run = run; /***/ }), -/***/ 351: +/***/ 7351: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -108,8 +303,8 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.issue = exports.issueCommand = void 0; -const os = __importStar(__nccwpck_require__(37)); -const utils_1 = __nccwpck_require__(278); +const os = __importStar(__nccwpck_require__(2037)); +const utils_1 = __nccwpck_require__(5278); /** * Commands * @@ -181,7 +376,7 @@ function escapeProperty(s) { /***/ }), -/***/ 186: +/***/ 2186: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -216,12 +411,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getIDToken = exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.notice = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getMultilineInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0; -const command_1 = __nccwpck_require__(351); +const command_1 = __nccwpck_require__(7351); const file_command_1 = __nccwpck_require__(717); -const utils_1 = __nccwpck_require__(278); -const os = __importStar(__nccwpck_require__(37)); -const path = __importStar(__nccwpck_require__(17)); -const oidc_utils_1 = __nccwpck_require__(41); +const utils_1 = __nccwpck_require__(5278); +const os = __importStar(__nccwpck_require__(2037)); +const path = __importStar(__nccwpck_require__(1017)); +const oidc_utils_1 = __nccwpck_require__(8041); /** * The code to exit an action */ @@ -499,17 +694,17 @@ exports.getIDToken = getIDToken; /** * Summary exports */ -var summary_1 = __nccwpck_require__(327); +var summary_1 = __nccwpck_require__(1327); Object.defineProperty(exports, "summary", ({ enumerable: true, get: function () { return summary_1.summary; } })); /** * @deprecated use core.summary */ -var summary_2 = __nccwpck_require__(327); +var summary_2 = __nccwpck_require__(1327); Object.defineProperty(exports, "markdownSummary", ({ enumerable: true, get: function () { return summary_2.markdownSummary; } })); /** * Path exports */ -var path_utils_1 = __nccwpck_require__(981); +var path_utils_1 = __nccwpck_require__(2981); Object.defineProperty(exports, "toPosixPath", ({ enumerable: true, get: function () { return path_utils_1.toPosixPath; } })); Object.defineProperty(exports, "toWin32Path", ({ enumerable: true, get: function () { return path_utils_1.toWin32Path; } })); Object.defineProperty(exports, "toPlatformPath", ({ enumerable: true, get: function () { return path_utils_1.toPlatformPath; } })); @@ -546,9 +741,9 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.issueCommand = void 0; // We use any as a valid input type /* eslint-disable @typescript-eslint/no-explicit-any */ -const fs = __importStar(__nccwpck_require__(147)); -const os = __importStar(__nccwpck_require__(37)); -const utils_1 = __nccwpck_require__(278); +const fs = __importStar(__nccwpck_require__(7147)); +const os = __importStar(__nccwpck_require__(2037)); +const utils_1 = __nccwpck_require__(5278); function issueCommand(command, message) { const filePath = process.env[`GITHUB_${command}`]; if (!filePath) { @@ -566,7 +761,7 @@ exports.issueCommand = issueCommand; /***/ }), -/***/ 41: +/***/ 8041: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -582,9 +777,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.OidcClient = void 0; -const http_client_1 = __nccwpck_require__(255); -const auth_1 = __nccwpck_require__(526); -const core_1 = __nccwpck_require__(186); +const http_client_1 = __nccwpck_require__(6255); +const auth_1 = __nccwpck_require__(5526); +const core_1 = __nccwpck_require__(2186); class OidcClient { static createHttpClient(allowRetry = true, maxRetry = 10) { const requestOptions = { @@ -650,7 +845,7 @@ exports.OidcClient = OidcClient; /***/ }), -/***/ 981: +/***/ 2981: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -676,7 +871,7 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = void 0; -const path = __importStar(__nccwpck_require__(17)); +const path = __importStar(__nccwpck_require__(1017)); /** * toPosixPath converts the given path to the posix form. On Windows, \\ will be * replaced with /. @@ -715,7 +910,7 @@ exports.toPlatformPath = toPlatformPath; /***/ }), -/***/ 327: +/***/ 1327: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -731,8 +926,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.summary = exports.markdownSummary = exports.SUMMARY_DOCS_URL = exports.SUMMARY_ENV_VAR = void 0; -const os_1 = __nccwpck_require__(37); -const fs_1 = __nccwpck_require__(147); +const os_1 = __nccwpck_require__(2037); +const fs_1 = __nccwpck_require__(7147); const { access, appendFile, writeFile } = fs_1.promises; exports.SUMMARY_ENV_VAR = 'GITHUB_STEP_SUMMARY'; exports.SUMMARY_DOCS_URL = 'https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary'; @@ -1005,7 +1200,7 @@ exports.summary = _summary; /***/ }), -/***/ 278: +/***/ 5278: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -1052,7 +1247,7 @@ exports.toCommandProperties = toCommandProperties; /***/ }), -/***/ 526: +/***/ 5526: /***/ (function(__unused_webpack_module, exports) { "use strict"; @@ -1140,7 +1335,7 @@ exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHand /***/ }), -/***/ 255: +/***/ 6255: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -1176,10 +1371,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.HttpClient = exports.isHttps = exports.HttpClientResponse = exports.HttpClientError = exports.getProxyUrl = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0; -const http = __importStar(__nccwpck_require__(685)); -const https = __importStar(__nccwpck_require__(687)); -const pm = __importStar(__nccwpck_require__(835)); -const tunnel = __importStar(__nccwpck_require__(294)); +const http = __importStar(__nccwpck_require__(3685)); +const https = __importStar(__nccwpck_require__(5687)); +const pm = __importStar(__nccwpck_require__(9835)); +const tunnel = __importStar(__nccwpck_require__(4294)); var HttpCodes; (function (HttpCodes) { HttpCodes[HttpCodes["OK"] = 200] = "OK"; @@ -1752,7 +1947,7 @@ const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCa /***/ }), -/***/ 835: +/***/ 9835: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -1820,363 +2015,45123 @@ exports.checkBypass = checkBypass; /***/ }), -/***/ 294: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 4858: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +var _interopRequireDefault = __nccwpck_require__(3286); + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _defineProperty2 = _interopRequireDefault(__nccwpck_require__(1814)); + +var _bmpJs = _interopRequireDefault(__nccwpck_require__(9030)); + +var _utils = __nccwpck_require__(7403); + +var MIME_TYPE = 'image/bmp'; +var MIME_TYPE_SECOND = 'image/x-ms-bmp'; + +function toAGBR(image) { + return (0, _utils.scan)(image, 0, 0, image.bitmap.width, image.bitmap.height, function (x, y, index) { + var red = this.bitmap.data[index + 0]; + var green = this.bitmap.data[index + 1]; + var blue = this.bitmap.data[index + 2]; + var alpha = this.bitmap.data[index + 3]; + this.bitmap.data[index + 0] = alpha; + this.bitmap.data[index + 1] = blue; + this.bitmap.data[index + 2] = green; + this.bitmap.data[index + 3] = red; + }).bitmap; +} + +function fromAGBR(bitmap) { + return (0, _utils.scan)({ + bitmap: bitmap + }, 0, 0, bitmap.width, bitmap.height, function (x, y, index) { + var alpha = this.bitmap.data[index + 0]; + var blue = this.bitmap.data[index + 1]; + var green = this.bitmap.data[index + 2]; + var red = this.bitmap.data[index + 3]; + this.bitmap.data[index + 0] = red; + this.bitmap.data[index + 1] = green; + this.bitmap.data[index + 2] = blue; + this.bitmap.data[index + 3] = bitmap.is_with_alpha ? alpha : 0xff; + }).bitmap; +} + +var decode = function decode(data) { + return fromAGBR(_bmpJs["default"].decode(data)); +}; + +var encode = function encode(image) { + return _bmpJs["default"].encode(toAGBR(image)).data; +}; + +var _default = function _default() { + var _decoders, _encoders; -module.exports = __nccwpck_require__(219); + return { + mime: (0, _defineProperty2["default"])({}, MIME_TYPE, ['bmp']), + constants: { + MIME_BMP: MIME_TYPE, + MIME_X_MS_BMP: MIME_TYPE_SECOND + }, + decoders: (_decoders = {}, (0, _defineProperty2["default"])(_decoders, MIME_TYPE, decode), (0, _defineProperty2["default"])(_decoders, MIME_TYPE_SECOND, decode), _decoders), + encoders: (_encoders = {}, (0, _defineProperty2["default"])(_encoders, MIME_TYPE, encode), (0, _defineProperty2["default"])(_encoders, MIME_TYPE_SECOND, encode), _encoders) + }; +}; +exports["default"] = _default; +module.exports = exports.default; +//# sourceMappingURL=index.js.map /***/ }), -/***/ 219: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 8284: +/***/ ((__unused_webpack_module, exports) => { "use strict"; -var net = __nccwpck_require__(808); -var tls = __nccwpck_require__(404); -var http = __nccwpck_require__(685); -var https = __nccwpck_require__(687); -var events = __nccwpck_require__(361); -var assert = __nccwpck_require__(491); -var util = __nccwpck_require__(837); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.srcOver = srcOver; +exports.dstOver = dstOver; +exports.multiply = multiply; +exports.add = add; +exports.screen = screen; +exports.overlay = overlay; +exports.darken = darken; +exports.lighten = lighten; +exports.hardLight = hardLight; +exports.difference = difference; +exports.exclusion = exclusion; +function srcOver(src, dst) { + var ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + src.a *= ops; + var a = dst.a + src.a - dst.a * src.a; + var r = (src.r * src.a + dst.r * dst.a * (1 - src.a)) / a; + var g = (src.g * src.a + dst.g * dst.a * (1 - src.a)) / a; + var b = (src.b * src.a + dst.b * dst.a * (1 - src.a)) / a; + return { + r: r, + g: g, + b: b, + a: a + }; +} -exports.httpOverHttp = httpOverHttp; -exports.httpsOverHttp = httpsOverHttp; -exports.httpOverHttps = httpOverHttps; -exports.httpsOverHttps = httpsOverHttps; +function dstOver(src, dst) { + var ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + src.a *= ops; + var a = dst.a + src.a - dst.a * src.a; + var r = (dst.r * dst.a + src.r * src.a * (1 - dst.a)) / a; + var g = (dst.g * dst.a + src.g * src.a * (1 - dst.a)) / a; + var b = (dst.b * dst.a + src.b * src.a * (1 - dst.a)) / a; + return { + r: r, + g: g, + b: b, + a: a + }; +} + +function multiply(src, dst) { + var ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + src.a *= ops; + var a = dst.a + src.a - dst.a * src.a; + var sra = src.r * src.a; + var sga = src.g * src.a; + var sba = src.b * src.a; + var dra = dst.r * dst.a; + var dga = dst.g * dst.a; + var dba = dst.b * dst.a; + var r = (sra * dra + sra * (1 - dst.a) + dra * (1 - src.a)) / a; + var g = (sga * dga + sga * (1 - dst.a) + dga * (1 - src.a)) / a; + var b = (sba * dba + sba * (1 - dst.a) + dba * (1 - src.a)) / a; + return { + r: r, + g: g, + b: b, + a: a + }; +} +function add(src, dst) { + var ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + src.a *= ops; + var a = dst.a + src.a - dst.a * src.a; + var sra = src.r * src.a; + var sga = src.g * src.a; + var sba = src.b * src.a; + var dra = dst.r * dst.a; + var dga = dst.g * dst.a; + var dba = dst.b * dst.a; + var r = (sra + dra) / a; + var g = (sga + dga) / a; + var b = (sba + dba) / a; + return { + r: r, + g: g, + b: b, + a: a + }; +} -function httpOverHttp(options) { - var agent = new TunnelingAgent(options); - agent.request = http.request; - return agent; +function screen(src, dst) { + var ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + src.a *= ops; + var a = dst.a + src.a - dst.a * src.a; + var sra = src.r * src.a; + var sga = src.g * src.a; + var sba = src.b * src.a; + var dra = dst.r * dst.a; + var dga = dst.g * dst.a; + var dba = dst.b * dst.a; + var r = (sra * dst.a + dra * src.a - sra * dra + sra * (1 - dst.a) + dra * (1 - src.a)) / a; + var g = (sga * dst.a + dga * src.a - sga * dga + sga * (1 - dst.a) + dga * (1 - src.a)) / a; + var b = (sba * dst.a + dba * src.a - sba * dba + sba * (1 - dst.a) + dba * (1 - src.a)) / a; + return { + r: r, + g: g, + b: b, + a: a + }; } -function httpsOverHttp(options) { - var agent = new TunnelingAgent(options); - agent.request = http.request; - agent.createSocket = createSecureSocket; - agent.defaultPort = 443; - return agent; +function overlay(src, dst) { + var ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + src.a *= ops; + var a = dst.a + src.a - dst.a * src.a; + var sra = src.r * src.a; + var sga = src.g * src.a; + var sba = src.b * src.a; + var dra = dst.r * dst.a; + var dga = dst.g * dst.a; + var dba = dst.b * dst.a; + var r = (2 * dra <= dst.a ? 2 * sra * dra + sra * (1 - dst.a) + dra * (1 - src.a) : sra * (1 + dst.a) + dra * (1 + src.a) - 2 * dra * sra - dst.a * src.a) / a; + var g = (2 * dga <= dst.a ? 2 * sga * dga + sga * (1 - dst.a) + dga * (1 - src.a) : sga * (1 + dst.a) + dga * (1 + src.a) - 2 * dga * sga - dst.a * src.a) / a; + var b = (2 * dba <= dst.a ? 2 * sba * dba + sba * (1 - dst.a) + dba * (1 - src.a) : sba * (1 + dst.a) + dba * (1 + src.a) - 2 * dba * sba - dst.a * src.a) / a; + return { + r: r, + g: g, + b: b, + a: a + }; } -function httpOverHttps(options) { - var agent = new TunnelingAgent(options); - agent.request = https.request; - return agent; +function darken(src, dst) { + var ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + src.a *= ops; + var a = dst.a + src.a - dst.a * src.a; + var sra = src.r * src.a; + var sga = src.g * src.a; + var sba = src.b * src.a; + var dra = dst.r * dst.a; + var dga = dst.g * dst.a; + var dba = dst.b * dst.a; + var r = (Math.min(sra * dst.a, dra * src.a) + sra * (1 - dst.a) + dra * (1 - src.a)) / a; + var g = (Math.min(sga * dst.a, dga * src.a) + sga * (1 - dst.a) + dga * (1 - src.a)) / a; + var b = (Math.min(sba * dst.a, dba * src.a) + sba * (1 - dst.a) + dba * (1 - src.a)) / a; + return { + r: r, + g: g, + b: b, + a: a + }; } -function httpsOverHttps(options) { - var agent = new TunnelingAgent(options); - agent.request = https.request; - agent.createSocket = createSecureSocket; - agent.defaultPort = 443; - return agent; +function lighten(src, dst) { + var ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + src.a *= ops; + var a = dst.a + src.a - dst.a * src.a; + var sra = src.r * src.a; + var sga = src.g * src.a; + var sba = src.b * src.a; + var dra = dst.r * dst.a; + var dga = dst.g * dst.a; + var dba = dst.b * dst.a; + var r = (Math.max(sra * dst.a, dra * src.a) + sra * (1 - dst.a) + dra * (1 - src.a)) / a; + var g = (Math.max(sga * dst.a, dga * src.a) + sga * (1 - dst.a) + dga * (1 - src.a)) / a; + var b = (Math.max(sba * dst.a, dba * src.a) + sba * (1 - dst.a) + dba * (1 - src.a)) / a; + return { + r: r, + g: g, + b: b, + a: a + }; } +function hardLight(src, dst) { + var ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + src.a *= ops; + var a = dst.a + src.a - dst.a * src.a; + var sra = src.r * src.a; + var sga = src.g * src.a; + var sba = src.b * src.a; + var dra = dst.r * dst.a; + var dga = dst.g * dst.a; + var dba = dst.b * dst.a; + var r = (2 * sra <= src.a ? 2 * sra * dra + sra * (1 - dst.a) + dra * (1 - src.a) : sra * (1 + dst.a) + dra * (1 + src.a) - 2 * dra * sra - dst.a * src.a) / a; + var g = (2 * sga <= src.a ? 2 * sga * dga + sga * (1 - dst.a) + dga * (1 - src.a) : sga * (1 + dst.a) + dga * (1 + src.a) - 2 * dga * sga - dst.a * src.a) / a; + var b = (2 * sba <= src.a ? 2 * sba * dba + sba * (1 - dst.a) + dba * (1 - src.a) : sba * (1 + dst.a) + dba * (1 + src.a) - 2 * dba * sba - dst.a * src.a) / a; + return { + r: r, + g: g, + b: b, + a: a + }; +} -function TunnelingAgent(options) { - var self = this; - self.options = options || {}; - self.proxyOptions = self.options.proxy || {}; - self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets; - self.requests = []; - self.sockets = []; +function difference(src, dst) { + var ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + src.a *= ops; + var a = dst.a + src.a - dst.a * src.a; + var sra = src.r * src.a; + var sga = src.g * src.a; + var sba = src.b * src.a; + var dra = dst.r * dst.a; + var dga = dst.g * dst.a; + var dba = dst.b * dst.a; + var r = (sra + dra - 2 * Math.min(sra * dst.a, dra * src.a)) / a; + var g = (sga + dga - 2 * Math.min(sga * dst.a, dga * src.a)) / a; + var b = (sba + dba - 2 * Math.min(sba * dst.a, dba * src.a)) / a; + return { + r: r, + g: g, + b: b, + a: a + }; +} - self.on('free', function onFree(socket, host, port, localAddress) { - var options = toOptions(host, port, localAddress); - for (var i = 0, len = self.requests.length; i < len; ++i) { - var pending = self.requests[i]; - if (pending.host === options.host && pending.port === options.port) { - // Detect the request to connect same origin server, - // reuse the connection. - self.requests.splice(i, 1); - pending.request.onSocket(socket); - return; - } - } - socket.destroy(); - self.removeSocket(socket); - }); +function exclusion(src, dst) { + var ops = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + src.a *= ops; + var a = dst.a + src.a - dst.a * src.a; + var sra = src.r * src.a; + var sga = src.g * src.a; + var sba = src.b * src.a; + var dra = dst.r * dst.a; + var dga = dst.g * dst.a; + var dba = dst.b * dst.a; + var r = (sra * dst.a + dra * src.a - 2 * sra * dra + sra * (1 - dst.a) + dra * (1 - src.a)) / a; + var g = (sga * dst.a + dga * src.a - 2 * sga * dga + sga * (1 - dst.a) + dga * (1 - src.a)) / a; + var b = (sba * dst.a + dba * src.a - 2 * sba * dba + sba * (1 - dst.a) + dba * (1 - src.a)) / a; + return { + r: r, + g: g, + b: b, + a: a + }; } -util.inherits(TunnelingAgent, events.EventEmitter); +//# sourceMappingURL=composite-modes.js.map -TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) { - var self = this; - var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress)); +/***/ }), - if (self.sockets.length >= this.maxSockets) { - // We are over limit so we'll add it to the queue. - self.requests.push(options); - return; - } +/***/ 5141: +/***/ ((module, exports, __nccwpck_require__) => { - // If we are under maxSockets create a new one. - self.createSocket(options, function(socket) { - socket.on('free', onFree); - socket.on('close', onCloseOrRemove); - socket.on('agentRemove', onCloseOrRemove); - req.onSocket(socket); +"use strict"; - function onFree() { - self.emit('free', socket, options); - } - function onCloseOrRemove(err) { - self.removeSocket(socket); - socket.removeListener('free', onFree); - socket.removeListener('close', onCloseOrRemove); - socket.removeListener('agentRemove', onCloseOrRemove); - } - }); -}; +var _interopRequireWildcard = __nccwpck_require__(4405); -TunnelingAgent.prototype.createSocket = function createSocket(options, cb) { - var self = this; - var placeholder = {}; - self.sockets.push(placeholder); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = composite; - var connectOptions = mergeOptions({}, self.proxyOptions, { - method: 'CONNECT', - path: options.host + ':' + options.port, - agent: false, - headers: { - host: options.host + ':' + options.port - } - }); - if (options.localAddress) { - connectOptions.localAddress = options.localAddress; +var _utils = __nccwpck_require__(7403); + +var constants = _interopRequireWildcard(__nccwpck_require__(4619)); + +var compositeModes = _interopRequireWildcard(__nccwpck_require__(8284)); + +/** + * Composites a source image over to this image respecting alpha channels + * @param {Jimp} src the source Jimp instance + * @param {number} x the x position to blit the image + * @param {number} y the y position to blit the image + * @param {object} options determine what mode to use + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ +function composite(src, x, y) { + var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; + var cb = arguments.length > 4 ? arguments[4] : undefined; + + if (typeof options === 'function') { + cb = options; + options = {}; } - if (connectOptions.proxyAuth) { - connectOptions.headers = connectOptions.headers || {}; - connectOptions.headers['Proxy-Authorization'] = 'Basic ' + - new Buffer(connectOptions.proxyAuth).toString('base64'); + + if (!(src instanceof this.constructor)) { + return _utils.throwError.call(this, 'The source must be a Jimp image', cb); } - debug('making CONNECT request'); - var connectReq = self.request(connectOptions); - connectReq.useChunkedEncodingByDefault = false; // for v0.6 - connectReq.once('response', onResponse); // for v0.6 - connectReq.once('upgrade', onUpgrade); // for v0.6 - connectReq.once('connect', onConnect); // for v0.7 or later - connectReq.once('error', onError); - connectReq.end(); + if (typeof x !== 'number' || typeof y !== 'number') { + return _utils.throwError.call(this, 'x and y must be numbers', cb); + } - function onResponse(res) { - // Very hacky. This is necessary to avoid http-parser leaks. - res.upgrade = true; + var _options = options, + mode = _options.mode, + opacitySource = _options.opacitySource, + opacityDest = _options.opacityDest; + + if (!mode) { + mode = constants.BLEND_SOURCE_OVER; } - function onUpgrade(res, socket, head) { - // Hacky. - process.nextTick(function() { - onConnect(res, socket, head); - }); + if (typeof opacitySource !== 'number' || opacitySource < 0 || opacitySource > 1) { + opacitySource = 1.0; } - function onConnect(res, socket, head) { - connectReq.removeAllListeners(); - socket.removeAllListeners(); + if (typeof opacityDest !== 'number' || opacityDest < 0 || opacityDest > 1) { + opacityDest = 1.0; + } - if (res.statusCode !== 200) { - debug('tunneling socket could not be established, statusCode=%d', - res.statusCode); - socket.destroy(); - var error = new Error('tunneling socket could not be established, ' + - 'statusCode=' + res.statusCode); - error.code = 'ECONNRESET'; - options.request.emit('error', error); - self.removeSocket(placeholder); - return; - } - if (head.length > 0) { - debug('got illegal response body from proxy'); - socket.destroy(); - var error = new Error('got illegal response body from proxy'); - error.code = 'ECONNRESET'; - options.request.emit('error', error); - self.removeSocket(placeholder); - return; - } - debug('tunneling connection has established'); - self.sockets[self.sockets.indexOf(placeholder)] = socket; - return cb(socket); - } + var blendmode = compositeModes[mode]; // round input - function onError(cause) { - connectReq.removeAllListeners(); + x = Math.round(x); + y = Math.round(y); + var baseImage = this; - debug('tunneling socket could not be established, cause=%s\n', - cause.message, cause.stack); - var error = new Error('tunneling socket could not be established, ' + - 'cause=' + cause.message); - error.code = 'ECONNRESET'; - options.request.emit('error', error); - self.removeSocket(placeholder); + if (opacityDest !== 1.0) { + baseImage.opacity(opacityDest); } -}; -TunnelingAgent.prototype.removeSocket = function removeSocket(socket) { - var pos = this.sockets.indexOf(socket) - if (pos === -1) { - return; + src.scanQuiet(0, 0, src.bitmap.width, src.bitmap.height, function (sx, sy, idx) { + var dstIdx = baseImage.getPixelIndex(x + sx, y + sy, constants.EDGE_CROP); + var blended = blendmode({ + r: this.bitmap.data[idx + 0] / 255, + g: this.bitmap.data[idx + 1] / 255, + b: this.bitmap.data[idx + 2] / 255, + a: this.bitmap.data[idx + 3] / 255 + }, { + r: baseImage.bitmap.data[dstIdx + 0] / 255, + g: baseImage.bitmap.data[dstIdx + 1] / 255, + b: baseImage.bitmap.data[dstIdx + 2] / 255, + a: baseImage.bitmap.data[dstIdx + 3] / 255 + }, opacitySource); + baseImage.bitmap.data[dstIdx + 0] = this.constructor.limit255(blended.r * 255); + baseImage.bitmap.data[dstIdx + 1] = this.constructor.limit255(blended.g * 255); + baseImage.bitmap.data[dstIdx + 2] = this.constructor.limit255(blended.b * 255); + baseImage.bitmap.data[dstIdx + 3] = this.constructor.limit255(blended.a * 255); + }); + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(this, null, this); } - this.sockets.splice(pos, 1); - var pending = this.requests.shift(); - if (pending) { - // If we have pending requests and a socket gets closed a new one - // needs to be created to take over in the pool for the one that closed. - this.createSocket(pending, function(socket) { - pending.request.onSocket(socket); - }); + return this; +} + +module.exports = exports.default; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 4619: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.EDGE_CROP = exports.EDGE_WRAP = exports.EDGE_EXTEND = exports.BLEND_EXCLUSION = exports.BLEND_DIFFERENCE = exports.BLEND_HARDLIGHT = exports.BLEND_LIGHTEN = exports.BLEND_DARKEN = exports.BLEND_OVERLAY = exports.BLEND_SCREEN = exports.BLEND_ADD = exports.BLEND_MULTIPLY = exports.BLEND_DESTINATION_OVER = exports.BLEND_SOURCE_OVER = exports.VERTICAL_ALIGN_BOTTOM = exports.VERTICAL_ALIGN_MIDDLE = exports.VERTICAL_ALIGN_TOP = exports.HORIZONTAL_ALIGN_RIGHT = exports.HORIZONTAL_ALIGN_CENTER = exports.HORIZONTAL_ALIGN_LEFT = exports.AUTO = void 0; +// used to auto resizing etc. +var AUTO = -1; // Align modes for cover, contain, bit masks + +exports.AUTO = AUTO; +var HORIZONTAL_ALIGN_LEFT = 1; +exports.HORIZONTAL_ALIGN_LEFT = HORIZONTAL_ALIGN_LEFT; +var HORIZONTAL_ALIGN_CENTER = 2; +exports.HORIZONTAL_ALIGN_CENTER = HORIZONTAL_ALIGN_CENTER; +var HORIZONTAL_ALIGN_RIGHT = 4; +exports.HORIZONTAL_ALIGN_RIGHT = HORIZONTAL_ALIGN_RIGHT; +var VERTICAL_ALIGN_TOP = 8; +exports.VERTICAL_ALIGN_TOP = VERTICAL_ALIGN_TOP; +var VERTICAL_ALIGN_MIDDLE = 16; +exports.VERTICAL_ALIGN_MIDDLE = VERTICAL_ALIGN_MIDDLE; +var VERTICAL_ALIGN_BOTTOM = 32; // blend modes + +exports.VERTICAL_ALIGN_BOTTOM = VERTICAL_ALIGN_BOTTOM; +var BLEND_SOURCE_OVER = 'srcOver'; +exports.BLEND_SOURCE_OVER = BLEND_SOURCE_OVER; +var BLEND_DESTINATION_OVER = 'dstOver'; +exports.BLEND_DESTINATION_OVER = BLEND_DESTINATION_OVER; +var BLEND_MULTIPLY = 'multiply'; +exports.BLEND_MULTIPLY = BLEND_MULTIPLY; +var BLEND_ADD = 'add'; +exports.BLEND_ADD = BLEND_ADD; +var BLEND_SCREEN = 'screen'; +exports.BLEND_SCREEN = BLEND_SCREEN; +var BLEND_OVERLAY = 'overlay'; +exports.BLEND_OVERLAY = BLEND_OVERLAY; +var BLEND_DARKEN = 'darken'; +exports.BLEND_DARKEN = BLEND_DARKEN; +var BLEND_LIGHTEN = 'lighten'; +exports.BLEND_LIGHTEN = BLEND_LIGHTEN; +var BLEND_HARDLIGHT = 'hardLight'; +exports.BLEND_HARDLIGHT = BLEND_HARDLIGHT; +var BLEND_DIFFERENCE = 'difference'; +exports.BLEND_DIFFERENCE = BLEND_DIFFERENCE; +var BLEND_EXCLUSION = 'exclusion'; // Edge Handling + +exports.BLEND_EXCLUSION = BLEND_EXCLUSION; +var EDGE_EXTEND = 1; +exports.EDGE_EXTEND = EDGE_EXTEND; +var EDGE_WRAP = 2; +exports.EDGE_WRAP = EDGE_WRAP; +var EDGE_CROP = 3; +exports.EDGE_CROP = EDGE_CROP; +//# sourceMappingURL=constants.js.map + +/***/ }), + +/***/ 678: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +var _interopRequireWildcard = __nccwpck_require__(4405); + +var _interopRequireDefault = __nccwpck_require__(3286); + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.addConstants = addConstants; +exports.addJimpMethods = addJimpMethods; +exports.jimpEvMethod = jimpEvMethod; +exports.jimpEvChange = jimpEvChange; +Object.defineProperty(exports, "addType", ({ + enumerable: true, + get: function get() { + return MIME.addType; } -}; +})); +exports["default"] = void 0; -function createSecureSocket(options, cb) { - var self = this; - TunnelingAgent.prototype.createSocket.call(self, options, function(socket) { - var hostHeader = options.request.getHeader('host'); - var tlsOptions = mergeOptions({}, self.options, { - socket: socket, - servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host - }); +var _construct2 = _interopRequireDefault(__nccwpck_require__(807)); - // 0 is dummy port for v0.6 - var secureSocket = tls.connect(0, tlsOptions); - self.sockets[self.sockets.indexOf(socket)] = secureSocket; - cb(secureSocket); - }); -} +var _slicedToArray2 = _interopRequireDefault(__nccwpck_require__(8209)); +var _classCallCheck2 = _interopRequireDefault(__nccwpck_require__(6383)); -function toOptions(host, port, localAddress) { - if (typeof host === 'string') { // since v0.10 - return { - host: host, - port: port, - localAddress: localAddress - }; +var _createClass2 = _interopRequireDefault(__nccwpck_require__(1957)); + +var _possibleConstructorReturn2 = _interopRequireDefault(__nccwpck_require__(6066)); + +var _getPrototypeOf2 = _interopRequireDefault(__nccwpck_require__(2369)); + +var _assertThisInitialized2 = _interopRequireDefault(__nccwpck_require__(5492)); + +var _inherits2 = _interopRequireDefault(__nccwpck_require__(2946)); + +var _defineProperty2 = _interopRequireDefault(__nccwpck_require__(1814)); + +var _typeof2 = _interopRequireDefault(__nccwpck_require__(5605)); + +var _fs = _interopRequireDefault(__nccwpck_require__(7147)); + +var _path = _interopRequireDefault(__nccwpck_require__(1017)); + +var _events = _interopRequireDefault(__nccwpck_require__(2361)); + +var _utils = __nccwpck_require__(7403); + +var _anyBase = _interopRequireDefault(__nccwpck_require__(8720)); + +var _mkdirp = _interopRequireDefault(__nccwpck_require__(6186)); + +var _pixelmatch = _interopRequireDefault(__nccwpck_require__(6097)); + +var _tinycolor = _interopRequireDefault(__nccwpck_require__(5479)); + +var _phash = _interopRequireDefault(__nccwpck_require__(7025)); + +var _request = _interopRequireDefault(__nccwpck_require__(4310)); + +var _composite = _interopRequireDefault(__nccwpck_require__(5141)); + +var _promisify = _interopRequireDefault(__nccwpck_require__(6826)); + +var MIME = _interopRequireWildcard(__nccwpck_require__(3153)); + +var _imageBitmap = __nccwpck_require__(3946); + +var constants = _interopRequireWildcard(__nccwpck_require__(4619)); + +var alphabet = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_'; // an array storing the maximum string length of hashes at various bases +// 0 and 1 do not exist as possible hash lengths + +var maxHashLength = [NaN, NaN]; + +for (var i = 2; i < 65; i++) { + var maxHash = (0, _anyBase["default"])(_anyBase["default"].BIN, alphabet.slice(0, i))(new Array(64 + 1).join('1')); + maxHashLength.push(maxHash.length); +} // no operation + + +function noop() {} // error checking methods + + +function isArrayBuffer(test) { + return Object.prototype.toString.call(test).toLowerCase().indexOf('arraybuffer') > -1; +} // Prepare a Buffer object from the arrayBuffer. Necessary in the browser > node conversion, +// But this function is not useful when running in node directly + + +function bufferFromArrayBuffer(arrayBuffer) { + var buffer = Buffer.alloc(arrayBuffer.byteLength); + var view = new Uint8Array(arrayBuffer); + + for (var _i = 0; _i < buffer.length; ++_i) { + buffer[_i] = view[_i]; } - return host; // for v0.11 or later + + return buffer; } -function mergeOptions(target) { - for (var i = 1, len = arguments.length; i < len; ++i) { - var overrides = arguments[i]; - if (typeof overrides === 'object') { - var keys = Object.keys(overrides); - for (var j = 0, keyLen = keys.length; j < keyLen; ++j) { - var k = keys[j]; - if (overrides[k] !== undefined) { - target[k] = overrides[k]; - } - } +function loadFromURL(options, cb) { + (0, _request["default"])(options, function (err, response, data) { + if (err) { + return cb(err); + } + + if ('headers' in response && 'location' in response.headers) { + options.url = response.headers.location; + return loadFromURL(options, cb); + } + + if ((0, _typeof2["default"])(data) === 'object' && Buffer.isBuffer(data)) { + return cb(null, data); } + + var msg = 'Could not load Buffer from <' + options.url + '> ' + '(HTTP: ' + response.statusCode + ')'; + return new Error(msg); + }); +} + +function loadBufferFromPath(src, cb) { + if (_fs["default"] && typeof _fs["default"].readFile === 'function' && !src.match(/^(http|ftp)s?:\/\/./)) { + _fs["default"].readFile(src, cb); + } else { + loadFromURL({ + url: src + }, cb); } - return target; } +function isRawRGBAData(obj) { + return obj && (0, _typeof2["default"])(obj) === 'object' && typeof obj.width === 'number' && typeof obj.height === 'number' && (Buffer.isBuffer(obj.data) || obj.data instanceof Uint8Array || typeof Uint8ClampedArray === 'function' && obj.data instanceof Uint8ClampedArray) && (obj.data.length === obj.width * obj.height * 4 || obj.data.length === obj.width * obj.height * 3); +} -var debug; -if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) { - debug = function() { - var args = Array.prototype.slice.call(arguments); - if (typeof args[0] === 'string') { - args[0] = 'TUNNEL: ' + args[0]; - } else { - args.unshift('TUNNEL:'); +function makeRGBABufferFromRGB(buffer) { + if (buffer.length % 3 !== 0) { + throw new Error('Buffer length is incorrect'); + } + + var rgbaBuffer = Buffer.allocUnsafe(buffer.length / 3 * 4); + var j = 0; + + for (var _i2 = 0; _i2 < buffer.length; _i2++) { + rgbaBuffer[j] = buffer[_i2]; + + if ((_i2 + 1) % 3 === 0) { + rgbaBuffer[++j] = 255; } - console.error.apply(console, args); + + j++; } -} else { - debug = function() {}; + + return rgbaBuffer; } -exports.debug = debug; // for test +var emptyBitmap = { + data: null, + width: null, + height: null +}; +/** + * Jimp constructor (from a file) + * @param path a path to the image + * @param {function(Error, Jimp)} cb (optional) a function to call when the image is parsed to a bitmap + */ -/***/ }), +/** + * Jimp constructor (from a url with options) + * @param options { url, otherOptions} + * @param {function(Error, Jimp)} cb (optional) a function to call when the image is parsed to a bitmap + */ -/***/ 491: -/***/ ((module) => { +/** + * Jimp constructor (from another Jimp image or raw image data) + * @param image a Jimp image to clone + * @param {function(Error, Jimp)} cb a function to call when the image is parsed to a bitmap + */ -"use strict"; -module.exports = require("assert"); +/** + * Jimp constructor (from a Buffer) + * @param data a Buffer containing the image data + * @param {function(Error, Jimp)} cb a function to call when the image is parsed to a bitmap + */ -/***/ }), +/** + * Jimp constructor (to generate a new image) + * @param w the width of the image + * @param h the height of the image + * @param {function(Error, Jimp)} cb (optional) a function to call when the image is parsed to a bitmap + */ -/***/ 361: -/***/ ((module) => { +/** + * Jimp constructor (to generate a new image) + * @param w the width of the image + * @param h the height of the image + * @param background color to fill the image with + * @param {function(Error, Jimp)} cb (optional) a function to call when the image is parsed to a bitmap + */ -"use strict"; -module.exports = require("events"); +var Jimp = +/*#__PURE__*/ +function (_EventEmitter) { + (0, _inherits2["default"])(Jimp, _EventEmitter); -/***/ }), + // An object representing a bitmap in memory, comprising: + // - data: a buffer of the bitmap data + // - width: the width of the image in pixels + // - height: the height of the image in pixels + // Default colour to use for new pixels + // Default MIME is PNG + // Exif data for the image + // Whether Transparency supporting formats will be exported as RGB or RGBA + function Jimp() { + var _this; -/***/ 147: -/***/ ((module) => { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } -"use strict"; -module.exports = require("fs"); + (0, _classCallCheck2["default"])(this, Jimp); + _this = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(Jimp).call(this)); + (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "bitmap", emptyBitmap); + (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "_background", 0x00000000); + (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "_originalMime", Jimp.MIME_PNG); + (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "_exif", null); + (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "_rgba", true); + (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "writeAsync", function (path) { + return (0, _promisify["default"])(_this.write, (0, _assertThisInitialized2["default"])(_this), path); + }); + (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "getBase64Async", function (mime) { + return (0, _promisify["default"])(_this.getBase64, (0, _assertThisInitialized2["default"])(_this), mime); + }); + (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "getBuffer", _imageBitmap.getBuffer); + (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "getBufferAsync", _imageBitmap.getBufferAsync); + (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "getPixelColour", _this.getPixelColor); + (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "setPixelColour", _this.setPixelColor); + var jimpInstance = (0, _assertThisInitialized2["default"])(_this); + var cb = noop; -/***/ }), + if (isArrayBuffer(args[0])) { + args[0] = bufferFromArrayBuffer(args[0]); + } -/***/ 685: -/***/ ((module) => { + function finish() { + for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } -"use strict"; -module.exports = require("http"); + var err = args[0]; + var evData = err || {}; + evData.methodName = 'constructor'; + setTimeout(function () { + var _cb; -/***/ }), + // run on next tick. + if (err && cb === noop) { + jimpInstance.emitError('constructor', err); + } else if (!err) { + jimpInstance.emitMulti('constructor', 'initialized'); + } -/***/ 687: -/***/ ((module) => { + (_cb = cb).call.apply(_cb, [jimpInstance].concat(args)); + }, 1); + } -"use strict"; -module.exports = require("https"); + if (typeof args[0] === 'number' && typeof args[1] === 'number' || parseInt(args[0], 10) && parseInt(args[1], 10)) { + // create a new image + var w = parseInt(args[0], 10); + var h = parseInt(args[1], 10); + cb = args[2]; // with a hex color -/***/ }), + if (typeof args[2] === 'number') { + _this._background = args[2]; + cb = args[3]; + } // with a css color -/***/ 808: -/***/ ((module) => { -"use strict"; -module.exports = require("net"); + if (typeof args[2] === 'string') { + _this._background = Jimp.cssColorToHex(args[2]); + cb = args[3]; + } -/***/ }), + if (typeof cb === 'undefined') { + cb = noop; + } -/***/ 37: -/***/ ((module) => { + if (typeof cb !== 'function') { + return (0, _possibleConstructorReturn2["default"])(_this, _utils.throwError.call((0, _assertThisInitialized2["default"])(_this), 'cb must be a function', finish)); + } -"use strict"; -module.exports = require("os"); + _this.bitmap = { + data: Buffer.alloc(w * h * 4), + width: w, + height: h + }; -/***/ }), + for (var _i3 = 0; _i3 < _this.bitmap.data.length; _i3 += 4) { + _this.bitmap.data.writeUInt32BE(_this._background, _i3); + } -/***/ 17: -/***/ ((module) => { + finish(null, (0, _assertThisInitialized2["default"])(_this)); + } else if ((0, _typeof2["default"])(args[0]) === 'object' && args[0].url) { + cb = args[1] || noop; -"use strict"; -module.exports = require("path"); + if (typeof cb !== 'function') { + return (0, _possibleConstructorReturn2["default"])(_this, _utils.throwError.call((0, _assertThisInitialized2["default"])(_this), 'cb must be a function', finish)); + } -/***/ }), + loadFromURL(args[0], function (err, data) { + if (err) { + return _utils.throwError.call((0, _assertThisInitialized2["default"])(_this), err, finish); + } -/***/ 404: -/***/ ((module) => { + _this.parseBitmap(data, args[0].url, finish); + }); + } else if (args[0] instanceof Jimp) { + // clone an existing Jimp + var original = args[0]; + cb = args[1]; -"use strict"; -module.exports = require("tls"); + if (typeof cb === 'undefined') { + cb = noop; + } -/***/ }), + if (typeof cb !== 'function') { + return (0, _possibleConstructorReturn2["default"])(_this, _utils.throwError.call((0, _assertThisInitialized2["default"])(_this), 'cb must be a function', finish)); + } -/***/ 837: -/***/ ((module) => { + _this.bitmap = { + data: Buffer.from(original.bitmap.data), + width: original.bitmap.width, + height: original.bitmap.height + }; + _this._quality = original._quality; + _this._deflateLevel = original._deflateLevel; + _this._deflateStrategy = original._deflateStrategy; + _this._filterType = original._filterType; + _this._rgba = original._rgba; + _this._background = original._background; + _this._originalMime = original._originalMime; + finish(null, (0, _assertThisInitialized2["default"])(_this)); + } else if (isRawRGBAData(args[0])) { + var imageData = args[0]; + cb = args[1] || noop; + var isRGBA = imageData.width * imageData.height * 4 === imageData.data.length; + var buffer = isRGBA ? Buffer.from(imageData.data) : makeRGBABufferFromRGB(imageData.data); + _this.bitmap = { + data: buffer, + width: imageData.width, + height: imageData.height + }; + finish(null, (0, _assertThisInitialized2["default"])(_this)); + } else if (typeof args[0] === 'string') { + // read from a path + var path = args[0]; + cb = args[1]; -"use strict"; -module.exports = require("util"); + if (typeof cb === 'undefined') { + cb = noop; + } + + if (typeof cb !== 'function') { + return (0, _possibleConstructorReturn2["default"])(_this, _utils.throwError.call((0, _assertThisInitialized2["default"])(_this), 'cb must be a function', finish)); + } + + loadBufferFromPath(path, function (err, data) { + if (err) { + return _utils.throwError.call((0, _assertThisInitialized2["default"])(_this), err, finish); + } + + _this.parseBitmap(data, path, finish); + }); + } else if ((0, _typeof2["default"])(args[0]) === 'object' && Buffer.isBuffer(args[0])) { + // read from a buffer + var data = args[0]; + cb = args[1]; + + if (typeof cb !== 'function') { + return (0, _possibleConstructorReturn2["default"])(_this, _utils.throwError.call((0, _assertThisInitialized2["default"])(_this), 'cb must be a function', finish)); + } + + _this.parseBitmap(data, null, finish); + } else { + // Allow client libs to add new ways to build a Jimp object. + // Extra constructors must be added by `Jimp.appendConstructorOption()` + cb = args[args.length - 1]; + + if (typeof cb !== 'function') { + // TODO: try to solve the args after cb problem. + cb = args[args.length - 2]; + + if (typeof cb !== 'function') { + cb = noop; + } + } + + var extraConstructor = Jimp.__extraConstructors.find(function (c) { + return c.test.apply(c, args); + }); + + if (extraConstructor) { + new Promise(function (resolve, reject) { + var _extraConstructor$run; + + return (_extraConstructor$run = extraConstructor.run).call.apply(_extraConstructor$run, [(0, _assertThisInitialized2["default"])(_this), resolve, reject].concat(args)); + }).then(function () { + return finish(null, (0, _assertThisInitialized2["default"])(_this)); + })["catch"](finish); + } else { + return (0, _possibleConstructorReturn2["default"])(_this, _utils.throwError.call((0, _assertThisInitialized2["default"])(_this), 'No matching constructor overloading was found. ' + 'Please see the docs for how to call the Jimp constructor.', finish)); + } + } + + return _this; + } + /** + * Parse a bitmap with the loaded image types. + * + * @param {Buffer} data raw image data + * @param {string} path optional path to file + * @param {function(Error, Jimp)} finish (optional) a callback for when complete + * @memberof Jimp + */ + + + (0, _createClass2["default"])(Jimp, [{ + key: "parseBitmap", + value: function parseBitmap(data, path, finish) { + _imageBitmap.parseBitmap.call(this, data, null, finish); + } + /** + * Sets the type of the image (RGB or RGBA) when saving in a format that supports transparency (default is RGBA) + * @param {boolean} bool A Boolean, true to use RGBA or false to use RGB + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ + + }, { + key: "rgba", + value: function rgba(bool, cb) { + if (typeof bool !== 'boolean') { + return _utils.throwError.call(this, 'bool must be a boolean, true for RGBA or false for RGB', cb); + } + + this._rgba = bool; + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(this, null, this); + } + + return this; + } + /** + * Emit for multiple listeners + * @param {string} methodName name of the method to emit an error for + * @param {string} eventName name of the eventName to emit an error for + * @param {object} data to emit + */ + + }, { + key: "emitMulti", + value: function emitMulti(methodName, eventName) { + var data = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + data = Object.assign(data, { + methodName: methodName, + eventName: eventName + }); + this.emit('any', data); + + if (methodName) { + this.emit(methodName, data); + } + + this.emit(eventName, data); + } + }, { + key: "emitError", + value: function emitError(methodName, err) { + this.emitMulti(methodName, 'error', err); + } + /** + * Get the current height of the image + * @return {number} height of the image + */ + + }, { + key: "getHeight", + value: function getHeight() { + return this.bitmap.height; + } + /** + * Get the current width of the image + * @return {number} width of the image + */ + + }, { + key: "getWidth", + value: function getWidth() { + return this.bitmap.width; + } + /** + * Nicely format Jimp object when sent to the console e.g. console.log(image) + * @returns {string} pretty printed + */ + + }, { + key: "inspect", + value: function inspect() { + return ''; + } + /** + * Nicely format Jimp object when converted to a string + * @returns {string} pretty printed + */ + + }, { + key: "toString", + value: function toString() { + return '[object Jimp]'; + } + /** + * Returns the original MIME of the image (default: "image/png") + * @returns {string} the MIME + */ + + }, { + key: "getMIME", + value: function getMIME() { + var mime = this._originalMime || Jimp.MIME_PNG; + return mime; + } + /** + * Returns the appropriate file extension for the original MIME of the image (default: "png") + * @returns {string} the file extension + */ + + }, { + key: "getExtension", + value: function getExtension() { + var mime = this.getMIME(); + return MIME.getExtension(mime); + } + /** + * Writes the image to a file + * @param {string} path a path to the destination file + * @param {function(Error, Jimp)} cb (optional) a function to call when the image is saved to disk + * @returns {Jimp} this for chaining of methods + */ + + }, { + key: "write", + value: function write(path, cb) { + var _this2 = this; + + if (!_fs["default"] || !_fs["default"].createWriteStream) { + throw new Error('Cant access the filesystem. You can use the getBase64 method.'); + } + + if (typeof path !== 'string') { + return _utils.throwError.call(this, 'path must be a string', cb); + } + + if (typeof cb === 'undefined') { + cb = noop; + } + + if (typeof cb !== 'function') { + return _utils.throwError.call(this, 'cb must be a function', cb); + } + + var mime = MIME.getType(path) || this.getMIME(); + + var pathObj = _path["default"].parse(path); + + if (pathObj.dir) { + _mkdirp["default"].sync(pathObj.dir); + } + + this.getBuffer(mime, function (err, buffer) { + if (err) { + return _utils.throwError.call(_this2, err, cb); + } + + var stream = _fs["default"].createWriteStream(path); + + stream.on('open', function () { + stream.write(buffer); + stream.end(); + }).on('error', function (err) { + return _utils.throwError.call(_this2, err, cb); + }); + stream.on('finish', function () { + cb.call(_this2, null, _this2); + }); + }); + return this; + } + }, { + key: "getBase64", + + /** + * Converts the image to a base 64 string + * @param {string} mime the mime type of the image data to be created + * @param {function(Error, Jimp)} cb a Node-style function to call with the buffer as the second argument + * @returns {Jimp} this for chaining of methods + */ + value: function getBase64(mime, cb) { + if (mime === Jimp.AUTO) { + // allow auto MIME detection + mime = this.getMIME(); + } + + if (typeof mime !== 'string') { + return _utils.throwError.call(this, 'mime must be a string', cb); + } + + if (typeof cb !== 'function') { + return _utils.throwError.call(this, 'cb must be a function', cb); + } + + this.getBuffer(mime, function (err, data) { + if (err) { + return _utils.throwError.call(this, err, cb); + } + + var src = 'data:' + mime + ';base64,' + data.toString('base64'); + cb.call(this, null, src); + }); + return this; + } + }, { + key: "hash", + + /** + * Generates a perceptual hash of the image . And pads the string. Can configure base. + * @param {number} base (optional) a number between 2 and 64 representing the base for the hash (e.g. 2 is binary, 10 is decimal, 16 is hex, 64 is base 64). Defaults to 64. + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {string} a string representing the hash + */ + value: function hash(base, cb) { + base = base || 64; + + if (typeof base === 'function') { + cb = base; + base = 64; + } + + if (typeof base !== 'number') { + return _utils.throwError.call(this, 'base must be a number', cb); + } + + if (base < 2 || base > 64) { + return _utils.throwError.call(this, 'base must be a number between 2 and 64', cb); + } + + var hash = this.pHash(); + hash = (0, _anyBase["default"])(_anyBase["default"].BIN, alphabet.slice(0, base))(hash); + + while (hash.length < maxHashLength[base]) { + hash = '0' + hash; // pad out with leading zeros + } + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(this, null, hash); + } + + return hash; + } + /** + * Calculates the perceptual hash + * @returns {number} the perceptual hash + */ + + }, { + key: "pHash", + value: function pHash() { + var pHash = new _phash["default"](); + return pHash.getHash(this); + } + /** + * Calculates the hamming distance of the current image and a hash based on their perceptual hash + * @param {hash} compareHash hash to compare to + * @returns {number} a number ranging from 0 to 1, 0 means they are believed to be identical + */ + + }, { + key: "distanceFromHash", + value: function distanceFromHash(compareHash) { + var pHash = new _phash["default"](); + var currentHash = pHash.getHash(this); + return pHash.distance(currentHash, compareHash); + } + /** + * Converts the image to a buffer + * @param {string} mime the mime type of the image buffer to be created + * @param {function(Error, Jimp)} cb a Node-style function to call with the buffer as the second argument + * @returns {Jimp} this for chaining of methods + */ + + }, { + key: "getPixelIndex", + + /** + * Returns the offset of a pixel in the bitmap buffer + * @param {number} x the x coordinate + * @param {number} y the y coordinate + * @param {string} edgeHandling (optional) define how to sum pixels from outside the border + * @param {number} cb (optional) a callback for when complete + * @returns {number} the index of the pixel or -1 if not found + */ + value: function getPixelIndex(x, y, edgeHandling, cb) { + var xi; + var yi; + + if (typeof edgeHandling === 'function' && typeof cb === 'undefined') { + cb = edgeHandling; + edgeHandling = null; + } + + if (!edgeHandling) { + edgeHandling = Jimp.EDGE_EXTEND; + } + + if (typeof x !== 'number' || typeof y !== 'number') { + return _utils.throwError.call(this, 'x and y must be numbers', cb); + } // round input + + + x = Math.round(x); + y = Math.round(y); + xi = x; + yi = y; + + if (edgeHandling === Jimp.EDGE_EXTEND) { + if (x < 0) xi = 0; + if (x >= this.bitmap.width) xi = this.bitmap.width - 1; + if (y < 0) yi = 0; + if (y >= this.bitmap.height) yi = this.bitmap.height - 1; + } + + if (edgeHandling === Jimp.EDGE_WRAP) { + if (x < 0) { + xi = this.bitmap.width + x; + } + + if (x >= this.bitmap.width) { + xi = x % this.bitmap.width; + } + + if (y < 0) { + xi = this.bitmap.height + y; + } + + if (y >= this.bitmap.height) { + yi = y % this.bitmap.height; + } + } + + var i = this.bitmap.width * yi + xi << 2; // if out of bounds index is -1 + + if (xi < 0 || xi >= this.bitmap.width) { + i = -1; + } + + if (yi < 0 || yi >= this.bitmap.height) { + i = -1; + } + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(this, null, i); + } + + return i; + } + /** + * Returns the hex colour value of a pixel + * @param {number} x the x coordinate + * @param {number} y the y coordinate + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {number} the color of the pixel + */ + + }, { + key: "getPixelColor", + value: function getPixelColor(x, y, cb) { + if (typeof x !== 'number' || typeof y !== 'number') return _utils.throwError.call(this, 'x and y must be numbers', cb); // round input + + x = Math.round(x); + y = Math.round(y); + var idx = this.getPixelIndex(x, y); + var hex = this.bitmap.data.readUInt32BE(idx); + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(this, null, hex); + } + + return hex; + } + }, { + key: "setPixelColor", + + /** + * Returns the hex colour value of a pixel + * @param {number} hex color to set + * @param {number} x the x coordinate + * @param {number} y the y coordinate + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {number} the index of the pixel or -1 if not found + */ + value: function setPixelColor(hex, x, y, cb) { + if (typeof hex !== 'number' || typeof x !== 'number' || typeof y !== 'number') return _utils.throwError.call(this, 'hex, x and y must be numbers', cb); // round input + + x = Math.round(x); + y = Math.round(y); + var idx = this.getPixelIndex(x, y); + this.bitmap.data.writeUInt32BE(hex, idx); + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(this, null, this); + } + + return this; + } + }, { + key: "hasAlpha", + + /** + * Determine if the image contains opaque pixels. + * @return {boolean} hasAlpha whether the image contains opaque pixels + */ + value: function hasAlpha() { + for (var yIndex = 0; yIndex < this.bitmap.height; yIndex++) { + for (var xIndex = 0; xIndex < this.bitmap.width; xIndex++) { + var idx = this.bitmap.width * yIndex + xIndex << 2; + var alpha = this.bitmap.data[idx + 3]; + + if (alpha !== 0xff) { + return true; + } + } + } + + return false; + } + /** + * Iterate scan through a region of the bitmap + * @param {number} x the x coordinate to begin the scan at + * @param {number} y the y coordinate to begin the scan at + * @param w the width of the scan region + * @param h the height of the scan region + * @returns {IterableIterator<{x: number, y: number, idx: number, image: Jimp}>} + */ + + }, { + key: "scanIterator", + value: function scanIterator(x, y, w, h) { + if (typeof x !== 'number' || typeof y !== 'number') { + return _utils.throwError.call(this, 'x and y must be numbers'); + } + + if (typeof w !== 'number' || typeof h !== 'number') { + return _utils.throwError.call(this, 'w and h must be numbers'); + } + + return (0, _utils.scanIterator)(this, x, y, w, h); + } + }]); + return Jimp; +}(_events["default"]); + +function addConstants(constants) { + var jimpInstance = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Jimp; + Object.entries(constants).forEach(function (_ref) { + var _ref2 = (0, _slicedToArray2["default"])(_ref, 2), + name = _ref2[0], + value = _ref2[1]; + + jimpInstance[name] = value; + }); +} + +function addJimpMethods(methods) { + var jimpInstance = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Jimp; + Object.entries(methods).forEach(function (_ref3) { + var _ref4 = (0, _slicedToArray2["default"])(_ref3, 2), + name = _ref4[0], + value = _ref4[1]; + + jimpInstance.prototype[name] = value; + }); +} + +addConstants(constants); +addJimpMethods({ + composite: _composite["default"] +}); +Jimp.__extraConstructors = []; +/** + * Allow client libs to add new ways to build a Jimp object. + * @param {string} name identify the extra constructor. + * @param {function} test a function that returns true when it accepts the arguments passed to the main constructor. + * @param {function} run where the magic happens. + */ + +Jimp.appendConstructorOption = function (name, test, run) { + Jimp.__extraConstructors.push({ + name: name, + test: test, + run: run + }); +}; +/** + * Read an image from a file or a Buffer. Takes the same args as the constructor + * @returns {Promise} a promise + */ + + +Jimp.read = function () { + for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + args[_key3] = arguments[_key3]; + } + + return new Promise(function (resolve, reject) { + (0, _construct2["default"])(Jimp, args.concat([function (err, image) { + if (err) reject(err);else resolve(image); + }])); + }); +}; + +Jimp.create = Jimp.read; +/** + * A static helper method that converts RGBA values to a single integer value + * @param {number} r the red value (0-255) + * @param {number} g the green value (0-255) + * @param {number} b the blue value (0-255) + * @param {number} a the alpha value (0-255) + * @param {function(Error, Jimp)} cb (optional) A callback for when complete + * @returns {number} an single integer colour value + */ + +Jimp.rgbaToInt = function (r, g, b, a, cb) { + if (typeof r !== 'number' || typeof g !== 'number' || typeof b !== 'number' || typeof a !== 'number') { + return _utils.throwError.call(this, 'r, g, b and a must be numbers', cb); + } + + if (r < 0 || r > 255) { + return _utils.throwError.call(this, 'r must be between 0 and 255', cb); + } + + if (g < 0 || g > 255) { + _utils.throwError.call(this, 'g must be between 0 and 255', cb); + } + + if (b < 0 || b > 255) { + return _utils.throwError.call(this, 'b must be between 0 and 255', cb); + } + + if (a < 0 || a > 255) { + return _utils.throwError.call(this, 'a must be between 0 and 255', cb); + } + + r = Math.round(r); + b = Math.round(b); + g = Math.round(g); + a = Math.round(a); + var i = r * Math.pow(256, 3) + g * Math.pow(256, 2) + b * Math.pow(256, 1) + a * Math.pow(256, 0); + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(this, null, i); + } + + return i; +}; +/** + * A static helper method that converts RGBA values to a single integer value + * @param {number} i a single integer value representing an RGBA colour (e.g. 0xFF0000FF for red) + * @param {function(Error, Jimp)} cb (optional) A callback for when complete + * @returns {object} an object with the properties r, g, b and a representing RGBA values + */ + + +Jimp.intToRGBA = function (i, cb) { + if (typeof i !== 'number') { + return _utils.throwError.call(this, 'i must be a number', cb); + } + + var rgba = {}; + rgba.r = Math.floor(i / Math.pow(256, 3)); + rgba.g = Math.floor((i - rgba.r * Math.pow(256, 3)) / Math.pow(256, 2)); + rgba.b = Math.floor((i - rgba.r * Math.pow(256, 3) - rgba.g * Math.pow(256, 2)) / Math.pow(256, 1)); + rgba.a = Math.floor((i - rgba.r * Math.pow(256, 3) - rgba.g * Math.pow(256, 2) - rgba.b * Math.pow(256, 1)) / Math.pow(256, 0)); + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(this, null, rgba); + } + + return rgba; +}; +/** + * Converts a css color (Hex, 8-digit (RGBA) Hex, RGB, RGBA, HSL, HSLA, HSV, HSVA, Named) to a hex number + * @param {string} cssColor a number + * @returns {number} a hex number representing a color + */ + + +Jimp.cssColorToHex = function (cssColor) { + cssColor = cssColor || 0; // 0, null, undefined, NaN + + if (typeof cssColor === 'number') return Number(cssColor); + return parseInt((0, _tinycolor["default"])(cssColor).toHex8(), 16); +}; +/** + * Limits a number to between 0 or 255 + * @param {number} n a number + * @returns {number} the number limited to between 0 or 255 + */ + + +Jimp.limit255 = function (n) { + n = Math.max(n, 0); + n = Math.min(n, 255); + return n; +}; +/** + * Diffs two images and returns + * @param {Jimp} img1 a Jimp image to compare + * @param {Jimp} img2 a Jimp image to compare + * @param {number} threshold (optional) a number, 0 to 1, the smaller the value the more sensitive the comparison (default: 0.1) + * @returns {object} an object { percent: percent similar, diff: a Jimp image highlighting differences } + */ + + +Jimp.diff = function (img1, img2) { + var threshold = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0.1; + if (!(img1 instanceof Jimp) || !(img2 instanceof Jimp)) return _utils.throwError.call(this, 'img1 and img2 must be an Jimp images'); + var bmp1 = img1.bitmap; + var bmp2 = img2.bitmap; + + if (bmp1.width !== bmp2.width || bmp1.height !== bmp2.height) { + if (bmp1.width * bmp1.height > bmp2.width * bmp2.height) { + // img1 is bigger + img1 = img1.cloneQuiet().resize(bmp2.width, bmp2.height); + } else { + // img2 is bigger (or they are the same in area) + img2 = img2.cloneQuiet().resize(bmp1.width, bmp1.height); + } + } + + if (typeof threshold !== 'number' || threshold < 0 || threshold > 1) { + return _utils.throwError.call(this, 'threshold must be a number between 0 and 1'); + } + + var diff = new Jimp(bmp1.width, bmp1.height, 0xffffffff); + var numDiffPixels = (0, _pixelmatch["default"])(bmp1.data, bmp2.data, diff.bitmap.data, diff.bitmap.width, diff.bitmap.height, { + threshold: threshold + }); + return { + percent: numDiffPixels / (diff.bitmap.width * diff.bitmap.height), + image: diff + }; +}; +/** + * Calculates the hamming distance of two images based on their perceptual hash + * @param {Jimp} img1 a Jimp image to compare + * @param {Jimp} img2 a Jimp image to compare + * @returns {number} a number ranging from 0 to 1, 0 means they are believed to be identical + */ + + +Jimp.distance = function (img1, img2) { + var phash = new _phash["default"](); + var hash1 = phash.getHash(img1); + var hash2 = phash.getHash(img2); + return phash.distance(hash1, hash2); +}; +/** + * Calculates the hamming distance of two images based on their perceptual hash + * @param {hash} hash1 a pHash + * @param {hash} hash2 a pHash + * @returns {number} a number ranging from 0 to 1, 0 means they are believed to be identical + */ + + +Jimp.compareHashes = function (hash1, hash2) { + var phash = new _phash["default"](); + return phash.distance(hash1, hash2); +}; +/** + * Compute color difference + * 0 means no difference, 1 means maximum difference. + * @param {number} rgba1: first color to compare. + * @param {number} rgba2: second color to compare. + * Both parameters must be an color object {r:val, g:val, b:val, a:val} + * Where `a` is optional and `val` is an integer between 0 and 255. + * @returns {number} float between 0 and 1. + */ + + +Jimp.colorDiff = function (rgba1, rgba2) { + var pow = function pow(n) { + return Math.pow(n, 2); + }; + + var max = Math.max; + var maxVal = 255 * 255 * 3; + + if (rgba1.a !== 0 && !rgba1.a) { + rgba1.a = 255; + } + + if (rgba2.a !== 0 && !rgba2.a) { + rgba2.a = 255; + } + + return (max(pow(rgba1.r - rgba2.r), pow(rgba1.r - rgba2.r - rgba1.a + rgba2.a)) + max(pow(rgba1.g - rgba2.g), pow(rgba1.g - rgba2.g - rgba1.a + rgba2.a)) + max(pow(rgba1.b - rgba2.b), pow(rgba1.b - rgba2.b - rgba1.a + rgba2.a))) / maxVal; +}; +/** + * Helper to create Jimp methods that emit events before and after its execution. + * @param {string} methodName The name to be appended to Jimp prototype. + * @param {string} evName The event name to be called. + * It will be prefixed by `before-` and emitted when on method call. + * It will be appended by `ed` and emitted after the method run. + * @param {function} method A function implementing the method itself. + * It will also create a quiet version that will not emit events, to not + * mess the user code with many `changed` event calls. You can call with + * `methodName + "Quiet"`. + * + * The emitted event comes with a object parameter to the listener with the + * `methodName` as one attribute. + */ + + +function jimpEvMethod(methodName, evName, method) { + var evNameBefore = 'before-' + evName; + var evNameAfter = evName.replace(/e$/, '') + 'ed'; + + Jimp.prototype[methodName] = function () { + var wrappedCb; + + for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { + args[_key4] = arguments[_key4]; + } + + var cb = args[method.length - 1]; + var jimpInstance = this; + + if (typeof cb === 'function') { + wrappedCb = function wrappedCb() { + for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { + args[_key5] = arguments[_key5]; + } + + var err = args[0], + data = args[1]; + + if (err) { + jimpInstance.emitError(methodName, err); + } else { + jimpInstance.emitMulti(methodName, evNameAfter, (0, _defineProperty2["default"])({}, methodName, data)); + } + + cb.apply(this, args); + }; + + args[args.length - 1] = wrappedCb; + } else { + wrappedCb = false; + } + + this.emitMulti(methodName, evNameBefore); + var result; + + try { + result = method.apply(this, args); + + if (!wrappedCb) { + this.emitMulti(methodName, evNameAfter, (0, _defineProperty2["default"])({}, methodName, result)); + } + } catch (error) { + error.methodName = methodName; + this.emitError(methodName, error); + } + + return result; + }; + + Jimp.prototype[methodName + 'Quiet'] = method; +} +/** + * Creates a new image that is a clone of this one. + * @param {function(Error, Jimp)} cb (optional) A callback for when complete + * @returns the new image + */ + + +jimpEvMethod('clone', 'clone', function (cb) { + var clone = new Jimp(this); + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(clone, null, clone); + } + + return clone; +}); +/** + * Simplify jimpEvMethod call for the common `change` evName. + * @param {string} methodName name of the method + * @param {function} method to watch changes for + */ + +function jimpEvChange(methodName, method) { + jimpEvMethod(methodName, 'change', method); +} +/** + * Sets the type of the image (RGB or RGBA) when saving as PNG format (default is RGBA) + * @param b A Boolean, true to use RGBA or false to use RGB + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ + + +jimpEvChange('background', function (hex, cb) { + if (typeof hex !== 'number') { + return _utils.throwError.call(this, 'hex must be a hexadecimal rgba value', cb); + } + + this._background = hex; + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(this, null, this); + } + + return this; +}); +/** + * Scans through a region of the bitmap, calling a function for each pixel. + * @param {number} x the x coordinate to begin the scan at + * @param {number} y the y coordinate to begin the scan at + * @param w the width of the scan region + * @param h the height of the scan region + * @param f a function to call on even pixel; the (x, y) position of the pixel + * and the index of the pixel in the bitmap buffer are passed to the function + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ + +jimpEvChange('scan', function (x, y, w, h, f, cb) { + if (typeof x !== 'number' || typeof y !== 'number') { + return _utils.throwError.call(this, 'x and y must be numbers', cb); + } + + if (typeof w !== 'number' || typeof h !== 'number') { + return _utils.throwError.call(this, 'w and h must be numbers', cb); + } + + if (typeof f !== 'function') { + return _utils.throwError.call(this, 'f must be a function', cb); + } + + var result = (0, _utils.scan)(this, x, y, w, h, f); + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(this, null, result); + } + + return result; +}); + +if (process.env.ENVIRONMENT === 'BROWSER') { + // For use in a web browser or web worker + + /* global self */ + var gl; + + if (typeof window !== 'undefined' && (typeof window === "undefined" ? "undefined" : (0, _typeof2["default"])(window)) === 'object') { + gl = window; + } + + if (typeof self !== 'undefined' && (typeof self === "undefined" ? "undefined" : (0, _typeof2["default"])(self)) === 'object') { + gl = self; + } + + gl.Jimp = Jimp; + gl.Buffer = Buffer; +} + +var _default = Jimp; +exports["default"] = _default; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 7025: +/***/ ((module) => { + +"use strict"; + + +/* +Copyright (c) 2011 Elliot Shepherd + +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. +*/ +// https://code.google.com/p/ironchef-team21/source/browse/ironchef_team21/src/ImagePHash.java + +/* + * pHash-like image hash. + * Author: Elliot Shepherd (elliot@jarofworms.com + * Based On: http://www.hackerfactor.com/blog/index.php?/archives/432-Looks-Like-It.html + */ +function ImagePHash(size, smallerSize) { + this.size = this.size || size; + this.smallerSize = this.smallerSize || smallerSize; + initCoefficients(this.size); +} + +ImagePHash.prototype.size = 32; +ImagePHash.prototype.smallerSize = 8; + +ImagePHash.prototype.distance = function (s1, s2) { + var counter = 0; + + for (var k = 0; k < s1.length; k++) { + if (s1[k] !== s2[k]) { + counter++; + } + } + + return counter / s1.length; +}; // Returns a 'binary string' (like. 001010111011100010) which is easy to do a hamming distance on. + + +ImagePHash.prototype.getHash = function (img) { + /* 1. Reduce size. + * Like Average Hash, pHash starts with a small image. + * However, the image is larger than 8x8; 32x32 is a good size. + * This is really done to simplify the DCT computation and not + * because it is needed to reduce the high frequencies. + */ + img = img.clone().resize(this.size, this.size); + /* 2. Reduce color. + * The image is reduced to a grayscale just to further simplify + * the number of computations. + */ + + img.grayscale(); + var vals = []; + + for (var x = 0; x < img.bitmap.width; x++) { + vals[x] = []; + + for (var y = 0; y < img.bitmap.height; y++) { + vals[x][y] = intToRGBA(img.getPixelColor(x, y)).b; + } + } + /* 3. Compute the DCT. + * The DCT separates the image into a collection of frequencies + * and scalars. While JPEG uses an 8x8 DCT, this algorithm uses + * a 32x32 DCT. + */ + + + var dctVals = applyDCT(vals, this.size); + /* 4. Reduce the DCT. + * This is the magic step. While the DCT is 32x32, just keep the + * top-left 8x8. Those represent the lowest frequencies in the + * picture. + */ + + /* 5. Compute the average value. + * Like the Average Hash, compute the mean DCT value (using only + * the 8x8 DCT low-frequency values and excluding the first term + * since the DC coefficient can be significantly different from + * the other values and will throw off the average). + */ + + var total = 0; + + for (var _x = 0; _x < this.smallerSize; _x++) { + for (var _y = 0; _y < this.smallerSize; _y++) { + total += dctVals[_x][_y]; + } + } + + var avg = total / (this.smallerSize * this.smallerSize); + /* 6. Further reduce the DCT. + * This is the magic step. Set the 64 hash bits to 0 or 1 + * depending on whether each of the 64 DCT values is above or + * below the average value. The result doesn't tell us the + * actual low frequencies; it just tells us the very-rough + * relative scale of the frequencies to the mean. The result + * will not vary as long as the overall structure of the image + * remains the same; this can survive gamma and color histogram + * adjustments without a problem. + */ + + var hash = ''; + + for (var _x2 = 0; _x2 < this.smallerSize; _x2++) { + for (var _y2 = 0; _y2 < this.smallerSize; _y2++) { + hash += dctVals[_x2][_y2] > avg ? '1' : '0'; + } + } + + return hash; +}; // DCT function stolen from http://stackoverflow.com/questions/4240490/problems-with-dct-and-idct-algorithm-in-java + + +function intToRGBA(i) { + var rgba = {}; + rgba.r = Math.floor(i / Math.pow(256, 3)); + rgba.g = Math.floor((i - rgba.r * Math.pow(256, 3)) / Math.pow(256, 2)); + rgba.b = Math.floor((i - rgba.r * Math.pow(256, 3) - rgba.g * Math.pow(256, 2)) / Math.pow(256, 1)); + rgba.a = Math.floor((i - rgba.r * Math.pow(256, 3) - rgba.g * Math.pow(256, 2) - rgba.b * Math.pow(256, 1)) / Math.pow(256, 0)); + return rgba; +} + +var c = []; + +function initCoefficients(size) { + for (var i = 1; i < size; i++) { + c[i] = 1; + } + + c[0] = 1 / Math.sqrt(2.0); +} + +function applyDCT(f, size) { + var N = size; + var F = []; + + for (var u = 0; u < N; u++) { + F[u] = []; + + for (var v = 0; v < N; v++) { + var sum = 0; + + for (var i = 0; i < N; i++) { + for (var j = 0; j < N; j++) { + sum += Math.cos((2 * i + 1) / (2.0 * N) * u * Math.PI) * Math.cos((2 * j + 1) / (2.0 * N) * v * Math.PI) * f[i][j]; + } + } + + sum *= c[u] * c[v] / 4; + F[u][v] = sum; + } + } + + return F; +} + +module.exports = ImagePHash; +//# sourceMappingURL=phash.js.map + +/***/ }), + +/***/ 4310: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var _interopRequireDefault = __nccwpck_require__(3286); + +var _defineProperty2 = _interopRequireDefault(__nccwpck_require__(1814)); + +var _extends2 = _interopRequireDefault(__nccwpck_require__(7299)); + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +/* global XMLHttpRequest */ +if (process.browser || process.env.ENVIRONMENT === 'BROWSER' || typeof process.versions.electron !== 'undefined' && process.type === 'renderer' && typeof XMLHttpRequest === 'function') { + // If we run into a browser or the electron renderer process, + // use XHR method instead of Request node module. + module.exports = function (options, cb) { + var xhr = new XMLHttpRequest(); + xhr.open('GET', options.url, true); + xhr.responseType = 'arraybuffer'; + xhr.addEventListener('load', function () { + if (xhr.status < 400) { + try { + var data = Buffer.from(this.response); + cb(null, xhr, data); + } catch (error) { + return cb(new Error('Response is not a buffer for url ' + options.url + '. Error: ' + error.message)); + } + } else { + cb(new Error('HTTP Status ' + xhr.status + ' for url ' + options.url)); + } + }); + xhr.addEventListener('error', function (e) { + cb(e); + }); + xhr.send(); + }; +} else { + module.exports = function (_ref, cb) { + var options = (0, _extends2["default"])({}, _ref); + + var p = __nccwpck_require__(6130); + + p(_objectSpread({ + compression: true + }, options), function (err, res) { + if (err === null) { + cb(null, res, res.body); + } else { + cb(err); + } + }); + }; +} +//# sourceMappingURL=request.js.map + +/***/ }), + +/***/ 3946: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +var _interopRequireWildcard = __nccwpck_require__(4405); + +var _interopRequireDefault = __nccwpck_require__(3286); + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.parseBitmap = parseBitmap; +exports.getBuffer = getBuffer; +exports.getBufferAsync = getBufferAsync; + +var _slicedToArray2 = _interopRequireDefault(__nccwpck_require__(8209)); + +var _fileType = _interopRequireDefault(__nccwpck_require__(4930)); + +var _exifParser = _interopRequireDefault(__nccwpck_require__(6621)); + +var _utils = __nccwpck_require__(7403); + +var constants = _interopRequireWildcard(__nccwpck_require__(4619)); + +var MIME = _interopRequireWildcard(__nccwpck_require__(3153)); + +var _promisify = _interopRequireDefault(__nccwpck_require__(6826)); + +function getMIMEFromBuffer(buffer, path) { + var fileTypeFromBuffer = (0, _fileType["default"])(buffer); + + if (fileTypeFromBuffer) { + // If fileType returns something for buffer, then return the mime given + return fileTypeFromBuffer.mime; + } + + if (path) { + // If a path is supplied, and fileType yields no results, then retry with MIME + // Path can be either a file path or a url + return MIME.getType(path); + } + + return null; +} +/* + * Obtains image orientation from EXIF metadata. + * + * @param img {Jimp} a Jimp image object + * @returns {number} a number 1-8 representing EXIF orientation, + * in particular 1 if orientation tag is missing + */ + + +function getExifOrientation(img) { + return img._exif && img._exif.tags && img._exif.tags.Orientation || 1; +} +/** + * Returns a function which translates EXIF-rotated coordinates into + * non-rotated ones. + * + * Transformation reference: http://sylvana.net/jpegcrop/exif_orientation.html. + * + * @param img {Jimp} a Jimp image object + * @returns {function} transformation function for transformBitmap(). + */ + + +function getExifOrientationTransformation(img) { + var w = img.getWidth(); + var h = img.getHeight(); + + switch (getExifOrientation(img)) { + case 1: + // Horizontal (normal) + // does not need to be supported here + return null; + + case 2: + // Mirror horizontal + return function (x, y) { + return [w - x - 1, y]; + }; + + case 3: + // Rotate 180 + return function (x, y) { + return [w - x - 1, h - y - 1]; + }; + + case 4: + // Mirror vertical + return function (x, y) { + return [x, h - y - 1]; + }; + + case 5: + // Mirror horizontal and rotate 270 CW + return function (x, y) { + return [y, x]; + }; + + case 6: + // Rotate 90 CW + return function (x, y) { + return [y, h - x - 1]; + }; + + case 7: + // Mirror horizontal and rotate 90 CW + return function (x, y) { + return [w - y - 1, h - x - 1]; + }; + + case 8: + // Rotate 270 CW + return function (x, y) { + return [w - y - 1, x]; + }; + + default: + return null; + } +} +/* + * Transforms bitmap in place (moves pixels around) according to given + * transformation function. + * + * @param img {Jimp} a Jimp image object, which bitmap is supposed to + * be transformed + * @param width {number} bitmap width after the transformation + * @param height {number} bitmap height after the transformation + * @param transformation {function} transformation function which defines pixel + * mapping between new and source bitmap. It takes a pair of coordinates + * in the target, and returns a respective pair of coordinates in + * the source bitmap, i.e. has following form: + * `function(new_x, new_y) { return [src_x, src_y] }`. + */ + + +function transformBitmap(img, width, height, transformation) { + // Underscore-prefixed values are related to the source bitmap + // Their counterparts with no prefix are related to the target bitmap + var _data = img.bitmap.data; + var _width = img.bitmap.width; + var data = Buffer.alloc(_data.length); + + for (var x = 0; x < width; x++) { + for (var y = 0; y < height; y++) { + var _transformation = transformation(x, y), + _transformation2 = (0, _slicedToArray2["default"])(_transformation, 2), + _x = _transformation2[0], + _y = _transformation2[1]; + + var idx = width * y + x << 2; + + var _idx = _width * _y + _x << 2; + + var pixel = _data.readUInt32BE(_idx); + + data.writeUInt32BE(pixel, idx); + } + } + + img.bitmap.data = data; + img.bitmap.width = width; + img.bitmap.height = height; +} +/* + * Automagically rotates an image based on its EXIF data (if present). + * @param img {Jimp} a Jimp image object + */ + + +function exifRotate(img) { + if (getExifOrientation(img) < 2) return; + var transformation = getExifOrientationTransformation(img); + var swapDimensions = getExifOrientation(img) > 4; + var newWidth = swapDimensions ? img.bitmap.height : img.bitmap.width; + var newHeight = swapDimensions ? img.bitmap.width : img.bitmap.height; + transformBitmap(img, newWidth, newHeight, transformation); +} // parses a bitmap from the constructor to the JIMP bitmap property + + +function parseBitmap(data, path, cb) { + var mime = getMIMEFromBuffer(data, path); + + if (typeof mime !== 'string') { + return cb(new Error('Could not find MIME for Buffer <' + path + '>')); + } + + this._originalMime = mime.toLowerCase(); + + try { + var _mime = this.getMIME(); + + if (this.constructor.decoders[_mime]) { + this.bitmap = this.constructor.decoders[_mime](data); + } else { + return _utils.throwError.call(this, 'Unsupported MIME type: ' + _mime, cb); + } + } catch (error) { + return cb.call(this, error, this); + } + + try { + this._exif = _exifParser["default"].create(data).parse(); + exifRotate(this); // EXIF data + } catch (error) { + /* meh */ + } + + cb.call(this, null, this); + return this; +} + +function compositeBitmapOverBackground(Jimp, image) { + return new Jimp(image.bitmap.width, image.bitmap.height, image._background).composite(image, 0, 0).bitmap; +} +/** + * Converts the image to a buffer + * @param {string} mime the mime type of the image buffer to be created + * @param {function(Error, Jimp)} cb a Node-style function to call with the buffer as the second argument + * @returns {Jimp} this for chaining of methods + */ + + +function getBuffer(mime, cb) { + if (mime === constants.AUTO) { + // allow auto MIME detection + mime = this.getMIME(); + } + + if (typeof mime !== 'string') { + return _utils.throwError.call(this, 'mime must be a string', cb); + } + + if (typeof cb !== 'function') { + return _utils.throwError.call(this, 'cb must be a function', cb); + } + + mime = mime.toLowerCase(); + + if (this._rgba && this.constructor.hasAlpha[mime]) { + this.bitmap.data = Buffer.from(this.bitmap.data); + } else { + // when format doesn't support alpha + // composite onto a new image so that the background shows through alpha channels + this.bitmap.data = compositeBitmapOverBackground(this.constructor, this).data; + } + + if (this.constructor.encoders[mime]) { + var buffer = this.constructor.encoders[mime](this); + cb.call(this, null, buffer); + } else { + cb.call(this, 'Unsupported MIME type: ' + mime); + } + + return this; +} + +function getBufferAsync(mime) { + return (0, _promisify["default"])(getBuffer, this, mime); +} +//# sourceMappingURL=image-bitmap.js.map + +/***/ }), + +/***/ 3153: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.getExtension = exports.getType = exports.addType = void 0; +var mimeTypes = {}; + +var findType = function findType(extension) { + return Object.entries(mimeTypes).find(function (type) { + return type[1].includes(extension); + }) || []; +}; + +var addType = function addType(mime, extensions) { + mimeTypes[mime] = extensions; +}; +/** + * Lookup a mime type based on extension + * @param {string} path path to find extension for + * @returns {string} mime found mime type + */ + + +exports.addType = addType; + +var getType = function getType(path) { + var pathParts = path.split('/').slice(-1); + var extension = pathParts[pathParts.length - 1].split('.').pop(); + var type = findType(extension); + return type[0]; +}; +/** + * Return file extension associated with a mime type + * @param {string} type mime type to look up + * @returns {string} extension file extension + */ + + +exports.getType = getType; + +var getExtension = function getExtension(type) { + return (mimeTypes[type.toLowerCase()] || [])[0]; +}; + +exports.getExtension = getExtension; +//# sourceMappingURL=mime.js.map + +/***/ }), + +/***/ 6826: +/***/ ((module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var promisify = function promisify(fun, ctx) { + for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { + args[_key - 2] = arguments[_key]; + } + + return new Promise(function (resolve, reject) { + args.push(function (err, data) { + if (err) { + reject(err); + } + + resolve(data); + }); + fun.bind(ctx).apply(void 0, args); + }); +}; + +var _default = promisify; +exports["default"] = _default; +module.exports = exports.default; +//# sourceMappingURL=promisify.js.map + +/***/ }), + +/***/ 9472: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +var _interopRequireWildcard = __nccwpck_require__(4405); + +var _interopRequireDefault = __nccwpck_require__(3286); + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = configure; + +var _toConsumableArray2 = _interopRequireDefault(__nccwpck_require__(3195)); + +var _defineProperty2 = _interopRequireDefault(__nccwpck_require__(1814)); + +var _slicedToArray2 = _interopRequireDefault(__nccwpck_require__(8209)); + +var _core = _interopRequireWildcard(__nccwpck_require__(678)); + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function configure(configuration) { + var jimpInstance = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _core["default"]; + var jimpConfig = { + hasAlpha: {}, + encoders: {}, + decoders: {}, + "class": {}, + constants: {} + }; + + function addToConfig(newConfig) { + Object.entries(newConfig).forEach(function (_ref) { + var _ref2 = (0, _slicedToArray2["default"])(_ref, 2), + key = _ref2[0], + value = _ref2[1]; + + jimpConfig[key] = _objectSpread({}, jimpConfig[key], {}, value); + }); + } + + function addImageType(typeModule) { + var type = typeModule(); + + if (Array.isArray(type.mime)) { + _core.addType.apply(void 0, (0, _toConsumableArray2["default"])(type.mime)); + } else { + Object.entries(type.mime).forEach(function (mimeType) { + return _core.addType.apply(void 0, (0, _toConsumableArray2["default"])(mimeType)); + }); + } + + delete type.mime; + addToConfig(type); + } + + function addPlugin(pluginModule) { + var plugin = pluginModule(_core.jimpEvChange) || {}; + + if (!plugin["class"] && !plugin.constants) { + // Default to class function + addToConfig({ + "class": plugin + }); + } else { + addToConfig(plugin); + } + } + + if (configuration.types) { + configuration.types.forEach(addImageType); + jimpInstance.decoders = _objectSpread({}, jimpInstance.decoders, {}, jimpConfig.decoders); + jimpInstance.encoders = _objectSpread({}, jimpInstance.encoders, {}, jimpConfig.encoders); + jimpInstance.hasAlpha = _objectSpread({}, jimpInstance.hasAlpha, {}, jimpConfig.hasAlpha); + } + + if (configuration.plugins) { + configuration.plugins.forEach(addPlugin); + } + + (0, _core.addJimpMethods)(jimpConfig["class"], jimpInstance); + (0, _core.addConstants)(jimpConfig.constants, jimpInstance); + return _core["default"]; +} + +module.exports = exports.default; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 8257: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +var _interopRequireDefault = __nccwpck_require__(3286); + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _defineProperty2 = _interopRequireDefault(__nccwpck_require__(1814)); + +var _omggif = _interopRequireDefault(__nccwpck_require__(9717)); + +var _gifwrap = __nccwpck_require__(7304); + +var MIME_TYPE = 'image/gif'; + +var _default = function _default() { + return { + mime: (0, _defineProperty2["default"])({}, MIME_TYPE, ['gif']), + constants: { + MIME_GIF: MIME_TYPE + }, + decoders: (0, _defineProperty2["default"])({}, MIME_TYPE, function (data) { + var gifObj = new _omggif["default"].GifReader(data); + var gifData = Buffer.alloc(gifObj.width * gifObj.height * 4); + gifObj.decodeAndBlitFrameRGBA(0, gifData); + return { + data: gifData, + width: gifObj.width, + height: gifObj.height + }; + }), + encoders: (0, _defineProperty2["default"])({}, MIME_TYPE, function (data) { + var bitmap = new _gifwrap.BitmapImage(data.bitmap); + + _gifwrap.GifUtil.quantizeDekker(bitmap, 256); + + var newFrame = new _gifwrap.GifFrame(bitmap); + var gifCodec = new _gifwrap.GifCodec(); + return gifCodec.encodeGif([newFrame], {}).then(function (newGif) { + return newGif.buffer; + }); + }) + }; +}; + +exports["default"] = _default; +module.exports = exports.default; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 5177: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +var _interopRequireDefault = __nccwpck_require__(3286); + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _defineProperty2 = _interopRequireDefault(__nccwpck_require__(1814)); + +var _jpegJs = _interopRequireDefault(__nccwpck_require__(8541)); + +var _utils = __nccwpck_require__(7403); + +var MIME_TYPE = 'image/jpeg'; + +var _default = function _default() { + return { + mime: (0, _defineProperty2["default"])({}, MIME_TYPE, ['jpeg', 'jpg', 'jpe']), + constants: { + MIME_JPEG: MIME_TYPE + }, + decoders: (0, _defineProperty2["default"])({}, MIME_TYPE, _jpegJs["default"].decode), + encoders: (0, _defineProperty2["default"])({}, MIME_TYPE, function (image) { + return _jpegJs["default"].encode(image.bitmap, image._quality).data; + }), + "class": { + // The quality to be used when saving JPEG images + _quality: 100, + + /** + * Sets the quality of the image when saving as JPEG format (default is 100) + * @param {number} n The quality to use 0-100 + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ + quality: function quality(n, cb) { + if (typeof n !== 'number') { + return _utils.throwError.call(this, 'n must be a number', cb); + } + + if (n < 0 || n > 100) { + return _utils.throwError.call(this, 'n must be a number 0 - 100', cb); + } + + this._quality = Math.round(n); + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(this, null, this); + } + + return this; + } + } + }; +}; + +exports["default"] = _default; +module.exports = exports.default; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 1485: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +var _interopRequireDefault = __nccwpck_require__(3286); + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _typeof2 = _interopRequireDefault(__nccwpck_require__(5605)); + +var _utils = __nccwpck_require__(7403); + +var _default = function _default() { + return { + /** + * Blits a source image on to this image + * @param {Jimp} src the source Jimp instance + * @param {number} x the x position to blit the image + * @param {number} y the y position to blit the image + * @param {number} srcx (optional) the x position from which to crop the source image + * @param {number} srcy (optional) the y position from which to crop the source image + * @param {number} srcw (optional) the width to which to crop the source image + * @param {number} srch (optional) the height to which to crop the source image + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ + blit: function blit(src, x, y, srcx, srcy, srcw, srch, cb) { + if (!(src instanceof this.constructor)) { + return _utils.throwError.call(this, 'The source must be a Jimp image', cb); + } + + if (typeof x !== 'number' || typeof y !== 'number') { + return _utils.throwError.call(this, 'x and y must be numbers', cb); + } + + if (typeof srcx === 'function') { + cb = srcx; + srcx = 0; + srcy = 0; + srcw = src.bitmap.width; + srch = src.bitmap.height; + } else if ((0, _typeof2["default"])(srcx) === (0, _typeof2["default"])(srcy) && (0, _typeof2["default"])(srcy) === (0, _typeof2["default"])(srcw) && (0, _typeof2["default"])(srcw) === (0, _typeof2["default"])(srch)) { + srcx = srcx || 0; + srcy = srcy || 0; + srcw = srcw || src.bitmap.width; + srch = srch || src.bitmap.height; + } else { + return _utils.throwError.call(this, 'srcx, srcy, srcw, srch must be numbers', cb); + } // round input + + + x = Math.round(x); + y = Math.round(y); // round input + + srcx = Math.round(srcx); + srcy = Math.round(srcy); + srcw = Math.round(srcw); + srch = Math.round(srch); + var maxWidth = this.bitmap.width; + var maxHeight = this.bitmap.height; + var baseImage = this; + src.scanQuiet(srcx, srcy, srcw, srch, function (sx, sy, idx) { + var xOffset = x + sx - srcx; + var yOffset = y + sy - srcy; + + if (xOffset >= 0 && yOffset >= 0 && maxWidth - xOffset > 0 && maxHeight - yOffset > 0) { + var dstIdx = baseImage.getPixelIndex(xOffset, yOffset); + var _src = { + r: this.bitmap.data[idx], + g: this.bitmap.data[idx + 1], + b: this.bitmap.data[idx + 2], + a: this.bitmap.data[idx + 3] + }; + var dst = { + r: baseImage.bitmap.data[dstIdx], + g: baseImage.bitmap.data[dstIdx + 1], + b: baseImage.bitmap.data[dstIdx + 2], + a: baseImage.bitmap.data[dstIdx + 3] + }; + baseImage.bitmap.data[dstIdx] = (_src.a * (_src.r - dst.r) - dst.r + 255 >> 8) + dst.r; + baseImage.bitmap.data[dstIdx + 1] = (_src.a * (_src.g - dst.g) - dst.g + 255 >> 8) + dst.g; + baseImage.bitmap.data[dstIdx + 2] = (_src.a * (_src.b - dst.b) - dst.b + 255 >> 8) + dst.b; + baseImage.bitmap.data[dstIdx + 3] = this.constructor.limit255(dst.a + _src.a); + } + }); + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(this, null, this); + } + + return this; + } + }; +}; + +exports["default"] = _default; +module.exports = exports.default; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 5803: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.shgTable = exports.mulTable = void 0; +var mulTable = [1, 57, 41, 21, 203, 34, 97, 73, 227, 91, 149, 62, 105, 45, 39, 137, 241, 107, 3, 173, 39, 71, 65, 238, 219, 101, 187, 87, 81, 151, 141, 133, 249, 117, 221, 209, 197, 187, 177, 169, 5, 153, 73, 139, 133, 127, 243, 233, 223, 107, 103, 99, 191, 23, 177, 171, 165, 159, 77, 149, 9, 139, 135, 131, 253, 245, 119, 231, 224, 109, 211, 103, 25, 195, 189, 23, 45, 175, 171, 83, 81, 79, 155, 151, 147, 9, 141, 137, 67, 131, 129, 251, 123, 30, 235, 115, 113, 221, 217, 53, 13, 51, 50, 49, 193, 189, 185, 91, 179, 175, 43, 169, 83, 163, 5, 79, 155, 19, 75, 147, 145, 143, 35, 69, 17, 67, 33, 65, 255, 251, 247, 243, 239, 59, 29, 229, 113, 111, 219, 27, 213, 105, 207, 51, 201, 199, 49, 193, 191, 47, 93, 183, 181, 179, 11, 87, 43, 85, 167, 165, 163, 161, 159, 157, 155, 77, 19, 75, 37, 73, 145, 143, 141, 35, 138, 137, 135, 67, 33, 131, 129, 255, 63, 250, 247, 61, 121, 239, 237, 117, 29, 229, 227, 225, 111, 55, 109, 216, 213, 211, 209, 207, 205, 203, 201, 199, 197, 195, 193, 48, 190, 47, 93, 185, 183, 181, 179, 178, 176, 175, 173, 171, 85, 21, 167, 165, 41, 163, 161, 5, 79, 157, 78, 154, 153, 19, 75, 149, 74, 147, 73, 144, 143, 71, 141, 140, 139, 137, 17, 135, 134, 133, 66, 131, 65, 129, 1]; +exports.mulTable = mulTable; +var shgTable = [0, 9, 10, 10, 14, 12, 14, 14, 16, 15, 16, 15, 16, 15, 15, 17, 18, 17, 12, 18, 16, 17, 17, 19, 19, 18, 19, 18, 18, 19, 19, 19, 20, 19, 20, 20, 20, 20, 20, 20, 15, 20, 19, 20, 20, 20, 21, 21, 21, 20, 20, 20, 21, 18, 21, 21, 21, 21, 20, 21, 17, 21, 21, 21, 22, 22, 21, 22, 22, 21, 22, 21, 19, 22, 22, 19, 20, 22, 22, 21, 21, 21, 22, 22, 22, 18, 22, 22, 21, 22, 22, 23, 22, 20, 23, 22, 22, 23, 23, 21, 19, 21, 21, 21, 23, 23, 23, 22, 23, 23, 21, 23, 22, 23, 18, 22, 23, 20, 22, 23, 23, 23, 21, 22, 20, 22, 21, 22, 24, 24, 24, 24, 24, 22, 21, 24, 23, 23, 24, 21, 24, 23, 24, 22, 24, 24, 22, 24, 24, 22, 23, 24, 24, 24, 20, 23, 22, 23, 24, 24, 24, 24, 24, 24, 24, 23, 21, 23, 22, 23, 24, 24, 24, 22, 24, 24, 24, 23, 22, 24, 24, 25, 23, 25, 25, 23, 24, 25, 25, 24, 22, 25, 25, 25, 24, 23, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 23, 25, 23, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 24, 22, 25, 25, 23, 25, 25, 20, 24, 25, 24, 25, 25, 22, 24, 25, 24, 25, 24, 25, 25, 24, 25, 25, 25, 25, 22, 25, 25, 25, 24, 25, 24, 25, 18]; +exports.shgTable = shgTable; +//# sourceMappingURL=blur-tables.js.map + +/***/ }), + +/***/ 6223: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _utils = __nccwpck_require__(7403); + +var _blurTables = __nccwpck_require__(5803); + +/* + Superfast Blur (0.5) + http://www.quasimondo.com/BoxBlurForCanvas/FastBlur.js + + Copyright (c) 2011 Mario Klingemann + + 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 _default = function _default() { + return { + /** + * A fast blur algorithm that produces similar effect to a Gaussian blur - but MUCH quicker + * @param {number} r the pixel radius of the blur + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ + blur: function blur(r, cb) { + if (typeof r !== 'number') return _utils.throwError.call(this, 'r must be a number', cb); + if (r < 1) return _utils.throwError.call(this, 'r must be greater than 0', cb); + var rsum; + var gsum; + var bsum; + var asum; + var x; + var y; + var i; + var p; + var p1; + var p2; + var yp; + var yi; + var yw; + var pa; + var wm = this.bitmap.width - 1; + var hm = this.bitmap.height - 1; // const wh = this.bitmap.width * this.bitmap.height; + + var rad1 = r + 1; + var mulSum = _blurTables.mulTable[r]; + var shgSum = _blurTables.shgTable[r]; + var red = []; + var green = []; + var blue = []; + var alpha = []; + var vmin = []; + var vmax = []; + var iterations = 2; + + while (iterations-- > 0) { + yi = 0; + yw = 0; + + for (y = 0; y < this.bitmap.height; y++) { + rsum = this.bitmap.data[yw] * rad1; + gsum = this.bitmap.data[yw + 1] * rad1; + bsum = this.bitmap.data[yw + 2] * rad1; + asum = this.bitmap.data[yw + 3] * rad1; + + for (i = 1; i <= r; i++) { + p = yw + ((i > wm ? wm : i) << 2); + rsum += this.bitmap.data[p++]; + gsum += this.bitmap.data[p++]; + bsum += this.bitmap.data[p++]; + asum += this.bitmap.data[p]; + } + + for (x = 0; x < this.bitmap.width; x++) { + red[yi] = rsum; + green[yi] = gsum; + blue[yi] = bsum; + alpha[yi] = asum; + + if (y === 0) { + vmin[x] = ((p = x + rad1) < wm ? p : wm) << 2; + vmax[x] = (p = x - r) > 0 ? p << 2 : 0; + } + + p1 = yw + vmin[x]; + p2 = yw + vmax[x]; + rsum += this.bitmap.data[p1++] - this.bitmap.data[p2++]; + gsum += this.bitmap.data[p1++] - this.bitmap.data[p2++]; + bsum += this.bitmap.data[p1++] - this.bitmap.data[p2++]; + asum += this.bitmap.data[p1] - this.bitmap.data[p2]; + yi++; + } + + yw += this.bitmap.width << 2; + } + + for (x = 0; x < this.bitmap.width; x++) { + yp = x; + rsum = red[yp] * rad1; + gsum = green[yp] * rad1; + bsum = blue[yp] * rad1; + asum = alpha[yp] * rad1; + + for (i = 1; i <= r; i++) { + yp += i > hm ? 0 : this.bitmap.width; + rsum += red[yp]; + gsum += green[yp]; + bsum += blue[yp]; + asum += alpha[yp]; + } + + yi = x << 2; + + for (y = 0; y < this.bitmap.height; y++) { + pa = asum * mulSum >>> shgSum; + this.bitmap.data[yi + 3] = pa; // normalize alpha + + if (pa > 255) { + this.bitmap.data[yi + 3] = 255; + } + + if (pa > 0) { + pa = 255 / pa; + this.bitmap.data[yi] = (rsum * mulSum >>> shgSum) * pa; + this.bitmap.data[yi + 1] = (gsum * mulSum >>> shgSum) * pa; + this.bitmap.data[yi + 2] = (bsum * mulSum >>> shgSum) * pa; + } else { + this.bitmap.data[yi + 2] = 0; + this.bitmap.data[yi + 1] = 0; + this.bitmap.data[yi] = 0; + } + + if (x === 0) { + vmin[y] = ((p = y + rad1) < hm ? p : hm) * this.bitmap.width; + vmax[y] = (p = y - r) > 0 ? p * this.bitmap.width : 0; + } + + p1 = x + vmin[y]; + p2 = x + vmax[y]; + rsum += red[p1] - red[p2]; + gsum += green[p1] - green[p2]; + bsum += blue[p1] - blue[p2]; + asum += alpha[p1] - alpha[p2]; + yi += this.bitmap.width << 2; + } + } + } + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(this, null, this); + } + + return this; + } + }; +}; + +exports["default"] = _default; +module.exports = exports.default; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 2005: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _utils = __nccwpck_require__(7403); + +/** + * Creates a circle out of an image. + * @param {function(Error, Jimp)} options (optional) radius, x, y + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ +var _default = function _default() { + return { + circle: function circle() { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var cb = arguments.length > 1 ? arguments[1] : undefined; + + if (typeof options === 'function') { + cb = options; + options = {}; + } + + var radius = options.radius || (this.bitmap.width > this.bitmap.height ? this.bitmap.height : this.bitmap.width) / 2; + var center = { + x: typeof options.x === 'number' ? options.x : this.bitmap.width / 2, + y: typeof options.y === 'number' ? options.y : this.bitmap.height / 2 + }; + this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) { + var curR = Math.sqrt(Math.pow(x - center.x, 2) + Math.pow(y - center.y, 2)); + + if (radius - curR <= 0.0) { + this.bitmap.data[idx + 3] = 0; + } else if (radius - curR < 1.0) { + this.bitmap.data[idx + 3] = 255 * (radius - curR); + } + }); + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(this, null, this); + } + + return this; + } + }; +}; + +exports["default"] = _default; +module.exports = exports.default; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 5432: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +var _interopRequireDefault = __nccwpck_require__(3286); + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _toConsumableArray2 = _interopRequireDefault(__nccwpck_require__(3195)); + +var _tinycolor = _interopRequireDefault(__nccwpck_require__(5479)); + +var _utils = __nccwpck_require__(7403); + +function applyKernel(im, kernel, x, y) { + var value = [0, 0, 0]; + var size = (kernel.length - 1) / 2; + + for (var kx = 0; kx < kernel.length; kx += 1) { + for (var ky = 0; ky < kernel[kx].length; ky += 1) { + var idx = im.getPixelIndex(x + kx - size, y + ky - size); + value[0] += im.bitmap.data[idx] * kernel[kx][ky]; + value[1] += im.bitmap.data[idx + 1] * kernel[kx][ky]; + value[2] += im.bitmap.data[idx + 2] * kernel[kx][ky]; + } + } + + return value; +} + +var isDef = function isDef(v) { + return typeof v !== 'undefined' && v !== null; +}; + +function greyscale(cb) { + this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) { + var grey = parseInt(0.2126 * this.bitmap.data[idx] + 0.7152 * this.bitmap.data[idx + 1] + 0.0722 * this.bitmap.data[idx + 2], 10); + this.bitmap.data[idx] = grey; + this.bitmap.data[idx + 1] = grey; + this.bitmap.data[idx + 2] = grey; + }); + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(this, null, this); + } + + return this; +} + +function mix(clr, clr2) { + var p = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 50; + return { + r: (clr2.r - clr.r) * (p / 100) + clr.r, + g: (clr2.g - clr.g) * (p / 100) + clr.g, + b: (clr2.b - clr.b) * (p / 100) + clr.b + }; +} + +function colorFn(actions, cb) { + var _this = this; + + if (!actions || !Array.isArray(actions)) { + return _utils.throwError.call(this, 'actions must be an array', cb); + } + + actions = actions.map(function (action) { + if (action.apply === 'xor' || action.apply === 'mix') { + action.params[0] = (0, _tinycolor["default"])(action.params[0]).toRgb(); + } + + return action; + }); + this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) { + var clr = { + r: _this.bitmap.data[idx], + g: _this.bitmap.data[idx + 1], + b: _this.bitmap.data[idx + 2] + }; + + var colorModifier = function colorModifier(i, amount) { + return _this.constructor.limit255(clr[i] + amount); + }; + + actions.forEach(function (action) { + if (action.apply === 'mix') { + clr = mix(clr, action.params[0], action.params[1]); + } else if (action.apply === 'tint') { + clr = mix(clr, { + r: 255, + g: 255, + b: 255 + }, action.params[0]); + } else if (action.apply === 'shade') { + clr = mix(clr, { + r: 0, + g: 0, + b: 0 + }, action.params[0]); + } else if (action.apply === 'xor') { + clr = { + r: clr.r ^ action.params[0].r, + g: clr.g ^ action.params[0].g, + b: clr.b ^ action.params[0].b + }; + } else if (action.apply === 'red') { + clr.r = colorModifier('r', action.params[0]); + } else if (action.apply === 'green') { + clr.g = colorModifier('g', action.params[0]); + } else if (action.apply === 'blue') { + clr.b = colorModifier('b', action.params[0]); + } else { + var _clr; + + if (action.apply === 'hue') { + action.apply = 'spin'; + } + + clr = (0, _tinycolor["default"])(clr); + + if (!clr[action.apply]) { + return _utils.throwError.call(_this, 'action ' + action.apply + ' not supported', cb); + } + + clr = (_clr = clr)[action.apply].apply(_clr, (0, _toConsumableArray2["default"])(action.params)).toRgb(); + } + }); + _this.bitmap.data[idx] = clr.r; + _this.bitmap.data[idx + 1] = clr.g; + _this.bitmap.data[idx + 2] = clr.b; + }); + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(this, null, this); + } + + return this; +} + +var _default = function _default() { + return { + /** + * Adjusts the brightness of the image + * @param {number} val the amount to adjust the brightness, a number between -1 and +1 + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp }this for chaining of methods + */ + brightness: function brightness(val, cb) { + if (typeof val !== 'number') { + return _utils.throwError.call(this, 'val must be numbers', cb); + } + + if (val < -1 || val > +1) { + return _utils.throwError.call(this, 'val must be a number between -1 and +1', cb); + } + + this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) { + if (val < 0.0) { + this.bitmap.data[idx] = this.bitmap.data[idx] * (1 + val); + this.bitmap.data[idx + 1] = this.bitmap.data[idx + 1] * (1 + val); + this.bitmap.data[idx + 2] = this.bitmap.data[idx + 2] * (1 + val); + } else { + this.bitmap.data[idx] = this.bitmap.data[idx] + (255 - this.bitmap.data[idx]) * val; + this.bitmap.data[idx + 1] = this.bitmap.data[idx + 1] + (255 - this.bitmap.data[idx + 1]) * val; + this.bitmap.data[idx + 2] = this.bitmap.data[idx + 2] + (255 - this.bitmap.data[idx + 2]) * val; + } + }); + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(this, null, this); + } + + return this; + }, + + /** + * Adjusts the contrast of the image + * @param {number} val the amount to adjust the contrast, a number between -1 and +1 + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp }this for chaining of methods + */ + contrast: function contrast(val, cb) { + if (typeof val !== 'number') { + return _utils.throwError.call(this, 'val must be numbers', cb); + } + + if (val < -1 || val > +1) { + return _utils.throwError.call(this, 'val must be a number between -1 and +1', cb); + } + + var factor = (val + 1) / (1 - val); + + function adjust(value) { + value = Math.floor(factor * (value - 127) + 127); + return value < 0 ? 0 : value > 255 ? 255 : value; + } + + this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) { + this.bitmap.data[idx] = adjust(this.bitmap.data[idx]); + this.bitmap.data[idx + 1] = adjust(this.bitmap.data[idx + 1]); + this.bitmap.data[idx + 2] = adjust(this.bitmap.data[idx + 2]); + }); + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(this, null, this); + } + + return this; + }, + + /** + * Apply a posterize effect + * @param {number} n the amount to adjust the contrast, minimum threshold is two + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp }this for chaining of methods + */ + posterize: function posterize(n, cb) { + if (typeof n !== 'number') { + return _utils.throwError.call(this, 'n must be numbers', cb); + } + + if (n < 2) { + n = 2; + } // minimum of 2 levels + + + this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) { + this.bitmap.data[idx] = Math.floor(this.bitmap.data[idx] / 255 * (n - 1)) / (n - 1) * 255; + this.bitmap.data[idx + 1] = Math.floor(this.bitmap.data[idx + 1] / 255 * (n - 1)) / (n - 1) * 255; + this.bitmap.data[idx + 2] = Math.floor(this.bitmap.data[idx + 2] / 255 * (n - 1)) / (n - 1) * 255; + }); + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(this, null, this); + } + + return this; + }, + + /** + * Removes colour from the image using ITU Rec 709 luminance values + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp }this for chaining of methods + */ + greyscale: greyscale, + // Alias of greyscale for our American friends + grayscale: greyscale, + + /** + * Multiplies the opacity of each pixel by a factor between 0 and 1 + * @param {number} f A number, the factor by which to multiply the opacity of each pixel + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp }this for chaining of methods + */ + opacity: function opacity(f, cb) { + if (typeof f !== 'number') return _utils.throwError.call(this, 'f must be a number', cb); + if (f < 0 || f > 1) return _utils.throwError.call(this, 'f must be a number from 0 to 1', cb); + this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) { + var v = this.bitmap.data[idx + 3] * f; + this.bitmap.data[idx + 3] = v; + }); + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(this, null, this); + } + + return this; + }, + + /** + * Applies a sepia tone to the image + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp }this for chaining of methods + */ + sepia: function sepia(cb) { + this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) { + var red = this.bitmap.data[idx]; + var green = this.bitmap.data[idx + 1]; + var blue = this.bitmap.data[idx + 2]; + red = red * 0.393 + green * 0.769 + blue * 0.189; + green = red * 0.349 + green * 0.686 + blue * 0.168; + blue = red * 0.272 + green * 0.534 + blue * 0.131; + this.bitmap.data[idx] = red < 255 ? red : 255; + this.bitmap.data[idx + 1] = green < 255 ? green : 255; + this.bitmap.data[idx + 2] = blue < 255 ? blue : 255; + }); + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(this, null, this); + } + + return this; + }, + + /** + * Fades each pixel by a factor between 0 and 1 + * @param {number} f A number from 0 to 1. 0 will haven no effect. 1 will turn the image completely transparent. + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp }this for chaining of methods + */ + fade: function fade(f, cb) { + if (typeof f !== 'number') { + return _utils.throwError.call(this, 'f must be a number', cb); + } + + if (f < 0 || f > 1) { + return _utils.throwError.call(this, 'f must be a number from 0 to 1', cb); + } // this method is an alternative to opacity (which may be deprecated) + + + this.opacity(1 - f); + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(this, null, this); + } + + return this; + }, + + /** + * Adds each element of the image to its local neighbors, weighted by the kernel + * @param {array} kernel a matrix to weight the neighbors sum + * @param {string} edgeHandling (optional) define how to sum pixels from outside the border + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp }this for chaining of methods + */ + convolution: function convolution(kernel, edgeHandling, cb) { + if (typeof edgeHandling === 'function' && typeof cb === 'undefined') { + cb = edgeHandling; + edgeHandling = null; + } + + if (!edgeHandling) { + edgeHandling = this.constructor.EDGE_EXTEND; + } + + var newData = Buffer.from(this.bitmap.data); + var kRows = kernel.length; + var kCols = kernel[0].length; + var rowEnd = Math.floor(kRows / 2); + var colEnd = Math.floor(kCols / 2); + var rowIni = -rowEnd; + var colIni = -colEnd; + var weight; + var rSum; + var gSum; + var bSum; + var ri; + var gi; + var bi; + var xi; + var yi; + var idxi; + this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) { + bSum = 0; + gSum = 0; + rSum = 0; + + for (var row = rowIni; row <= rowEnd; row++) { + for (var col = colIni; col <= colEnd; col++) { + xi = x + col; + yi = y + row; + weight = kernel[row + rowEnd][col + colEnd]; + idxi = this.getPixelIndex(xi, yi, edgeHandling); + + if (idxi === -1) { + bi = 0; + gi = 0; + ri = 0; + } else { + ri = this.bitmap.data[idxi + 0]; + gi = this.bitmap.data[idxi + 1]; + bi = this.bitmap.data[idxi + 2]; + } + + rSum += weight * ri; + gSum += weight * gi; + bSum += weight * bi; + } + } + + if (rSum < 0) { + rSum = 0; + } + + if (gSum < 0) { + gSum = 0; + } + + if (bSum < 0) { + bSum = 0; + } + + if (rSum > 255) { + rSum = 255; + } + + if (gSum > 255) { + gSum = 255; + } + + if (bSum > 255) { + bSum = 255; + } + + newData[idx + 0] = rSum; + newData[idx + 1] = gSum; + newData[idx + 2] = bSum; + }); + this.bitmap.data = newData; + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(this, null, this); + } + + return this; + }, + + /** + * Set the alpha channel on every pixel to fully opaque + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp }this for chaining of methods + */ + opaque: function opaque(cb) { + this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) { + this.bitmap.data[idx + 3] = 255; + }); + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(this, null, this); + } + + return this; + }, + + /** + * Pixelates the image or a region + * @param {number} size the size of the pixels + * @param {number} x (optional) the x position of the region to pixelate + * @param {number} y (optional) the y position of the region to pixelate + * @param {number} w (optional) the width of the region to pixelate + * @param {number} h (optional) the height of the region to pixelate + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp }this for chaining of methods + */ + pixelate: function pixelate(size, x, y, w, h, cb) { + if (typeof x === 'function') { + cb = x; + h = null; + w = null; + y = null; + x = null; + } else { + if (typeof size !== 'number') { + return _utils.throwError.call(this, 'size must be a number', cb); + } + + if (isDef(x) && typeof x !== 'number') { + return _utils.throwError.call(this, 'x must be a number', cb); + } + + if (isDef(y) && typeof y !== 'number') { + return _utils.throwError.call(this, 'y must be a number', cb); + } + + if (isDef(w) && typeof w !== 'number') { + return _utils.throwError.call(this, 'w must be a number', cb); + } + + if (isDef(h) && typeof h !== 'number') { + return _utils.throwError.call(this, 'h must be a number', cb); + } + } + + var kernel = [[1 / 16, 2 / 16, 1 / 16], [2 / 16, 4 / 16, 2 / 16], [1 / 16, 2 / 16, 1 / 16]]; + x = x || 0; + y = y || 0; + w = isDef(w) ? w : this.bitmap.width - x; + h = isDef(h) ? h : this.bitmap.height - y; + var source = this.cloneQuiet(); + this.scanQuiet(x, y, w, h, function (xx, yx, idx) { + xx = size * Math.floor(xx / size); + yx = size * Math.floor(yx / size); + var value = applyKernel(source, kernel, xx, yx); + this.bitmap.data[idx] = value[0]; + this.bitmap.data[idx + 1] = value[1]; + this.bitmap.data[idx + 2] = value[2]; + }); + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(this, null, this); + } + + return this; + }, + + /** + * Applies a convolution kernel to the image or a region + * @param {array} kernel the convolution kernel + * @param {number} x (optional) the x position of the region to apply convolution to + * @param {number} y (optional) the y position of the region to apply convolution to + * @param {number} w (optional) the width of the region to apply convolution to + * @param {number} h (optional) the height of the region to apply convolution to + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp }this for chaining of methods + */ + convolute: function convolute(kernel, x, y, w, h, cb) { + if (!Array.isArray(kernel)) return _utils.throwError.call(this, 'the kernel must be an array', cb); + + if (typeof x === 'function') { + cb = x; + x = null; + y = null; + w = null; + h = null; + } else { + if (isDef(x) && typeof x !== 'number') { + return _utils.throwError.call(this, 'x must be a number', cb); + } + + if (isDef(y) && typeof y !== 'number') { + return _utils.throwError.call(this, 'y must be a number', cb); + } + + if (isDef(w) && typeof w !== 'number') { + return _utils.throwError.call(this, 'w must be a number', cb); + } + + if (isDef(h) && typeof h !== 'number') { + return _utils.throwError.call(this, 'h must be a number', cb); + } + } + + var ksize = (kernel.length - 1) / 2; + x = isDef(x) ? x : ksize; + y = isDef(y) ? y : ksize; + w = isDef(w) ? w : this.bitmap.width - x; + h = isDef(h) ? h : this.bitmap.height - y; + var source = this.cloneQuiet(); + this.scanQuiet(x, y, w, h, function (xx, yx, idx) { + var value = applyKernel(source, kernel, xx, yx); + this.bitmap.data[idx] = this.constructor.limit255(value[0]); + this.bitmap.data[idx + 1] = this.constructor.limit255(value[1]); + this.bitmap.data[idx + 2] = this.constructor.limit255(value[2]); + }); + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(this, null, this); + } + + return this; + }, + + /** + * Apply multiple color modification rules + * @param {array} actions list of color modification rules, in following format: { apply: '', params: [ ] } + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp }this for chaining of methods + */ + color: colorFn, + colour: colorFn + }; +}; + +exports["default"] = _default; +module.exports = exports.default; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 7125: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _utils = __nccwpck_require__(7403); + +/** + * Scale the image to the given width and height keeping the aspect ratio. Some parts of the image may be letter boxed. + * @param {number} w the width to resize the image to + * @param {number} h the height to resize the image to + * @param {number} alignBits (optional) A bitmask for horizontal and vertical alignment + * @param {string} mode (optional) a scaling method (e.g. Jimp.RESIZE_BEZIER) + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ +var _default = function _default() { + return { + contain: function contain(w, h, alignBits, mode, cb) { + if (typeof w !== 'number' || typeof h !== 'number') { + return _utils.throwError.call(this, 'w and h must be numbers', cb); + } // permit any sort of optional parameters combination + + + if (typeof alignBits === 'string') { + if (typeof mode === 'function' && typeof cb === 'undefined') cb = mode; + mode = alignBits; + alignBits = null; + } + + if (typeof alignBits === 'function') { + if (typeof cb === 'undefined') cb = alignBits; + mode = null; + alignBits = null; + } + + if (typeof mode === 'function' && typeof cb === 'undefined') { + cb = mode; + mode = null; + } + + alignBits = alignBits || this.constructor.HORIZONTAL_ALIGN_CENTER | this.constructor.VERTICAL_ALIGN_MIDDLE; + var hbits = alignBits & (1 << 3) - 1; + var vbits = alignBits >> 3; // check if more flags than one is in the bit sets + + if (!(hbits !== 0 && !(hbits & hbits - 1) || vbits !== 0 && !(vbits & vbits - 1))) { + return _utils.throwError.call(this, 'only use one flag per alignment direction', cb); + } + + var alignH = hbits >> 1; // 0, 1, 2 + + var alignV = vbits >> 1; // 0, 1, 2 + + var f = w / h > this.bitmap.width / this.bitmap.height ? h / this.bitmap.height : w / this.bitmap.width; + var c = this.cloneQuiet().scale(f, mode); + this.resize(w, h, mode); + this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) { + this.bitmap.data.writeUInt32BE(this._background, idx); + }); + this.blit(c, (this.bitmap.width - c.bitmap.width) / 2 * alignH, (this.bitmap.height - c.bitmap.height) / 2 * alignV); + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(this, null, this); + } + + return this; + } + }; +}; + +exports["default"] = _default; +module.exports = exports.default; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 937: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _utils = __nccwpck_require__(7403); + +/** + * Scale the image so the given width and height keeping the aspect ratio. Some parts of the image may be clipped. + * @param {number} w the width to resize the image to + * @param {number} h the height to resize the image to + * @param {number} alignBits (optional) A bitmask for horizontal and vertical alignment + * @param {string} mode (optional) a scaling method (e.g. Jimp.RESIZE_BEZIER) + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ +var _default = function _default() { + return { + cover: function cover(w, h, alignBits, mode, cb) { + if (typeof w !== 'number' || typeof h !== 'number') { + return _utils.throwError.call(this, 'w and h must be numbers', cb); + } + + if (alignBits && typeof alignBits === 'function' && typeof cb === 'undefined') { + cb = alignBits; + alignBits = null; + mode = null; + } else if (typeof mode === 'function' && typeof cb === 'undefined') { + cb = mode; + mode = null; + } + + alignBits = alignBits || this.constructor.HORIZONTAL_ALIGN_CENTER | this.constructor.VERTICAL_ALIGN_MIDDLE; + var hbits = alignBits & (1 << 3) - 1; + var vbits = alignBits >> 3; // check if more flags than one is in the bit sets + + if (!(hbits !== 0 && !(hbits & hbits - 1) || vbits !== 0 && !(vbits & vbits - 1))) return _utils.throwError.call(this, 'only use one flag per alignment direction', cb); + var alignH = hbits >> 1; // 0, 1, 2 + + var alignV = vbits >> 1; // 0, 1, 2 + + var f = w / h > this.bitmap.width / this.bitmap.height ? w / this.bitmap.width : h / this.bitmap.height; + this.scale(f, mode); + this.crop((this.bitmap.width - w) / 2 * alignH, (this.bitmap.height - h) / 2 * alignV, w, h); + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(this, null, this); + } + + return this; + } + }; +}; + +exports["default"] = _default; +module.exports = exports.default; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 1623: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +var _interopRequireDefault = __nccwpck_require__(3286); + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = pluginCrop; + +var _typeof2 = _interopRequireDefault(__nccwpck_require__(5605)); + +var _utils = __nccwpck_require__(7403); + +/* eslint-disable no-labels */ +function pluginCrop(event) { + /** + * Crops the image at a given point to a give size + * @param {number} x the x coordinate to crop form + * @param {number} y the y coordinate to crop form + * @param w the width of the crop region + * @param h the height of the crop region + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ + event('crop', function (x, y, w, h, cb) { + if (typeof x !== 'number' || typeof y !== 'number') return _utils.throwError.call(this, 'x and y must be numbers', cb); + if (typeof w !== 'number' || typeof h !== 'number') return _utils.throwError.call(this, 'w and h must be numbers', cb); // round input + + x = Math.round(x); + y = Math.round(y); + w = Math.round(w); + h = Math.round(h); + + if (x === 0 && w === this.bitmap.width) { + // shortcut + var start = w * y + x << 2; + var end = start + h * w << 2; + this.bitmap.data = this.bitmap.data.slice(start, end); + } else { + var bitmap = Buffer.allocUnsafe(w * h * 4); + var offset = 0; + this.scanQuiet(x, y, w, h, function (x, y, idx) { + var data = this.bitmap.data.readUInt32BE(idx, true); + bitmap.writeUInt32BE(data, offset, true); + offset += 4; + }); + this.bitmap.data = bitmap; + } + + this.bitmap.width = w; + this.bitmap.height = h; + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(this, null, this); + } + + return this; + }); + return { + "class": { + /** + * Autocrop same color borders from this image + * @param {number} tolerance (optional): a percent value of tolerance for pixels color difference (default: 0.0002%) + * @param {boolean} cropOnlyFrames (optional): flag to crop only real frames: all 4 sides of the image must have some border (default: true) + * @param {function(Error, Jimp)} cb (optional): a callback for when complete (default: no callback) + * @returns {Jimp} this for chaining of methods + */ + autocrop: function autocrop() { + var w = this.bitmap.width; + var h = this.bitmap.height; + var minPixelsPerSide = 1; // to avoid cropping completely the image, resulting in an invalid 0 sized image + + var cb; // callback + + var leaveBorder = 0; // Amount of pixels in border to leave + + var tolerance = 0.0002; // percent of color difference tolerance (default value) + + var cropOnlyFrames = true; // flag to force cropping only if the image has a real "frame" + // i.e. all 4 sides have some border (default value) + + var cropSymmetric = false; // flag to force cropping top be symmetric. + // i.e. north and south / east and west are cropped by the same value + + var ignoreSides = { + north: false, + south: false, + east: false, + west: false + }; // parse arguments + + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + for (var a = 0, len = args.length; a < len; a++) { + if (typeof args[a] === 'number') { + // tolerance value passed + tolerance = args[a]; + } + + if (typeof args[a] === 'boolean') { + // cropOnlyFrames value passed + cropOnlyFrames = args[a]; + } + + if (typeof args[a] === 'function') { + // callback value passed + cb = args[a]; + } + + if ((0, _typeof2["default"])(args[a]) === 'object') { + // config object passed + var config = args[a]; + + if (typeof config.tolerance !== 'undefined') { + tolerance = config.tolerance; + } + + if (typeof config.cropOnlyFrames !== 'undefined') { + cropOnlyFrames = config.cropOnlyFrames; + } + + if (typeof config.cropSymmetric !== 'undefined') { + cropSymmetric = config.cropSymmetric; + } + + if (typeof config.leaveBorder !== 'undefined') { + leaveBorder = config.leaveBorder; + } + + if (typeof config.ignoreSides !== 'undefined') { + ignoreSides = config.ignoreSides; + } + } + } + /** + * All borders must be of the same color as the top left pixel, to be cropped. + * It should be possible to crop borders each with a different color, + * but since there are many ways for corners to intersect, it would + * introduce unnecessary complexity to the algorithm. + */ + // scan each side for same color borders + + + var colorTarget = this.getPixelColor(0, 0); // top left pixel color is the target color + + var rgba1 = this.constructor.intToRGBA(colorTarget); // for north and east sides + + var northPixelsToCrop = 0; + var eastPixelsToCrop = 0; + var southPixelsToCrop = 0; + var westPixelsToCrop = 0; // north side (scan rows from north to south) + + colorTarget = this.getPixelColor(0, 0); + + if (!ignoreSides.north) { + north: for (var y = 0; y < h - minPixelsPerSide; y++) { + for (var x = 0; x < w; x++) { + var colorXY = this.getPixelColor(x, y); + var rgba2 = this.constructor.intToRGBA(colorXY); + + if (this.constructor.colorDiff(rgba1, rgba2) > tolerance) { + // this pixel is too distant from the first one: abort this side scan + break north; + } + } // this row contains all pixels with the same color: increment this side pixels to crop + + + northPixelsToCrop++; + } + } // east side (scan columns from east to west) + + + colorTarget = this.getPixelColor(w, 0); + + if (!ignoreSides.east) { + east: for (var _x = 0; _x < w - minPixelsPerSide; _x++) { + for (var _y = 0 + northPixelsToCrop; _y < h; _y++) { + var _colorXY = this.getPixelColor(_x, _y); + + var _rgba = this.constructor.intToRGBA(_colorXY); + + if (this.constructor.colorDiff(rgba1, _rgba) > tolerance) { + // this pixel is too distant from the first one: abort this side scan + break east; + } + } // this column contains all pixels with the same color: increment this side pixels to crop + + + eastPixelsToCrop++; + } + } // south side (scan rows from south to north) + + + colorTarget = this.getPixelColor(0, h); + + if (!ignoreSides.south) { + south: for (var _y2 = h - 1; _y2 >= northPixelsToCrop + minPixelsPerSide; _y2--) { + for (var _x2 = w - eastPixelsToCrop - 1; _x2 >= 0; _x2--) { + var _colorXY2 = this.getPixelColor(_x2, _y2); + + var _rgba2 = this.constructor.intToRGBA(_colorXY2); + + if (this.constructor.colorDiff(rgba1, _rgba2) > tolerance) { + // this pixel is too distant from the first one: abort this side scan + break south; + } + } // this row contains all pixels with the same color: increment this side pixels to crop + + + southPixelsToCrop++; + } + } // west side (scan columns from west to east) + + + colorTarget = this.getPixelColor(w, h); + + if (!ignoreSides.west) { + west: for (var _x3 = w - 1; _x3 >= 0 + eastPixelsToCrop + minPixelsPerSide; _x3--) { + for (var _y3 = h - 1; _y3 >= 0 + northPixelsToCrop; _y3--) { + var _colorXY3 = this.getPixelColor(_x3, _y3); + + var _rgba3 = this.constructor.intToRGBA(_colorXY3); + + if (this.constructor.colorDiff(rgba1, _rgba3) > tolerance) { + // this pixel is too distant from the first one: abort this side scan + break west; + } + } // this column contains all pixels with the same color: increment this side pixels to crop + + + westPixelsToCrop++; + } + } // decide if a crop is needed + + + var doCrop = false; // apply leaveBorder + + westPixelsToCrop -= leaveBorder; + eastPixelsToCrop -= leaveBorder; + northPixelsToCrop -= leaveBorder; + southPixelsToCrop -= leaveBorder; + + if (cropSymmetric) { + var horizontal = Math.min(eastPixelsToCrop, westPixelsToCrop); + var vertical = Math.min(northPixelsToCrop, southPixelsToCrop); + westPixelsToCrop = horizontal; + eastPixelsToCrop = horizontal; + northPixelsToCrop = vertical; + southPixelsToCrop = vertical; + } // make sure that crops are >= 0 + + + westPixelsToCrop = westPixelsToCrop >= 0 ? westPixelsToCrop : 0; + eastPixelsToCrop = eastPixelsToCrop >= 0 ? eastPixelsToCrop : 0; + northPixelsToCrop = northPixelsToCrop >= 0 ? northPixelsToCrop : 0; + southPixelsToCrop = southPixelsToCrop >= 0 ? southPixelsToCrop : 0; // safety checks + + var widthOfRemainingPixels = w - (westPixelsToCrop + eastPixelsToCrop); + var heightOfRemainingPixels = h - (southPixelsToCrop + northPixelsToCrop); + + if (cropOnlyFrames) { + // crop image if all sides should be cropped + doCrop = eastPixelsToCrop !== 0 && northPixelsToCrop !== 0 && westPixelsToCrop !== 0 && southPixelsToCrop !== 0; + } else { + // crop image if at least one side should be cropped + doCrop = eastPixelsToCrop !== 0 || northPixelsToCrop !== 0 || westPixelsToCrop !== 0 || southPixelsToCrop !== 0; + } + + if (doCrop) { + // do the real crop + this.crop(eastPixelsToCrop, northPixelsToCrop, widthOfRemainingPixels, heightOfRemainingPixels); + } + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(this, null, this); + } + + return this; + } + } + }; +} + +module.exports = exports.default; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 6096: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +var _interopRequireDefault = __nccwpck_require__(3286); + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _typeof2 = _interopRequireDefault(__nccwpck_require__(5605)); + +var _utils = __nccwpck_require__(7403); + +/** + * Displaces the image based on the provided displacement map + * @param {object} map the source Jimp instance + * @param {number} offset the maximum displacement value + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ +var _default = function _default() { + return { + displace: function displace(map, offset, cb) { + if ((0, _typeof2["default"])(map) !== 'object' || map.constructor !== this.constructor) { + return _utils.throwError.call(this, 'The source must be a Jimp image', cb); + } + + if (typeof offset !== 'number') { + return _utils.throwError.call(this, 'factor must be a number', cb); + } + + var source = this.cloneQuiet(); + this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) { + var displacement = map.bitmap.data[idx] / 256 * offset; + displacement = Math.round(displacement); + var ids = this.getPixelIndex(x + displacement, y); + this.bitmap.data[ids] = source.bitmap.data[idx]; + this.bitmap.data[ids + 1] = source.bitmap.data[idx + 1]; + this.bitmap.data[ids + 2] = source.bitmap.data[idx + 2]; + }); + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(this, null, this); + } + + return this; + } + }; +}; + +exports["default"] = _default; +module.exports = exports.default; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 5808: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _utils = __nccwpck_require__(7403); + +/** + * Apply a ordered dithering effect + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ +function dither(cb) { + var rgb565Matrix = [1, 9, 3, 11, 13, 5, 15, 7, 4, 12, 2, 10, 16, 8, 14, 6]; + this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) { + var thresholdId = ((y & 3) << 2) + x % 4; + var dither = rgb565Matrix[thresholdId]; + this.bitmap.data[idx] = Math.min(this.bitmap.data[idx] + dither, 0xff); + this.bitmap.data[idx + 1] = Math.min(this.bitmap.data[idx + 1] + dither, 0xff); + this.bitmap.data[idx + 2] = Math.min(this.bitmap.data[idx + 2] + dither, 0xff); + }); + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(this, null, this); + } + + return this; +} + +var _default = function _default() { + return { + dither565: dither, + dither16: dither + }; +}; + +exports["default"] = _default; +module.exports = exports.default; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 1885: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _utils = __nccwpck_require__(7403); + +/** + * Creates a circle out of an image. + * @param {object} options (optional) r: radius of effect + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ +var _default = function _default() { + return { + fisheye: function fisheye() { + var _this = this; + + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { + r: 2.5 + }; + var cb = arguments.length > 1 ? arguments[1] : undefined; + + if (typeof options === 'function') { + cb = options; + options = { + r: 2.5 + }; + } + + var source = this.cloneQuiet(); + var _source$bitmap = source.bitmap, + width = _source$bitmap.width, + height = _source$bitmap.height; + source.scanQuiet(0, 0, width, height, function (x, y) { + var hx = x / width; + var hy = y / height; + var r = Math.sqrt(Math.pow(hx - 0.5, 2) + Math.pow(hy - 0.5, 2)); + var rn = 2 * Math.pow(r, options.r); + var cosA = (hx - 0.5) / r; + var sinA = (hy - 0.5) / r; + var newX = Math.round((rn * cosA + 0.5) * width); + var newY = Math.round((rn * sinA + 0.5) * height); + var color = source.getPixelColor(newX, newY); + + _this.setPixelColor(color, x, y); + }); + /* Set center pixel color, otherwise it will be transparent */ + + this.setPixelColor(source.getPixelColor(width / 2, height / 2), width / 2, height / 2); + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(this, null, this); + } + + return this; + } + }; +}; + +exports["default"] = _default; +module.exports = exports.default; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 2818: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _utils = __nccwpck_require__(7403); + +/** + * Flip the image horizontally + * @param {boolean} horizontal a Boolean, if true the image will be flipped horizontally + * @param {boolean} vertical a Boolean, if true the image will be flipped vertically + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ +function flipFn(horizontal, vertical, cb) { + if (typeof horizontal !== 'boolean' || typeof vertical !== 'boolean') return _utils.throwError.call(this, 'horizontal and vertical must be Booleans', cb); + var bitmap = Buffer.alloc(this.bitmap.data.length); + this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) { + var _x = horizontal ? this.bitmap.width - 1 - x : x; + + var _y = vertical ? this.bitmap.height - 1 - y : y; + + var _idx = this.bitmap.width * _y + _x << 2; + + var data = this.bitmap.data.readUInt32BE(idx); + bitmap.writeUInt32BE(data, _idx); + }); + this.bitmap.data = Buffer.from(bitmap); + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(this, null, this); + } + + return this; +} + +var _default = function _default() { + return { + flip: flipFn, + mirror: flipFn + }; +}; + +exports["default"] = _default; +module.exports = exports.default; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 2135: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _utils = __nccwpck_require__(7403); + +/** + * Applies a true Gaussian blur to the image (warning: this is VERY slow) + * @param {number} r the pixel radius of the blur + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ +var _default = function _default() { + return { + gaussian: function gaussian(r, cb) { + // http://blog.ivank.net/fastest-gaussian-blur.html + if (typeof r !== 'number') { + return _utils.throwError.call(this, 'r must be a number', cb); + } + + if (r < 1) { + return _utils.throwError.call(this, 'r must be greater than 0', cb); + } + + var rs = Math.ceil(r * 2.57); // significant radius + + var range = rs * 2 + 1; + var rr2 = r * r * 2; + var rr2pi = rr2 * Math.PI; + var weights = []; + + for (var y = 0; y < range; y++) { + weights[y] = []; + + for (var x = 0; x < range; x++) { + var dsq = Math.pow(x - rs, 2) + Math.pow(y - rs, 2); + weights[y][x] = Math.exp(-dsq / rr2) / rr2pi; + } + } + + for (var _y = 0; _y < this.bitmap.height; _y++) { + for (var _x = 0; _x < this.bitmap.width; _x++) { + var red = 0; + var green = 0; + var blue = 0; + var alpha = 0; + var wsum = 0; + + for (var iy = 0; iy < range; iy++) { + for (var ix = 0; ix < range; ix++) { + var x1 = Math.min(this.bitmap.width - 1, Math.max(0, ix + _x - rs)); + var y1 = Math.min(this.bitmap.height - 1, Math.max(0, iy + _y - rs)); + var weight = weights[iy][ix]; + + var _idx = y1 * this.bitmap.width + x1 << 2; + + red += this.bitmap.data[_idx] * weight; + green += this.bitmap.data[_idx + 1] * weight; + blue += this.bitmap.data[_idx + 2] * weight; + alpha += this.bitmap.data[_idx + 3] * weight; + wsum += weight; + } + + var idx = _y * this.bitmap.width + _x << 2; + this.bitmap.data[idx] = Math.round(red / wsum); + this.bitmap.data[idx + 1] = Math.round(green / wsum); + this.bitmap.data[idx + 2] = Math.round(blue / wsum); + this.bitmap.data[idx + 3] = Math.round(alpha / wsum); + } + } + } + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(this, null, this); + } + + return this; + } + }; +}; + +exports["default"] = _default; +module.exports = exports.default; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 9534: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _utils = __nccwpck_require__(7403); + +/** + * Inverts the image + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ +var _default = function _default() { + return { + invert: function invert(cb) { + this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) { + this.bitmap.data[idx] = 255 - this.bitmap.data[idx]; + this.bitmap.data[idx + 1] = 255 - this.bitmap.data[idx + 1]; + this.bitmap.data[idx + 2] = 255 - this.bitmap.data[idx + 2]; + }); + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(this, null, this); + } + + return this; + } + }; +}; + +exports["default"] = _default; +module.exports = exports.default; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 497: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _utils = __nccwpck_require__(7403); + +/** + * Masks a source image on to this image using average pixel colour. A completely black pixel on the mask will turn a pixel in the image completely transparent. + * @param {Jimp} src the source Jimp instance + * @param {number} x the horizontal position to blit the image + * @param {number} y the vertical position to blit the image + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ +var _default = function _default() { + return { + mask: function mask(src) { + var x = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var y = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var cb = arguments.length > 3 ? arguments[3] : undefined; + + if (!(src instanceof this.constructor)) { + return _utils.throwError.call(this, 'The source must be a Jimp image', cb); + } + + if (typeof x !== 'number' || typeof y !== 'number') { + return _utils.throwError.call(this, 'x and y must be numbers', cb); + } // round input + + + x = Math.round(x); + y = Math.round(y); + var w = this.bitmap.width; + var h = this.bitmap.height; + var baseImage = this; + src.scanQuiet(0, 0, src.bitmap.width, src.bitmap.height, function (sx, sy, idx) { + var destX = x + sx; + var destY = y + sy; + + if (destX >= 0 && destY >= 0 && destX < w && destY < h) { + var dstIdx = baseImage.getPixelIndex(destX, destY); + var data = this.bitmap.data; + var avg = (data[idx + 0] + data[idx + 1] + data[idx + 2]) / 3; + baseImage.bitmap.data[dstIdx + 3] *= avg / 255; + } + }); + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(this, null, this); + } + + return this; + } + }; +}; + +exports["default"] = _default; +module.exports = exports.default; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 7022: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _utils = __nccwpck_require__(7403); + +/** + * Get an image's histogram + * @return {object} An object with an array of color occurrence counts for each channel (r,g,b) + */ +function histogram() { + var histogram = { + r: new Array(256).fill(0), + g: new Array(256).fill(0), + b: new Array(256).fill(0) + }; + this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, index) { + histogram.r[this.bitmap.data[index + 0]]++; + histogram.g[this.bitmap.data[index + 1]]++; + histogram.b[this.bitmap.data[index + 2]]++; + }); + return histogram; +} +/** + * Normalize values + * @param {integer} value Pixel channel value. + * @param {integer} min Minimum value for channel + * @param {integer} max Maximum value for channel + * @return {integer} normalized values + */ + + +var _normalize = function normalize(value, min, max) { + return (value - min) * 255 / (max - min); +}; + +var getBounds = function getBounds(histogramChannel) { + return [histogramChannel.findIndex(function (value) { + return value > 0; + }), 255 - histogramChannel.slice().reverse().findIndex(function (value) { + return value > 0; + })]; +}; +/** + * Normalizes the image + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ + + +var _default = function _default() { + return { + normalize: function normalize(cb) { + var h = histogram.call(this); // store bounds (minimum and maximum values) + + var bounds = { + r: getBounds(h.r), + g: getBounds(h.g), + b: getBounds(h.b) + }; // apply value transformations + + this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) { + var r = this.bitmap.data[idx + 0]; + var g = this.bitmap.data[idx + 1]; + var b = this.bitmap.data[idx + 2]; + this.bitmap.data[idx + 0] = _normalize(r, bounds.r[0], bounds.r[1]); + this.bitmap.data[idx + 1] = _normalize(g, bounds.g[0], bounds.g[1]); + this.bitmap.data[idx + 2] = _normalize(b, bounds.b[0], bounds.b[1]); + }); + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(this, null, this); + } + + return this; + } + }; +}; + +exports["default"] = _default; +module.exports = exports.default; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 7996: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +var _interopRequireDefault = __nccwpck_require__(3286); + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _typeof2 = _interopRequireDefault(__nccwpck_require__(5605)); + +var _toConsumableArray2 = _interopRequireDefault(__nccwpck_require__(3195)); + +var _path = _interopRequireDefault(__nccwpck_require__(1017)); + +var _loadBmfont = _interopRequireDefault(__nccwpck_require__(9919)); + +var _utils = __nccwpck_require__(7403); + +var _measureText = __nccwpck_require__(4803); + +function xOffsetBasedOnAlignment(constants, font, line, maxWidth, alignment) { + if (alignment === constants.HORIZONTAL_ALIGN_LEFT) { + return 0; + } + + if (alignment === constants.HORIZONTAL_ALIGN_CENTER) { + return (maxWidth - (0, _measureText.measureText)(font, line)) / 2; + } + + return maxWidth - (0, _measureText.measureText)(font, line); +} + +function drawCharacter(image, font, x, y, _char) { + if (_char.width > 0 && _char.height > 0) { + var characterPage = font.pages[_char.page]; + image.blit(characterPage, x + _char.xoffset, y + _char.yoffset, _char.x, _char.y, _char.width, _char.height); + } + + return image; +} + +function printText(font, x, y, text, defaultCharWidth) { + for (var i = 0; i < text.length; i++) { + var _char2 = void 0; + + if (font.chars[text[i]]) { + _char2 = text[i]; + } else if (/\s/.test(text[i])) { + _char2 = ''; + } else { + _char2 = '?'; + } + + var fontChar = font.chars[_char2] || {}; + var fontKerning = font.kernings[_char2]; + drawCharacter(this, font, x, y, fontChar || {}); + var kerning = fontKerning && fontKerning[text[i + 1]] ? fontKerning[text[i + 1]] : 0; + x += kerning + (fontChar.xadvance || defaultCharWidth); + } +} + +function splitLines(font, text, maxWidth) { + var words = text.split(' '); + var lines = []; + var currentLine = []; + var longestLine = 0; + words.forEach(function (word) { + var line = [].concat((0, _toConsumableArray2["default"])(currentLine), [word]).join(' '); + var length = (0, _measureText.measureText)(font, line); + + if (length <= maxWidth) { + if (length > longestLine) { + longestLine = length; + } + + currentLine.push(word); + } else { + lines.push(currentLine); + currentLine = [word]; + } + }); + lines.push(currentLine); + return { + lines: lines, + longestLine: longestLine + }; +} + +function loadPages(Jimp, dir, pages) { + var newPages = pages.map(function (page) { + return Jimp.read(dir + '/' + page); + }); + return Promise.all(newPages); +} + +var dir = process.env.DIRNAME || "".concat(__dirname, "/../"); + +var _default = function _default() { + return { + constants: { + measureText: _measureText.measureText, + measureTextHeight: _measureText.measureTextHeight, + FONT_SANS_8_BLACK: _path["default"].join(dir, 'fonts/open-sans/open-sans-8-black/open-sans-8-black.fnt'), + FONT_SANS_10_BLACK: _path["default"].join(dir, 'fonts/open-sans/open-sans-10-black/open-sans-10-black.fnt'), + FONT_SANS_12_BLACK: _path["default"].join(dir, 'fonts/open-sans/open-sans-12-black/open-sans-12-black.fnt'), + FONT_SANS_14_BLACK: _path["default"].join(dir, 'fonts/open-sans/open-sans-14-black/open-sans-14-black.fnt'), + FONT_SANS_16_BLACK: _path["default"].join(dir, 'fonts/open-sans/open-sans-16-black/open-sans-16-black.fnt'), + FONT_SANS_32_BLACK: _path["default"].join(dir, 'fonts/open-sans/open-sans-32-black/open-sans-32-black.fnt'), + FONT_SANS_64_BLACK: _path["default"].join(dir, 'fonts/open-sans/open-sans-64-black/open-sans-64-black.fnt'), + FONT_SANS_128_BLACK: _path["default"].join(dir, 'fonts/open-sans/open-sans-128-black/open-sans-128-black.fnt'), + FONT_SANS_8_WHITE: _path["default"].join(dir, 'fonts/open-sans/open-sans-8-white/open-sans-8-white.fnt'), + FONT_SANS_16_WHITE: _path["default"].join(dir, 'fonts/open-sans/open-sans-16-white/open-sans-16-white.fnt'), + FONT_SANS_32_WHITE: _path["default"].join(dir, 'fonts/open-sans/open-sans-32-white/open-sans-32-white.fnt'), + FONT_SANS_64_WHITE: _path["default"].join(dir, 'fonts/open-sans/open-sans-64-white/open-sans-64-white.fnt'), + FONT_SANS_128_WHITE: _path["default"].join(dir, 'fonts/open-sans/open-sans-128-white/open-sans-128-white.fnt'), + + /** + * Loads a bitmap font from a file + * @param {string} file the file path of a .fnt file + * @param {function(Error, Jimp)} cb (optional) a function to call when the font is loaded + * @returns {Promise} a promise + */ + loadFont: function loadFont(file, cb) { + var _this = this; + + if (typeof file !== 'string') return _utils.throwError.call(this, 'file must be a string', cb); + return new Promise(function (resolve, reject) { + cb = cb || function (err, font) { + if (err) reject(err);else resolve(font); + }; + + (0, _loadBmfont["default"])(file, function (err, font) { + var chars = {}; + var kernings = {}; + + if (err) { + return _utils.throwError.call(_this, err, cb); + } + + for (var i = 0; i < font.chars.length; i++) { + chars[String.fromCharCode(font.chars[i].id)] = font.chars[i]; + } + + for (var _i = 0; _i < font.kernings.length; _i++) { + var firstString = String.fromCharCode(font.kernings[_i].first); + kernings[firstString] = kernings[firstString] || {}; + kernings[firstString][String.fromCharCode(font.kernings[_i].second)] = font.kernings[_i].amount; + } + + loadPages(_this, _path["default"].dirname(file), font.pages).then(function (pages) { + cb(null, { + chars: chars, + kernings: kernings, + pages: pages, + common: font.common, + info: font.info + }); + }); + }); + }); + } + }, + "class": { + /** + * Draws a text on a image on a given boundary + * @param {Jimp} font a bitmap font loaded from `Jimp.loadFont` command + * @param {number} x the x position to start drawing the text + * @param {number} y the y position to start drawing the text + * @param {any} text the text to draw (string or object with `text`, `alignmentX`, and/or `alignmentY`) + * @param {number} maxWidth (optional) the boundary width to draw in + * @param {number} maxHeight (optional) the boundary height to draw in + * @param {function(Error, Jimp)} cb (optional) a function to call when the text is written + * @returns {Jimp} this for chaining of methods + */ + print: function print(font, x, y, text, maxWidth, maxHeight, cb) { + var _this2 = this; + + if (typeof maxWidth === 'function' && typeof cb === 'undefined') { + cb = maxWidth; + maxWidth = Infinity; + } + + if (typeof maxWidth === 'undefined') { + maxWidth = Infinity; + } + + if (typeof maxHeight === 'function' && typeof cb === 'undefined') { + cb = maxHeight; + maxHeight = Infinity; + } + + if (typeof maxHeight === 'undefined') { + maxHeight = Infinity; + } + + if ((0, _typeof2["default"])(font) !== 'object') { + return _utils.throwError.call(this, 'font must be a Jimp loadFont', cb); + } + + if (typeof x !== 'number' || typeof y !== 'number' || typeof maxWidth !== 'number') { + return _utils.throwError.call(this, 'x, y and maxWidth must be numbers', cb); + } + + if (typeof maxWidth !== 'number') { + return _utils.throwError.call(this, 'maxWidth must be a number', cb); + } + + if (typeof maxHeight !== 'number') { + return _utils.throwError.call(this, 'maxHeight must be a number', cb); + } + + var alignmentX; + var alignmentY; + + if ((0, _typeof2["default"])(text) === 'object' && text.text !== null && text.text !== undefined) { + alignmentX = text.alignmentX || this.constructor.HORIZONTAL_ALIGN_LEFT; + alignmentY = text.alignmentY || this.constructor.VERTICAL_ALIGN_TOP; + var _text = text; + text = _text.text; + } else { + alignmentX = this.constructor.HORIZONTAL_ALIGN_LEFT; + alignmentY = this.constructor.VERTICAL_ALIGN_TOP; + text = text.toString(); + } + + if (maxHeight !== Infinity && alignmentY === this.constructor.VERTICAL_ALIGN_BOTTOM) { + y += maxHeight - (0, _measureText.measureTextHeight)(font, text, maxWidth); + } else if (maxHeight !== Infinity && alignmentY === this.constructor.VERTICAL_ALIGN_MIDDLE) { + y += maxHeight / 2 - (0, _measureText.measureTextHeight)(font, text, maxWidth) / 2; + } + + var defaultCharWidth = Object.entries(font.chars)[0][1].xadvance; + + var _splitLines = splitLines(font, text, maxWidth), + lines = _splitLines.lines, + longestLine = _splitLines.longestLine; + + lines.forEach(function (line) { + var lineString = line.join(' '); + var alignmentWidth = xOffsetBasedOnAlignment(_this2.constructor, font, lineString, maxWidth, alignmentX); + printText.call(_this2, font, x + alignmentWidth, y, lineString, defaultCharWidth); + y += font.common.lineHeight; + }); + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(this, null, this, { + x: x + longestLine, + y: y + }); + } + + return this; + } + } + }; +}; + +exports["default"] = _default; +module.exports = exports.default; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 4803: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.measureText = measureText; +exports.measureTextHeight = measureTextHeight; + +function measureText(font, text) { + var x = 0; + + for (var i = 0; i < text.length; i++) { + if (font.chars[text[i]]) { + var kerning = font.kernings[text[i]] && font.kernings[text[i]][text[i + 1]] ? font.kernings[text[i]][text[i + 1]] : 0; + x += (font.chars[text[i]].xadvance || 0) + kerning; + } + } + + return x; +} + +function measureTextHeight(font, text, maxWidth) { + var words = text.split(' '); + var line = ''; + var textTotalHeight = font.common.lineHeight; + + for (var n = 0; n < words.length; n++) { + var testLine = line + words[n] + ' '; + var testWidth = measureText(font, testLine); + + if (testWidth > maxWidth && n > 0) { + textTotalHeight += font.common.lineHeight; + line = words[n] + ' '; + } else { + line = testLine; + } + } + + return textTotalHeight; +} +//# sourceMappingURL=measure-text.js.map + +/***/ }), + +/***/ 5555: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +var _interopRequireDefault = __nccwpck_require__(3286); + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _utils = __nccwpck_require__(7403); + +var _resize = _interopRequireDefault(__nccwpck_require__(391)); + +var _resize2 = _interopRequireDefault(__nccwpck_require__(1846)); + +var _default = function _default() { + return { + constants: { + RESIZE_NEAREST_NEIGHBOR: 'nearestNeighbor', + RESIZE_BILINEAR: 'bilinearInterpolation', + RESIZE_BICUBIC: 'bicubicInterpolation', + RESIZE_HERMITE: 'hermiteInterpolation', + RESIZE_BEZIER: 'bezierInterpolation' + }, + "class": { + /** + * Resizes the image to a set width and height using a 2-pass bilinear algorithm + * @param {number} w the width to resize the image to (or Jimp.AUTO) + * @param {number} h the height to resize the image to (or Jimp.AUTO) + * @param {string} mode (optional) a scaling method (e.g. Jimp.RESIZE_BEZIER) + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ + resize: function resize(w, h, mode, cb) { + if (typeof w !== 'number' || typeof h !== 'number') { + return _utils.throwError.call(this, 'w and h must be numbers', cb); + } + + if (typeof mode === 'function' && typeof cb === 'undefined') { + cb = mode; + mode = null; + } + + if (w === this.constructor.AUTO && h === this.constructor.AUTO) { + return _utils.throwError.call(this, 'w and h cannot both be set to auto', cb); + } + + if (w === this.constructor.AUTO) { + w = this.bitmap.width * (h / this.bitmap.height); + } + + if (h === this.constructor.AUTO) { + h = this.bitmap.height * (w / this.bitmap.width); + } + + if (w < 0 || h < 0) { + return _utils.throwError.call(this, 'w and h must be positive numbers', cb); + } // round inputs + + + w = Math.round(w); + h = Math.round(h); + + if (typeof _resize2["default"][mode] === 'function') { + var dst = { + data: Buffer.alloc(w * h * 4), + width: w, + height: h + }; + + _resize2["default"][mode](this.bitmap, dst); + + this.bitmap = dst; + } else { + var image = this; + var resize = new _resize["default"](this.bitmap.width, this.bitmap.height, w, h, true, true, function (buffer) { + image.bitmap.data = Buffer.from(buffer); + image.bitmap.width = w; + image.bitmap.height = h; + }); + resize.resize(this.bitmap.data); + } + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(this, null, this); + } + + return this; + } + } + }; +}; + +exports["default"] = _default; +module.exports = exports.default; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 391: +/***/ ((module) => { + +"use strict"; + + +// JavaScript Image Resizer (c) 2012 - Grant Galitz +// Released to public domain 29 July 2013: https://github.com/grantgalitz/JS-Image-Resizer/issues/4 +function Resize(widthOriginal, heightOriginal, targetWidth, targetHeight, blendAlpha, interpolationPass, resizeCallback) { + this.widthOriginal = Math.abs(Math.floor(widthOriginal) || 0); + this.heightOriginal = Math.abs(Math.floor(heightOriginal) || 0); + this.targetWidth = Math.abs(Math.floor(targetWidth) || 0); + this.targetHeight = Math.abs(Math.floor(targetHeight) || 0); + this.colorChannels = blendAlpha ? 4 : 3; + this.interpolationPass = Boolean(interpolationPass); + this.resizeCallback = typeof resizeCallback === 'function' ? resizeCallback : function () {}; + this.targetWidthMultipliedByChannels = this.targetWidth * this.colorChannels; + this.originalWidthMultipliedByChannels = this.widthOriginal * this.colorChannels; + this.originalHeightMultipliedByChannels = this.heightOriginal * this.colorChannels; + this.widthPassResultSize = this.targetWidthMultipliedByChannels * this.heightOriginal; + this.finalResultSize = this.targetWidthMultipliedByChannels * this.targetHeight; + this.initialize(); +} + +Resize.prototype.initialize = function () { + // Perform some checks: + if (this.widthOriginal > 0 && this.heightOriginal > 0 && this.targetWidth > 0 && this.targetHeight > 0) { + this.configurePasses(); + } else { + throw new Error('Invalid settings specified for the resizer.'); + } +}; + +Resize.prototype.configurePasses = function () { + if (this.widthOriginal === this.targetWidth) { + // Bypass the width resizer pass: + this.resizeWidth = this.bypassResizer; + } else { + // Setup the width resizer pass: + this.ratioWeightWidthPass = this.widthOriginal / this.targetWidth; + + if (this.ratioWeightWidthPass < 1 && this.interpolationPass) { + this.initializeFirstPassBuffers(true); + this.resizeWidth = this.colorChannels === 4 ? this.resizeWidthInterpolatedRGBA : this.resizeWidthInterpolatedRGB; + } else { + this.initializeFirstPassBuffers(false); + this.resizeWidth = this.colorChannels === 4 ? this.resizeWidthRGBA : this.resizeWidthRGB; + } + } + + if (this.heightOriginal === this.targetHeight) { + // Bypass the height resizer pass: + this.resizeHeight = this.bypassResizer; + } else { + // Setup the height resizer pass: + this.ratioWeightHeightPass = this.heightOriginal / this.targetHeight; + + if (this.ratioWeightHeightPass < 1 && this.interpolationPass) { + this.initializeSecondPassBuffers(true); + this.resizeHeight = this.resizeHeightInterpolated; + } else { + this.initializeSecondPassBuffers(false); + this.resizeHeight = this.colorChannels === 4 ? this.resizeHeightRGBA : this.resizeHeightRGB; + } + } +}; + +Resize.prototype._resizeWidthInterpolatedRGBChannels = function (buffer, fourthChannel) { + var channelsNum = fourthChannel ? 4 : 3; + var ratioWeight = this.ratioWeightWidthPass; + var outputBuffer = this.widthBuffer; + var weight = 0; + var finalOffset = 0; + var pixelOffset = 0; + var firstWeight = 0; + var secondWeight = 0; + var targetPosition; // Handle for only one interpolation input being valid for start calculation: + + for (targetPosition = 0; weight < 1 / 3; targetPosition += channelsNum, weight += ratioWeight) { + for (finalOffset = targetPosition, pixelOffset = 0; finalOffset < this.widthPassResultSize; pixelOffset += this.originalWidthMultipliedByChannels, finalOffset += this.targetWidthMultipliedByChannels) { + outputBuffer[finalOffset] = buffer[pixelOffset]; + outputBuffer[finalOffset + 1] = buffer[pixelOffset + 1]; + outputBuffer[finalOffset + 2] = buffer[pixelOffset + 2]; + if (fourthChannel) outputBuffer[finalOffset + 3] = buffer[pixelOffset + 3]; + } + } // Adjust for overshoot of the last pass's counter: + + + weight -= 1 / 3; + var interpolationWidthSourceReadStop; + + for (interpolationWidthSourceReadStop = this.widthOriginal - 1; weight < interpolationWidthSourceReadStop; targetPosition += channelsNum, weight += ratioWeight) { + // Calculate weightings: + secondWeight = weight % 1; + firstWeight = 1 - secondWeight; // Interpolate: + + for (finalOffset = targetPosition, pixelOffset = Math.floor(weight) * channelsNum; finalOffset < this.widthPassResultSize; pixelOffset += this.originalWidthMultipliedByChannels, finalOffset += this.targetWidthMultipliedByChannels) { + outputBuffer[finalOffset + 0] = buffer[pixelOffset + 0] * firstWeight + buffer[pixelOffset + channelsNum + 0] * secondWeight; + outputBuffer[finalOffset + 1] = buffer[pixelOffset + 1] * firstWeight + buffer[pixelOffset + channelsNum + 1] * secondWeight; + outputBuffer[finalOffset + 2] = buffer[pixelOffset + 2] * firstWeight + buffer[pixelOffset + channelsNum + 2] * secondWeight; + if (fourthChannel) outputBuffer[finalOffset + 3] = buffer[pixelOffset + 3] * firstWeight + buffer[pixelOffset + channelsNum + 3] * secondWeight; + } + } // Handle for only one interpolation input being valid for end calculation: + + + for (interpolationWidthSourceReadStop = this.originalWidthMultipliedByChannels - channelsNum; targetPosition < this.targetWidthMultipliedByChannels; targetPosition += channelsNum) { + for (finalOffset = targetPosition, pixelOffset = interpolationWidthSourceReadStop; finalOffset < this.widthPassResultSize; pixelOffset += this.originalWidthMultipliedByChannels, finalOffset += this.targetWidthMultipliedByChannels) { + outputBuffer[finalOffset] = buffer[pixelOffset]; + outputBuffer[finalOffset + 1] = buffer[pixelOffset + 1]; + outputBuffer[finalOffset + 2] = buffer[pixelOffset + 2]; + if (fourthChannel) outputBuffer[finalOffset + 3] = buffer[pixelOffset + 3]; + } + } + + return outputBuffer; +}; + +Resize.prototype._resizeWidthRGBChannels = function (buffer, fourthChannel) { + var channelsNum = fourthChannel ? 4 : 3; + var ratioWeight = this.ratioWeightWidthPass; + var ratioWeightDivisor = 1 / ratioWeight; + var nextLineOffsetOriginalWidth = this.originalWidthMultipliedByChannels - channelsNum + 1; + var nextLineOffsetTargetWidth = this.targetWidthMultipliedByChannels - channelsNum + 1; + var output = this.outputWidthWorkBench; + var outputBuffer = this.widthBuffer; + var trustworthyColorsCount = this.outputWidthWorkBenchOpaquePixelsCount; + var weight = 0; + var amountToNext = 0; + var actualPosition = 0; + var currentPosition = 0; + var line = 0; + var pixelOffset = 0; + var outputOffset = 0; + var multiplier = 1; + var r = 0; + var g = 0; + var b = 0; + var a = 0; + + do { + for (line = 0; line < this.originalHeightMultipliedByChannels;) { + output[line++] = 0; + output[line++] = 0; + output[line++] = 0; + + if (fourthChannel) { + output[line++] = 0; + trustworthyColorsCount[line / channelsNum - 1] = 0; + } + } + + weight = ratioWeight; + + do { + amountToNext = 1 + actualPosition - currentPosition; + multiplier = Math.min(weight, amountToNext); + + for (line = 0, pixelOffset = actualPosition; line < this.originalHeightMultipliedByChannels; pixelOffset += nextLineOffsetOriginalWidth) { + r = buffer[pixelOffset]; + g = buffer[++pixelOffset]; + b = buffer[++pixelOffset]; + a = fourthChannel ? buffer[++pixelOffset] : 255; // Ignore RGB values if pixel is completely transparent + + output[line++] += (a ? r : 0) * multiplier; + output[line++] += (a ? g : 0) * multiplier; + output[line++] += (a ? b : 0) * multiplier; + + if (fourthChannel) { + output[line++] += a * multiplier; + trustworthyColorsCount[line / channelsNum - 1] += a ? multiplier : 0; + } + } + + if (weight >= amountToNext) { + actualPosition += channelsNum; + currentPosition = actualPosition; + weight -= amountToNext; + } else { + currentPosition += weight; + break; + } + } while (weight > 0 && actualPosition < this.originalWidthMultipliedByChannels); + + for (line = 0, pixelOffset = outputOffset; line < this.originalHeightMultipliedByChannels; pixelOffset += nextLineOffsetTargetWidth) { + weight = fourthChannel ? trustworthyColorsCount[line / channelsNum] : 1; + multiplier = fourthChannel ? weight ? 1 / weight : 0 : ratioWeightDivisor; + outputBuffer[pixelOffset] = output[line++] * multiplier; + outputBuffer[++pixelOffset] = output[line++] * multiplier; + outputBuffer[++pixelOffset] = output[line++] * multiplier; + if (fourthChannel) outputBuffer[++pixelOffset] = output[line++] * ratioWeightDivisor; + } + + outputOffset += channelsNum; + } while (outputOffset < this.targetWidthMultipliedByChannels); + + return outputBuffer; +}; + +Resize.prototype._resizeHeightRGBChannels = function (buffer, fourthChannel) { + var ratioWeight = this.ratioWeightHeightPass; + var ratioWeightDivisor = 1 / ratioWeight; + var output = this.outputHeightWorkBench; + var outputBuffer = this.heightBuffer; + var trustworthyColorsCount = this.outputHeightWorkBenchOpaquePixelsCount; + var weight = 0; + var amountToNext = 0; + var actualPosition = 0; + var currentPosition = 0; + var pixelOffset = 0; + var outputOffset = 0; + var caret = 0; + var multiplier = 1; + var r = 0; + var g = 0; + var b = 0; + var a = 0; + + do { + for (pixelOffset = 0; pixelOffset < this.targetWidthMultipliedByChannels;) { + output[pixelOffset++] = 0; + output[pixelOffset++] = 0; + output[pixelOffset++] = 0; + + if (fourthChannel) { + output[pixelOffset++] = 0; + trustworthyColorsCount[pixelOffset / 4 - 1] = 0; + } + } + + weight = ratioWeight; + + do { + amountToNext = 1 + actualPosition - currentPosition; + multiplier = Math.min(weight, amountToNext); + caret = actualPosition; + + for (pixelOffset = 0; pixelOffset < this.targetWidthMultipliedByChannels;) { + r = buffer[caret++]; + g = buffer[caret++]; + b = buffer[caret++]; + a = fourthChannel ? buffer[caret++] : 255; // Ignore RGB values if pixel is completely transparent + + output[pixelOffset++] += (a ? r : 0) * multiplier; + output[pixelOffset++] += (a ? g : 0) * multiplier; + output[pixelOffset++] += (a ? b : 0) * multiplier; + + if (fourthChannel) { + output[pixelOffset++] += a * multiplier; + trustworthyColorsCount[pixelOffset / 4 - 1] += a ? multiplier : 0; + } + } + + if (weight >= amountToNext) { + actualPosition = caret; + currentPosition = actualPosition; + weight -= amountToNext; + } else { + currentPosition += weight; + break; + } + } while (weight > 0 && actualPosition < this.widthPassResultSize); + + for (pixelOffset = 0; pixelOffset < this.targetWidthMultipliedByChannels;) { + weight = fourthChannel ? trustworthyColorsCount[pixelOffset / 4] : 1; + multiplier = fourthChannel ? weight ? 1 / weight : 0 : ratioWeightDivisor; + outputBuffer[outputOffset++] = Math.round(output[pixelOffset++] * multiplier); + outputBuffer[outputOffset++] = Math.round(output[pixelOffset++] * multiplier); + outputBuffer[outputOffset++] = Math.round(output[pixelOffset++] * multiplier); + + if (fourthChannel) { + outputBuffer[outputOffset++] = Math.round(output[pixelOffset++] * ratioWeightDivisor); + } + } + } while (outputOffset < this.finalResultSize); + + return outputBuffer; +}; + +Resize.prototype.resizeWidthInterpolatedRGB = function (buffer) { + return this._resizeWidthInterpolatedRGBChannels(buffer, false); +}; + +Resize.prototype.resizeWidthInterpolatedRGBA = function (buffer) { + return this._resizeWidthInterpolatedRGBChannels(buffer, true); +}; + +Resize.prototype.resizeWidthRGB = function (buffer) { + return this._resizeWidthRGBChannels(buffer, false); +}; + +Resize.prototype.resizeWidthRGBA = function (buffer) { + return this._resizeWidthRGBChannels(buffer, true); +}; + +Resize.prototype.resizeHeightInterpolated = function (buffer) { + var ratioWeight = this.ratioWeightHeightPass; + var outputBuffer = this.heightBuffer; + var weight = 0; + var finalOffset = 0; + var pixelOffset = 0; + var pixelOffsetAccumulated = 0; + var pixelOffsetAccumulated2 = 0; + var firstWeight = 0; + var secondWeight = 0; + var interpolationHeightSourceReadStop; // Handle for only one interpolation input being valid for start calculation: + + for (; weight < 1 / 3; weight += ratioWeight) { + for (pixelOffset = 0; pixelOffset < this.targetWidthMultipliedByChannels;) { + outputBuffer[finalOffset++] = Math.round(buffer[pixelOffset++]); + } + } // Adjust for overshoot of the last pass's counter: + + + weight -= 1 / 3; + + for (interpolationHeightSourceReadStop = this.heightOriginal - 1; weight < interpolationHeightSourceReadStop; weight += ratioWeight) { + // Calculate weightings: + secondWeight = weight % 1; + firstWeight = 1 - secondWeight; // Interpolate: + + pixelOffsetAccumulated = Math.floor(weight) * this.targetWidthMultipliedByChannels; + pixelOffsetAccumulated2 = pixelOffsetAccumulated + this.targetWidthMultipliedByChannels; + + for (pixelOffset = 0; pixelOffset < this.targetWidthMultipliedByChannels; ++pixelOffset) { + outputBuffer[finalOffset++] = Math.round(buffer[pixelOffsetAccumulated++] * firstWeight + buffer[pixelOffsetAccumulated2++] * secondWeight); + } + } // Handle for only one interpolation input being valid for end calculation: + + + while (finalOffset < this.finalResultSize) { + for (pixelOffset = 0, pixelOffsetAccumulated = interpolationHeightSourceReadStop * this.targetWidthMultipliedByChannels; pixelOffset < this.targetWidthMultipliedByChannels; ++pixelOffset) { + outputBuffer[finalOffset++] = Math.round(buffer[pixelOffsetAccumulated++]); + } + } + + return outputBuffer; +}; + +Resize.prototype.resizeHeightRGB = function (buffer) { + return this._resizeHeightRGBChannels(buffer, false); +}; + +Resize.prototype.resizeHeightRGBA = function (buffer) { + return this._resizeHeightRGBChannels(buffer, true); +}; + +Resize.prototype.resize = function (buffer) { + this.resizeCallback(this.resizeHeight(this.resizeWidth(buffer))); +}; + +Resize.prototype.bypassResizer = function (buffer) { + // Just return the buffer passed: + return buffer; +}; + +Resize.prototype.initializeFirstPassBuffers = function (BILINEARAlgo) { + // Initialize the internal width pass buffers: + this.widthBuffer = this.generateFloatBuffer(this.widthPassResultSize); + + if (!BILINEARAlgo) { + this.outputWidthWorkBench = this.generateFloatBuffer(this.originalHeightMultipliedByChannels); + + if (this.colorChannels > 3) { + this.outputWidthWorkBenchOpaquePixelsCount = this.generateFloat64Buffer(this.heightOriginal); + } + } +}; + +Resize.prototype.initializeSecondPassBuffers = function (BILINEARAlgo) { + // Initialize the internal height pass buffers: + this.heightBuffer = this.generateUint8Buffer(this.finalResultSize); + + if (!BILINEARAlgo) { + this.outputHeightWorkBench = this.generateFloatBuffer(this.targetWidthMultipliedByChannels); + + if (this.colorChannels > 3) { + this.outputHeightWorkBenchOpaquePixelsCount = this.generateFloat64Buffer(this.targetWidth); + } + } +}; + +Resize.prototype.generateFloatBuffer = function (bufferLength) { + // Generate a float32 typed array buffer: + try { + return new Float32Array(bufferLength); + } catch (error) { + return []; + } +}; + +Resize.prototype.generateFloat64Buffer = function (bufferLength) { + // Generate a float64 typed array buffer: + try { + return new Float64Array(bufferLength); + } catch (error) { + return []; + } +}; + +Resize.prototype.generateUint8Buffer = function (bufferLength) { + // Generate a uint8 typed array buffer: + try { + return new Uint8Array(bufferLength); + } catch (error) { + return []; + } +}; + +module.exports = Resize; +//# sourceMappingURL=resize.js.map + +/***/ }), + +/***/ 1846: +/***/ ((module) => { + +"use strict"; + + +/** + * Copyright (c) 2015 Guyon Roche + * + * 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 = { + nearestNeighbor: function nearestNeighbor(src, dst) { + var wSrc = src.width; + var hSrc = src.height; + var wDst = dst.width; + var hDst = dst.height; + var bufSrc = src.data; + var bufDst = dst.data; + + for (var i = 0; i < hDst; i++) { + for (var j = 0; j < wDst; j++) { + var posDst = (i * wDst + j) * 4; + var iSrc = Math.floor(i * hSrc / hDst); + var jSrc = Math.floor(j * wSrc / wDst); + var posSrc = (iSrc * wSrc + jSrc) * 4; + bufDst[posDst++] = bufSrc[posSrc++]; + bufDst[posDst++] = bufSrc[posSrc++]; + bufDst[posDst++] = bufSrc[posSrc++]; + bufDst[posDst++] = bufSrc[posSrc++]; + } + } + }, + bilinearInterpolation: function bilinearInterpolation(src, dst) { + var wSrc = src.width; + var hSrc = src.height; + var wDst = dst.width; + var hDst = dst.height; + var bufSrc = src.data; + var bufDst = dst.data; + + var interpolate = function interpolate(k, kMin, vMin, kMax, vMax) { + // special case - k is integer + if (kMin === kMax) { + return vMin; + } + + return Math.round((k - kMin) * vMax + (kMax - k) * vMin); + }; + + var assign = function assign(pos, offset, x, xMin, xMax, y, yMin, yMax) { + var posMin = (yMin * wSrc + xMin) * 4 + offset; + var posMax = (yMin * wSrc + xMax) * 4 + offset; + var vMin = interpolate(x, xMin, bufSrc[posMin], xMax, bufSrc[posMax]); // special case, y is integer + + if (yMax === yMin) { + bufDst[pos + offset] = vMin; + } else { + posMin = (yMax * wSrc + xMin) * 4 + offset; + posMax = (yMax * wSrc + xMax) * 4 + offset; + var vMax = interpolate(x, xMin, bufSrc[posMin], xMax, bufSrc[posMax]); + bufDst[pos + offset] = interpolate(y, yMin, vMin, yMax, vMax); + } + }; + + for (var i = 0; i < hDst; i++) { + for (var j = 0; j < wDst; j++) { + var posDst = (i * wDst + j) * 4; // x & y in src coordinates + + var x = j * wSrc / wDst; + var xMin = Math.floor(x); + var xMax = Math.min(Math.ceil(x), wSrc - 1); + var y = i * hSrc / hDst; + var yMin = Math.floor(y); + var yMax = Math.min(Math.ceil(y), hSrc - 1); + assign(posDst, 0, x, xMin, xMax, y, yMin, yMax); + assign(posDst, 1, x, xMin, xMax, y, yMin, yMax); + assign(posDst, 2, x, xMin, xMax, y, yMin, yMax); + assign(posDst, 3, x, xMin, xMax, y, yMin, yMax); + } + } + }, + _interpolate2D: function _interpolate2D(src, dst, options, interpolate) { + var bufSrc = src.data; + var bufDst = dst.data; + var wSrc = src.width; + var hSrc = src.height; + var wDst = dst.width; + var hDst = dst.height; // when dst smaller than src/2, interpolate first to a multiple between 0.5 and 1.0 src, then sum squares + + var wM = Math.max(1, Math.floor(wSrc / wDst)); + var wDst2 = wDst * wM; + var hM = Math.max(1, Math.floor(hSrc / hDst)); + var hDst2 = hDst * hM; // =========================================================== + // Pass 1 - interpolate rows + // buf1 has width of dst2 and height of src + + var buf1 = Buffer.alloc(wDst2 * hSrc * 4); + + for (var i = 0; i < hSrc; i++) { + for (var j = 0; j < wDst2; j++) { + // i in src coords, j in dst coords + // calculate x in src coords + // this interpolation requires 4 sample points and the two inner ones must be real + // the outer points can be fudged for the edges. + // therefore (wSrc-1)/wDst2 + var x = j * (wSrc - 1) / wDst2; + var xPos = Math.floor(x); + var t = x - xPos; + var srcPos = (i * wSrc + xPos) * 4; + var buf1Pos = (i * wDst2 + j) * 4; + + for (var k = 0; k < 4; k++) { + var kPos = srcPos + k; + var x0 = xPos > 0 ? bufSrc[kPos - 4] : 2 * bufSrc[kPos] - bufSrc[kPos + 4]; + var x1 = bufSrc[kPos]; + var x2 = bufSrc[kPos + 4]; + var x3 = xPos < wSrc - 2 ? bufSrc[kPos + 8] : 2 * bufSrc[kPos + 4] - bufSrc[kPos]; + buf1[buf1Pos + k] = interpolate(x0, x1, x2, x3, t); + } + } + } // this._writeFile(wDst2, hSrc, buf1, "out/buf1.jpg"); + // =========================================================== + // Pass 2 - interpolate columns + // buf2 has width and height of dst2 + + + var buf2 = Buffer.alloc(wDst2 * hDst2 * 4); + + for (var _i = 0; _i < hDst2; _i++) { + for (var _j = 0; _j < wDst2; _j++) { + // i&j in dst2 coords + // calculate y in buf1 coords + // this interpolation requires 4 sample points and the two inner ones must be real + // the outer points can be fudged for the edges. + // therefore (hSrc-1)/hDst2 + var y = _i * (hSrc - 1) / hDst2; + var yPos = Math.floor(y); + + var _t = y - yPos; + + var _buf1Pos = (yPos * wDst2 + _j) * 4; + + var buf2Pos = (_i * wDst2 + _j) * 4; + + for (var _k = 0; _k < 4; _k++) { + var _kPos = _buf1Pos + _k; + + var y0 = yPos > 0 ? buf1[_kPos - wDst2 * 4] : 2 * buf1[_kPos] - buf1[_kPos + wDst2 * 4]; + var y1 = buf1[_kPos]; + var y2 = buf1[_kPos + wDst2 * 4]; + var y3 = yPos < hSrc - 2 ? buf1[_kPos + wDst2 * 8] : 2 * buf1[_kPos + wDst2 * 4] - buf1[_kPos]; + buf2[buf2Pos + _k] = interpolate(y0, y1, y2, y3, _t); + } + } + } // this._writeFile(wDst2, hDst2, buf2, "out/buf2.jpg"); + // =========================================================== + // Pass 3 - scale to dst + + + var m = wM * hM; + + if (m > 1) { + for (var _i2 = 0; _i2 < hDst; _i2++) { + for (var _j2 = 0; _j2 < wDst; _j2++) { + // i&j in dst bounded coords + var r = 0; + var g = 0; + var b = 0; + var a = 0; + var realColors = 0; + + for (var _y = 0; _y < hM; _y++) { + var _yPos = _i2 * hM + _y; + + for (var _x = 0; _x < wM; _x++) { + var _xPos = _j2 * wM + _x; + + var xyPos = (_yPos * wDst2 + _xPos) * 4; + var pixelAlpha = buf2[xyPos + 3]; + + if (pixelAlpha) { + r += buf2[xyPos]; + g += buf2[xyPos + 1]; + b += buf2[xyPos + 2]; + realColors++; + } + + a += pixelAlpha; + } + } + + var pos = (_i2 * wDst + _j2) * 4; + bufDst[pos] = realColors ? Math.round(r / realColors) : 0; + bufDst[pos + 1] = realColors ? Math.round(g / realColors) : 0; + bufDst[pos + 2] = realColors ? Math.round(b / realColors) : 0; + bufDst[pos + 3] = Math.round(a / m); + } + } + } else { + // replace dst buffer with buf2 + dst.data = buf2; + } + }, + bicubicInterpolation: function bicubicInterpolation(src, dst, options) { + var interpolateCubic = function interpolateCubic(x0, x1, x2, x3, t) { + var a0 = x3 - x2 - x0 + x1; + var a1 = x0 - x1 - a0; + var a2 = x2 - x0; + var a3 = x1; + return Math.max(0, Math.min(255, a0 * (t * t * t) + a1 * (t * t) + a2 * t + a3)); + }; + + return this._interpolate2D(src, dst, options, interpolateCubic); + }, + hermiteInterpolation: function hermiteInterpolation(src, dst, options) { + var interpolateHermite = function interpolateHermite(x0, x1, x2, x3, t) { + var c0 = x1; + var c1 = 0.5 * (x2 - x0); + var c2 = x0 - 2.5 * x1 + 2 * x2 - 0.5 * x3; + var c3 = 0.5 * (x3 - x0) + 1.5 * (x1 - x2); + return Math.max(0, Math.min(255, Math.round(((c3 * t + c2) * t + c1) * t + c0))); + }; + + return this._interpolate2D(src, dst, options, interpolateHermite); + }, + bezierInterpolation: function bezierInterpolation(src, dst, options) { + // between 2 points y(n), y(n+1), use next points out, y(n-1), y(n+2) + // to predict control points (a & b) to be placed at n+0.5 + // ya(n) = y(n) + (y(n+1)-y(n-1))/4 + // yb(n) = y(n+1) - (y(n+2)-y(n))/4 + // then use std bezier to interpolate [n,n+1) + // y(n+t) = y(n)*(1-t)^3 + 3 * ya(n)*(1-t)^2*t + 3 * yb(n)*(1-t)*t^2 + y(n+1)*t^3 + // note the 3* factor for the two control points + // for edge cases, can choose: + // y(-1) = y(0) - 2*(y(1)-y(0)) + // y(w) = y(w-1) + 2*(y(w-1)-y(w-2)) + // but can go with y(-1) = y(0) and y(w) = y(w-1) + var interpolateBezier = function interpolateBezier(x0, x1, x2, x3, t) { + // x1, x2 are the knots, use x0 and x3 to calculate control points + var cp1 = x1 + (x2 - x0) / 4; + var cp2 = x2 - (x3 - x1) / 4; + var nt = 1 - t; + var c0 = x1 * nt * nt * nt; + var c1 = 3 * cp1 * nt * nt * t; + var c2 = 3 * cp2 * nt * t * t; + var c3 = x2 * t * t * t; + return Math.max(0, Math.min(255, Math.round(c0 + c1 + c2 + c3))); + }; + + return this._interpolate2D(src, dst, options, interpolateBezier); + } +}; +//# sourceMappingURL=resize2.js.map + +/***/ }), + +/***/ 6880: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _utils = __nccwpck_require__(7403); + +/** + * Rotates an image clockwise by an arbitrary number of degrees. NB: 'this' must be a Jimp object. + * @param {number} deg the number of degrees to rotate the image by + * @param {string|boolean} mode (optional) resize mode or a boolean, if false then the width and height of the image will not be changed + */ +function advancedRotate(deg, mode) { + deg %= 360; + var rad = deg * Math.PI / 180; + var cosine = Math.cos(rad); + var sine = Math.sin(rad); // the final width and height will change if resize == true + + var w = this.bitmap.width; + var h = this.bitmap.height; + + if (mode === true || typeof mode === 'string') { + // resize the image to it maximum dimension and blit the existing image + // onto the center so that when it is rotated the image is kept in bounds + // http://stackoverflow.com/questions/3231176/how-to-get-size-of-a-rotated-rectangle + // Plus 1 border pixel to ensure to show all rotated result for some cases. + w = Math.ceil(Math.abs(this.bitmap.width * cosine) + Math.abs(this.bitmap.height * sine)) + 1; + h = Math.ceil(Math.abs(this.bitmap.width * sine) + Math.abs(this.bitmap.height * cosine)) + 1; // Ensure destination to have even size to a better result. + + if (w % 2 !== 0) { + w++; + } + + if (h % 2 !== 0) { + h++; + } + + var c = this.cloneQuiet(); + this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) { + this.bitmap.data.writeUInt32BE(this._background, idx); + }); + var max = Math.max(w, h, this.bitmap.width, this.bitmap.height); + this.resize(max, max, mode); + this.blit(c, this.bitmap.width / 2 - c.bitmap.width / 2, this.bitmap.height / 2 - c.bitmap.height / 2); + } + + var bW = this.bitmap.width; + var bH = this.bitmap.height; + var dstBuffer = Buffer.alloc(this.bitmap.data.length); + + function createTranslationFunction(deltaX, deltaY) { + return function (x, y) { + return { + x: x + deltaX, + y: y + deltaY + }; + }; + } + + var translate2Cartesian = createTranslationFunction(-(bW / 2), -(bH / 2)); + var translate2Screen = createTranslationFunction(bW / 2 + 0.5, bH / 2 + 0.5); + + for (var y = 1; y <= bH; y++) { + for (var x = 1; x <= bW; x++) { + var cartesian = translate2Cartesian(x, y); + var source = translate2Screen(cosine * cartesian.x - sine * cartesian.y, cosine * cartesian.y + sine * cartesian.x); + var dstIdx = bW * (y - 1) + x - 1 << 2; + + if (source.x >= 0 && source.x < bW && source.y >= 0 && source.y < bH) { + var srcIdx = (bW * (source.y | 0) + source.x | 0) << 2; + var pixelRGBA = this.bitmap.data.readUInt32BE(srcIdx); + dstBuffer.writeUInt32BE(pixelRGBA, dstIdx); + } else { + // reset off-image pixels + dstBuffer.writeUInt32BE(this._background, dstIdx); + } + } + } + + this.bitmap.data = dstBuffer; + + if (mode === true || typeof mode === 'string') { + // now crop the image to the final size + var _x = bW / 2 - w / 2; + + var _y = bH / 2 - h / 2; + + this.crop(_x, _y, w, h); + } +} + +var _default = function _default() { + return { + /** + * Rotates the image clockwise by a number of degrees. By default the width and height of the image will be resized appropriately. + * @param {number} deg the number of degrees to rotate the image by + * @param {string|boolean} mode (optional) resize mode or a boolean, if false then the width and height of the image will not be changed + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ + rotate: function rotate(deg, mode, cb) { + // enable overloading + if (typeof mode === 'undefined' || mode === null) { + // e.g. image.resize(120); + // e.g. image.resize(120, null, cb); + // e.g. image.resize(120, undefined, cb); + mode = true; + } + + if (typeof mode === 'function' && typeof cb === 'undefined') { + // e.g. image.resize(120, cb); + cb = mode; + mode = true; + } + + if (typeof deg !== 'number') { + return _utils.throwError.call(this, 'deg must be a number', cb); + } + + if (typeof mode !== 'boolean' && typeof mode !== 'string') { + return _utils.throwError.call(this, 'mode must be a boolean or a string', cb); + } + + advancedRotate.call(this, deg, mode, cb); + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(this, null, this); + } + + return this; + } + }; +}; + +exports["default"] = _default; +module.exports = exports.default; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 8212: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _utils = __nccwpck_require__(7403); + +var _default = function _default() { + return { + /** + * Uniformly scales the image by a factor. + * @param {number} f the factor to scale the image by + * @param {string} mode (optional) a scaling method (e.g. Jimp.RESIZE_BEZIER) + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ + scale: function scale(f, mode, cb) { + if (typeof f !== 'number') { + return _utils.throwError.call(this, 'f must be a number', cb); + } + + if (f < 0) { + return _utils.throwError.call(this, 'f must be a positive number', cb); + } + + if (typeof mode === 'function' && typeof cb === 'undefined') { + cb = mode; + mode = null; + } + + var w = this.bitmap.width * f; + var h = this.bitmap.height * f; + this.resize(w, h, mode); + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(this, null, this); + } + + return this; + }, + + /** + * Scale the image to the largest size that fits inside the rectangle that has the given width and height. + * @param {number} w the width to resize the image to + * @param {number} h the height to resize the image to + * @param {string} mode (optional) a scaling method (e.g. Jimp.RESIZE_BEZIER) + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ + scaleToFit: function scaleToFit(w, h, mode, cb) { + if (typeof w !== 'number' || typeof h !== 'number') { + return _utils.throwError.call(this, 'w and h must be numbers', cb); + } + + if (typeof mode === 'function' && typeof cb === 'undefined') { + cb = mode; + mode = null; + } + + var f = w / h > this.bitmap.width / this.bitmap.height ? h / this.bitmap.height : w / this.bitmap.width; + this.scale(f, mode); + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(this, null, this); + } + + return this; + } + }; +}; + +exports["default"] = _default; +module.exports = exports.default; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 8178: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _utils = __nccwpck_require__(7403); + +/** + * Creates a circle out of an image. + * @param {function(Error, Jimp)} options (optional) + * opacity - opacity of the shadow between 0 and 1 + * size,- of the shadow + * blur - how blurry the shadow is + * x- x position of shadow + * y - y position of shadow + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ +var _default = function _default() { + return { + shadow: function shadow() { + var _this = this; + + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var cb = arguments.length > 1 ? arguments[1] : undefined; + + if (typeof options === 'function') { + cb = options; + options = {}; + } + + var _options = options, + _options$opacity = _options.opacity, + opacity = _options$opacity === void 0 ? 0.7 : _options$opacity, + _options$size = _options.size, + size = _options$size === void 0 ? 1.1 : _options$size, + _options$x = _options.x, + x = _options$x === void 0 ? -25 : _options$x, + _options$y = _options.y, + y = _options$y === void 0 ? 25 : _options$y, + _options$blur = _options.blur, + blur = _options$blur === void 0 ? 5 : _options$blur; // clone the image + + var orig = this.clone(); + var shadow = this.clone(); // turn all it's pixels black + + shadow.scan(0, 0, shadow.bitmap.width, shadow.bitmap.height, function (x, y, idx) { + shadow.bitmap.data[idx] = 0x00; + shadow.bitmap.data[idx + 1] = 0x00; + shadow.bitmap.data[idx + 2] = 0x00; // up the opacity a little, + + shadow.bitmap.data[idx + 3] = shadow.constructor.limit255(shadow.bitmap.data[idx + 3] * opacity); + _this.bitmap.data[idx] = 0x00; + _this.bitmap.data[idx + 1] = 0x00; + _this.bitmap.data[idx + 2] = 0x00; + _this.bitmap.data[idx + 3] = 0x00; + }); // enlarge it. This creates a "shadow". + + shadow.resize(shadow.bitmap.width * size, shadow.bitmap.height * size).blur(blur); // Then blit the "shadow" onto the background and the image on top of that. + + this.composite(shadow, x, y); + this.composite(orig, 0, 0); + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(this, null, this); + } + + return this; + } + }; +}; + +exports["default"] = _default; +module.exports = exports.default; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 897: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _utils = __nccwpck_require__(7403); + +/** + * Applies a minimum color threshold to a greyscale image. Converts image to greyscale by default + * @param {number} options object + * max: A number auto limited between 0 - 255 + * replace: (optional) A number auto limited between 0 - 255 (default 255) + * autoGreyscale: (optional) A boolean whether to apply greyscale beforehand (default true) + * @param {number} cb (optional) a callback for when complete + * @return {this} this for chaining of methods + */ +var _default = function _default() { + return { + threshold: function threshold(_ref, cb) { + var _this = this; + + var max = _ref.max, + _ref$replace = _ref.replace, + replace = _ref$replace === void 0 ? 255 : _ref$replace, + _ref$autoGreyscale = _ref.autoGreyscale, + autoGreyscale = _ref$autoGreyscale === void 0 ? true : _ref$autoGreyscale; + + if (typeof max !== 'number') { + return _utils.throwError.call(this, 'max must be a number', cb); + } + + if (typeof replace !== 'number') { + return _utils.throwError.call(this, 'replace must be a number', cb); + } + + if (typeof autoGreyscale !== 'boolean') { + return _utils.throwError.call(this, 'autoGreyscale must be a boolean', cb); + } + + max = this.constructor.limit255(max); + replace = this.constructor.limit255(replace); + + if (autoGreyscale) { + this.greyscale(); + } + + this.scanQuiet(0, 0, this.bitmap.width, this.bitmap.height, function (x, y, idx) { + var grey = _this.bitmap.data[idx] < max ? _this.bitmap.data[idx] : replace; + _this.bitmap.data[idx] = grey; + _this.bitmap.data[idx + 1] = grey; + _this.bitmap.data[idx + 2] = grey; + }); + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(this, null, this); + } + + return this; + } + }; +}; + +exports["default"] = _default; +module.exports = exports.default; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 4976: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +var _interopRequireDefault = __nccwpck_require__(3286); + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _toConsumableArray2 = _interopRequireDefault(__nccwpck_require__(3195)); + +var _timm = __nccwpck_require__(3567); + +var _pluginBlit = _interopRequireDefault(__nccwpck_require__(1485)); + +var _pluginBlur = _interopRequireDefault(__nccwpck_require__(6223)); + +var _pluginCircle = _interopRequireDefault(__nccwpck_require__(2005)); + +var _pluginColor = _interopRequireDefault(__nccwpck_require__(5432)); + +var _pluginContain = _interopRequireDefault(__nccwpck_require__(7125)); + +var _pluginCover = _interopRequireDefault(__nccwpck_require__(937)); + +var _pluginCrop = _interopRequireDefault(__nccwpck_require__(1623)); + +var _pluginDisplace = _interopRequireDefault(__nccwpck_require__(6096)); + +var _pluginDither = _interopRequireDefault(__nccwpck_require__(5808)); + +var _pluginFisheye = _interopRequireDefault(__nccwpck_require__(1885)); + +var _pluginFlip = _interopRequireDefault(__nccwpck_require__(2818)); + +var _pluginGaussian = _interopRequireDefault(__nccwpck_require__(2135)); + +var _pluginInvert = _interopRequireDefault(__nccwpck_require__(9534)); + +var _pluginMask = _interopRequireDefault(__nccwpck_require__(497)); + +var _pluginNormalize = _interopRequireDefault(__nccwpck_require__(7022)); + +var _pluginPrint = _interopRequireDefault(__nccwpck_require__(7996)); + +var _pluginResize = _interopRequireDefault(__nccwpck_require__(5555)); + +var _pluginRotate = _interopRequireDefault(__nccwpck_require__(6880)); + +var _pluginScale = _interopRequireDefault(__nccwpck_require__(8212)); + +var _pluginShadow = _interopRequireDefault(__nccwpck_require__(8178)); + +var _pluginThreshold = _interopRequireDefault(__nccwpck_require__(897)); + +var plugins = [_pluginBlit["default"], _pluginBlur["default"], _pluginCircle["default"], _pluginColor["default"], _pluginContain["default"], _pluginCover["default"], _pluginCrop["default"], _pluginDisplace["default"], _pluginDither["default"], _pluginFisheye["default"], _pluginFlip["default"], _pluginGaussian["default"], _pluginInvert["default"], _pluginMask["default"], _pluginNormalize["default"], _pluginPrint["default"], _pluginResize["default"], _pluginRotate["default"], _pluginScale["default"], _pluginShadow["default"], _pluginThreshold["default"]]; + +var _default = function _default(jimpEvChange) { + var initializedPlugins = plugins.map(function (pluginModule) { + var plugin = pluginModule(jimpEvChange) || {}; + + if (!plugin["class"] && !plugin.constants) { + // Default to class function + plugin = { + "class": plugin + }; + } + + return plugin; + }); + return _timm.mergeDeep.apply(void 0, (0, _toConsumableArray2["default"])(initializedPlugins)); +}; + +exports["default"] = _default; +module.exports = exports.default; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 7657: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +var _interopRequireDefault = __nccwpck_require__(3286); + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _defineProperty2 = _interopRequireDefault(__nccwpck_require__(1814)); + +var _pngjs = __nccwpck_require__(6413); + +var _utils = __nccwpck_require__(7403); + +var MIME_TYPE = 'image/png'; // PNG filter types + +var PNG_FILTER_AUTO = -1; +var PNG_FILTER_NONE = 0; +var PNG_FILTER_SUB = 1; +var PNG_FILTER_UP = 2; +var PNG_FILTER_AVERAGE = 3; +var PNG_FILTER_PATH = 4; + +var _default = function _default() { + return { + mime: (0, _defineProperty2["default"])({}, MIME_TYPE, ['png']), + constants: { + MIME_PNG: MIME_TYPE, + PNG_FILTER_AUTO: PNG_FILTER_AUTO, + PNG_FILTER_NONE: PNG_FILTER_NONE, + PNG_FILTER_SUB: PNG_FILTER_SUB, + PNG_FILTER_UP: PNG_FILTER_UP, + PNG_FILTER_AVERAGE: PNG_FILTER_AVERAGE, + PNG_FILTER_PATH: PNG_FILTER_PATH + }, + hasAlpha: (0, _defineProperty2["default"])({}, MIME_TYPE, true), + decoders: (0, _defineProperty2["default"])({}, MIME_TYPE, _pngjs.PNG.sync.read), + encoders: (0, _defineProperty2["default"])({}, MIME_TYPE, function (data) { + var png = new _pngjs.PNG({ + width: data.bitmap.width, + height: data.bitmap.height + }); + png.data = data.bitmap.data; + return _pngjs.PNG.sync.write(png, { + width: data.bitmap.width, + height: data.bitmap.height, + deflateLevel: data._deflateLevel, + deflateStrategy: data._deflateStrategy, + filterType: data._filterType, + colorType: typeof data._colorType === 'number' ? data._colorType : data._rgba ? 6 : 2, + inputHasAlpha: data._rgba + }); + }), + "class": { + _deflateLevel: 9, + _deflateStrategy: 3, + _filterType: PNG_FILTER_AUTO, + _colorType: null, + + /** + * Sets the deflate level used when saving as PNG format (default is 9) + * @param {number} l Deflate level to use 0-9. 0 is no compression. 9 (default) is maximum compression. + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ + deflateLevel: function deflateLevel(l, cb) { + if (typeof l !== 'number') { + return _utils.throwError.call(this, 'l must be a number', cb); + } + + if (l < 0 || l > 9) { + return _utils.throwError.call(this, 'l must be a number 0 - 9', cb); + } + + this._deflateLevel = Math.round(l); + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(this, null, this); + } + + return this; + }, + + /** + * Sets the deflate strategy used when saving as PNG format (default is 3) + * @param {number} s Deflate strategy to use 0-3. + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ + deflateStrategy: function deflateStrategy(s, cb) { + if (typeof s !== 'number') { + return _utils.throwError.call(this, 's must be a number', cb); + } + + if (s < 0 || s > 3) { + return _utils.throwError.call(this, 's must be a number 0 - 3', cb); + } + + this._deflateStrategy = Math.round(s); + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(this, null, this); + } + + return this; + }, + + /** + * Sets the filter type used when saving as PNG format (default is automatic filters) + * @param {number} f The quality to use -1-4. + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ + filterType: function filterType(f, cb) { + if (typeof f !== 'number') { + return _utils.throwError.call(this, 'n must be a number', cb); + } + + if (f < -1 || f > 4) { + return _utils.throwError.call(this, 'n must be -1 (auto) or a number 0 - 4', cb); + } + + this._filterType = Math.round(f); + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(this, null, this); + } + + return this; + }, + + /** + * Sets the color type used when saving as PNG format + * @param {number} s color type to use 0, 2, 4, 6. + * @param {function(Error, Jimp)} cb (optional) a callback for when complete + * @returns {Jimp} this for chaining of methods + */ + colorType: function colorType(s, cb) { + if (typeof s !== 'number') { + return _utils.throwError.call(this, 's must be a number', cb); + } + + if (s !== 0 && s !== 2 && s !== 4 && s !== 6) { + return _utils.throwError.call(this, 's must be a number 0, 2, 4, 6.', cb); + } + + this._colorType = Math.round(s); + + if ((0, _utils.isNodePattern)(cb)) { + cb.call(this, null, this); + } + + return this; + } + } + }; +}; + +exports["default"] = _default; +module.exports = exports.default; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 6447: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +var _interopRequireDefault = __nccwpck_require__(3286); + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _defineProperty2 = _interopRequireDefault(__nccwpck_require__(1814)); + +var _utif = _interopRequireDefault(__nccwpck_require__(6303)); + +var MIME_TYPE = 'image/tiff'; + +var _default = function _default() { + return { + mime: (0, _defineProperty2["default"])({}, MIME_TYPE, ['tiff', 'tif']), + constants: { + MIME_TIFF: MIME_TYPE + }, + decoders: (0, _defineProperty2["default"])({}, MIME_TYPE, function (data) { + var ifds = _utif["default"].decode(data); + + var page = ifds[0]; + + _utif["default"].decodeImages(data, ifds); + + var rgba = _utif["default"].toRGBA8(page); + + return { + data: Buffer.from(rgba), + width: page.t256[0], + height: page.t257[0] + }; + }), + encoders: (0, _defineProperty2["default"])({}, MIME_TYPE, function (image) { + var tiff = _utif["default"].encodeImage(image.bitmap.data, image.bitmap.width, image.bitmap.height); + + return Buffer.from(tiff); + }) + }; +}; + +exports["default"] = _default; +module.exports = exports.default; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 770: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +var _interopRequireDefault = __nccwpck_require__(3286); + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _timm = __nccwpck_require__(3567); + +var _jpeg = _interopRequireDefault(__nccwpck_require__(5177)); + +var _png = _interopRequireDefault(__nccwpck_require__(7657)); + +var _bmp = _interopRequireDefault(__nccwpck_require__(4858)); + +var _tiff = _interopRequireDefault(__nccwpck_require__(6447)); + +var _gif = _interopRequireDefault(__nccwpck_require__(8257)); + +var _default = function _default() { + return (0, _timm.mergeDeep)((0, _jpeg["default"])(), (0, _png["default"])(), (0, _bmp["default"])(), (0, _tiff["default"])(), (0, _gif["default"])()); +}; + +exports["default"] = _default; +module.exports = exports.default; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 7403: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +var _interopRequireDefault = __nccwpck_require__(3286); + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.isNodePattern = isNodePattern; +exports.throwError = throwError; +exports.scan = scan; +exports.scanIterator = scanIterator; + +var _regenerator = _interopRequireDefault(__nccwpck_require__(4210)); + +var _marked = +/*#__PURE__*/ +_regenerator["default"].mark(scanIterator); + +function isNodePattern(cb) { + if (typeof cb === 'undefined') { + return false; + } + + if (typeof cb !== 'function') { + throw new TypeError('Callback must be a function'); + } + + return true; +} + +function throwError(error, cb) { + if (typeof error === 'string') { + error = new Error(error); + } + + if (typeof cb === 'function') { + return cb.call(this, error); + } + + throw error; +} + +function scan(image, x, y, w, h, f) { + // round input + x = Math.round(x); + y = Math.round(y); + w = Math.round(w); + h = Math.round(h); + + for (var _y = y; _y < y + h; _y++) { + for (var _x = x; _x < x + w; _x++) { + var idx = image.bitmap.width * _y + _x << 2; + f.call(image, _x, _y, idx); + } + } + + return image; +} + +function scanIterator(image, x, y, w, h) { + var _y, _x, idx; + + return _regenerator["default"].wrap(function scanIterator$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + // round input + x = Math.round(x); + y = Math.round(y); + w = Math.round(w); + h = Math.round(h); + _y = y; + + case 5: + if (!(_y < y + h)) { + _context.next = 17; + break; + } + + _x = x; + + case 7: + if (!(_x < x + w)) { + _context.next = 14; + break; + } + + idx = image.bitmap.width * _y + _x << 2; + _context.next = 11; + return { + x: _x, + y: _y, + idx: idx, + image: image + }; + + case 11: + _x++; + _context.next = 7; + break; + + case 14: + _y++; + _context.next = 5; + break; + + case 17: + case "end": + return _context.stop(); + } + } + }, _marked); +} +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 8720: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var Converter = __nccwpck_require__(1605); + +/** + * Function get source and destination alphabet and return convert function + * + * @param {string|Array} srcAlphabet + * @param {string|Array} dstAlphabet + * + * @returns {function(number|Array)} + */ +function anyBase(srcAlphabet, dstAlphabet) { + var converter = new Converter(srcAlphabet, dstAlphabet); + /** + * Convert function + * + * @param {string|Array} number + * + * @return {string|Array} number + */ + return function (number) { + return converter.convert(number); + } +}; + +anyBase.BIN = '01'; +anyBase.OCT = '01234567'; +anyBase.DEC = '0123456789'; +anyBase.HEX = '0123456789abcdef'; + +module.exports = anyBase; + +/***/ }), + +/***/ 1605: +/***/ ((module) => { + +"use strict"; + + +/** + * Converter + * + * @param {string|Array} srcAlphabet + * @param {string|Array} dstAlphabet + * @constructor + */ +function Converter(srcAlphabet, dstAlphabet) { + if (!srcAlphabet || !dstAlphabet || !srcAlphabet.length || !dstAlphabet.length) { + throw new Error('Bad alphabet'); + } + this.srcAlphabet = srcAlphabet; + this.dstAlphabet = dstAlphabet; +} + +/** + * Convert number from source alphabet to destination alphabet + * + * @param {string|Array} number - number represented as a string or array of points + * + * @returns {string|Array} + */ +Converter.prototype.convert = function(number) { + var i, divide, newlen, + numberMap = {}, + fromBase = this.srcAlphabet.length, + toBase = this.dstAlphabet.length, + length = number.length, + result = typeof number === 'string' ? '' : []; + + if (!this.isValid(number)) { + throw new Error('Number "' + number + '" contains of non-alphabetic digits (' + this.srcAlphabet + ')'); + } + + if (this.srcAlphabet === this.dstAlphabet) { + return number; + } + + for (i = 0; i < length; i++) { + numberMap[i] = this.srcAlphabet.indexOf(number[i]); + } + do { + divide = 0; + newlen = 0; + for (i = 0; i < length; i++) { + divide = divide * fromBase + numberMap[i]; + if (divide >= toBase) { + numberMap[newlen++] = parseInt(divide / toBase, 10); + divide = divide % toBase; + } else if (newlen > 0) { + numberMap[newlen++] = 0; + } + } + length = newlen; + result = this.dstAlphabet.slice(divide, divide + 1).concat(result); + } while (newlen !== 0); + + return result; +}; + +/** + * Valid number with source alphabet + * + * @param {number} number + * + * @returns {boolean} + */ +Converter.prototype.isValid = function(number) { + var i = 0; + for (; i < number.length; ++i) { + if (this.srcAlphabet.indexOf(number[i]) === -1) { + return false; + } + } + return true; +}; + +module.exports = Converter; + +/***/ }), + +/***/ 4812: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +module.exports = +{ + parallel : __nccwpck_require__(8210), + serial : __nccwpck_require__(445), + serialOrdered : __nccwpck_require__(3578) +}; + + +/***/ }), + +/***/ 1700: +/***/ ((module) => { + +// API +module.exports = abort; + +/** + * Aborts leftover active jobs + * + * @param {object} state - current state object + */ +function abort(state) +{ + Object.keys(state.jobs).forEach(clean.bind(state)); + + // reset leftover jobs + state.jobs = {}; +} + +/** + * 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](); + } +} + + +/***/ }), + +/***/ 2794: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var defer = __nccwpck_require__(5295); + +// API +module.exports = async; + +/** + * 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; + + // check if async happened + defer(function() { isAsync = true; }); + + return function async_callback(err, result) + { + if (isAsync) + { + callback(err, result); + } + 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); + } +} + + +/***/ }), + +/***/ 9023: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var async = __nccwpck_require__(2794) + , abort = __nccwpck_require__(1700) + ; + +// API +module.exports = iterate; + +/** + * 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; + + state.jobs[key] = runJob(iterator, key, list[key], function(error, output) + { + // don't repeat yourself + // skip secondary callbacks + if (!(key in state.jobs)) + { + return; + } + + // 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 salvaged results + callback(error, state.results); + }); +} + +/** + * 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; + + // 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)); + } + + return aborter; +} + + +/***/ }), + +/***/ 2474: +/***/ ((module) => { + +// API +module.exports = state; + +/** + * 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 (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]); + }); + } + + return initState; +} + + +/***/ }), + +/***/ 7942: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var abort = __nccwpck_require__(1700) + , async = __nccwpck_require__(2794) + ; + +// API +module.exports = terminator; + +/** + * 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; + } + + // fast forward iteration index + this.index = this.size; + + // abort jobs + abort(this); + + // send back results we have so far + async(callback)(null, this.results); +} + + +/***/ }), + +/***/ 8210: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var iterate = __nccwpck_require__(9023) + , initState = __nccwpck_require__(2474) + , terminator = __nccwpck_require__(7942) + ; + +// Public API +module.exports = parallel; + +/** + * 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); + + while (state.index < (state['keyedList'] || list).length) + { + iterate(list, iterator, state, function(error, result) + { + if (error) + { + callback(error, result); + return; + } + + // looks like it's the last one + if (Object.keys(state.jobs).length === 0) + { + callback(null, state.results); + return; + } + }); + + state.index++; + } + + return terminator.bind(state, callback); +} + + +/***/ }), + +/***/ 445: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var serialOrdered = __nccwpck_require__(3578); + +// Public API +module.exports = serial; + +/** + * 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); +} + + +/***/ }), + +/***/ 3578: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var iterate = __nccwpck_require__(9023) + , initState = __nccwpck_require__(2474) + , terminator = __nccwpck_require__(7942) + ; + +// Public API +module.exports = serialOrdered; +// sorting helpers +module.exports.ascending = ascending; +module.exports.descending = descending; + +/** + * 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); + + iterate(list, iterator, state, function iteratorHandler(error, result) + { + if (error) + { + callback(error, result); + return; + } + + state.index++; + + // are we there yet? + if (state.index < (state['keyedList'] || list).length) + { + iterate(list, iterator, state, iteratorHandler); + return; + } + + // done here + callback(null, state.results); + }); + + return terminator.bind(state, callback); +} + +/* + * -- 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; +} + +/** + * 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); +} + + +/***/ }), + +/***/ 6545: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +module.exports = __nccwpck_require__(2618); + +/***/ }), + +/***/ 8104: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var utils = __nccwpck_require__(328); +var settle = __nccwpck_require__(3211); +var buildFullPath = __nccwpck_require__(1934); +var buildURL = __nccwpck_require__(646); +var http = __nccwpck_require__(3685); +var https = __nccwpck_require__(5687); +var httpFollow = (__nccwpck_require__(7707).http); +var httpsFollow = (__nccwpck_require__(7707).https); +var url = __nccwpck_require__(7310); +var zlib = __nccwpck_require__(9796); +var VERSION = (__nccwpck_require__(4322).version); +var transitionalDefaults = __nccwpck_require__(936); +var AxiosError = __nccwpck_require__(2093); +var CanceledError = __nccwpck_require__(4098); + +var isHttps = /https:?/; + +var supportedProtocols = [ 'http:', 'https:', 'file:' ]; + +/** + * + * @param {http.ClientRequestArgs} options + * @param {AxiosProxyConfig} proxy + * @param {string} location + */ +function setProxy(options, proxy, location) { + options.hostname = proxy.host; + options.host = proxy.host; + options.port = proxy.port; + options.path = location; + + // Basic proxy authorization + if (proxy.auth) { + var base64 = Buffer.from(proxy.auth.username + ':' + proxy.auth.password, 'utf8').toString('base64'); + options.headers['Proxy-Authorization'] = 'Basic ' + base64; + } + + // If a proxy is used, any redirects must also pass through the proxy + options.beforeRedirect = function beforeRedirect(redirection) { + redirection.headers.host = redirection.host; + setProxy(redirection, proxy, redirection.href); + }; +} + +/*eslint consistent-return:0*/ +module.exports = function httpAdapter(config) { + return new Promise(function dispatchHttpRequest(resolvePromise, rejectPromise) { + var onCanceled; + function done() { + if (config.cancelToken) { + config.cancelToken.unsubscribe(onCanceled); + } + + if (config.signal) { + config.signal.removeEventListener('abort', onCanceled); + } + } + var resolve = function resolve(value) { + done(); + resolvePromise(value); + }; + var rejected = false; + var reject = function reject(value) { + done(); + rejected = true; + rejectPromise(value); + }; + var data = config.data; + var headers = config.headers; + var headerNames = {}; + + Object.keys(headers).forEach(function storeLowerName(name) { + headerNames[name.toLowerCase()] = name; + }); + + // Set User-Agent (required by some servers) + // See https://github.com/axios/axios/issues/69 + if ('user-agent' in headerNames) { + // User-Agent is specified; handle case where no UA header is desired + if (!headers[headerNames['user-agent']]) { + delete headers[headerNames['user-agent']]; + } + // Otherwise, use specified value + } else { + // Only set header if it hasn't been set in config + headers['User-Agent'] = 'axios/' + VERSION; + } + + // support for https://www.npmjs.com/package/form-data api + if (utils.isFormData(data) && utils.isFunction(data.getHeaders)) { + Object.assign(headers, data.getHeaders()); + } else if (data && !utils.isStream(data)) { + if (Buffer.isBuffer(data)) { + // Nothing to do... + } else if (utils.isArrayBuffer(data)) { + data = Buffer.from(new Uint8Array(data)); + } else if (utils.isString(data)) { + data = Buffer.from(data, 'utf-8'); + } else { + return reject(new AxiosError( + 'Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream', + AxiosError.ERR_BAD_REQUEST, + config + )); + } + + if (config.maxBodyLength > -1 && data.length > config.maxBodyLength) { + return reject(new AxiosError( + 'Request body larger than maxBodyLength limit', + AxiosError.ERR_BAD_REQUEST, + config + )); + } + + // Add Content-Length header if data exists + if (!headerNames['content-length']) { + headers['Content-Length'] = data.length; + } + } + + // HTTP basic authentication + var auth = undefined; + if (config.auth) { + var username = config.auth.username || ''; + var password = config.auth.password || ''; + auth = username + ':' + password; + } + + // Parse url + var fullPath = buildFullPath(config.baseURL, config.url); + var parsed = url.parse(fullPath); + var protocol = parsed.protocol || supportedProtocols[0]; + + if (supportedProtocols.indexOf(protocol) === -1) { + return reject(new AxiosError( + 'Unsupported protocol ' + protocol, + AxiosError.ERR_BAD_REQUEST, + config + )); + } + + if (!auth && parsed.auth) { + var urlAuth = parsed.auth.split(':'); + var urlUsername = urlAuth[0] || ''; + var urlPassword = urlAuth[1] || ''; + auth = urlUsername + ':' + urlPassword; + } + + if (auth && headerNames.authorization) { + delete headers[headerNames.authorization]; + } + + var isHttpsRequest = isHttps.test(protocol); + var agent = isHttpsRequest ? config.httpsAgent : config.httpAgent; + + try { + buildURL(parsed.path, config.params, config.paramsSerializer).replace(/^\?/, ''); + } catch (err) { + var customErr = new Error(err.message); + customErr.config = config; + customErr.url = config.url; + customErr.exists = true; + reject(customErr); + } + + var options = { + path: buildURL(parsed.path, config.params, config.paramsSerializer).replace(/^\?/, ''), + method: config.method.toUpperCase(), + headers: headers, + agent: agent, + agents: { http: config.httpAgent, https: config.httpsAgent }, + auth: auth + }; + + if (config.socketPath) { + options.socketPath = config.socketPath; + } else { + options.hostname = parsed.hostname; + options.port = parsed.port; + } + + var proxy = config.proxy; + if (!proxy && proxy !== false) { + var proxyEnv = protocol.slice(0, -1) + '_proxy'; + var proxyUrl = process.env[proxyEnv] || process.env[proxyEnv.toUpperCase()]; + if (proxyUrl) { + var parsedProxyUrl = url.parse(proxyUrl); + var noProxyEnv = process.env.no_proxy || process.env.NO_PROXY; + var shouldProxy = true; + + if (noProxyEnv) { + var noProxy = noProxyEnv.split(',').map(function trim(s) { + return s.trim(); + }); + + shouldProxy = !noProxy.some(function proxyMatch(proxyElement) { + if (!proxyElement) { + return false; + } + if (proxyElement === '*') { + return true; + } + if (proxyElement[0] === '.' && + parsed.hostname.substr(parsed.hostname.length - proxyElement.length) === proxyElement) { + return true; + } + + return parsed.hostname === proxyElement; + }); + } + + if (shouldProxy) { + proxy = { + host: parsedProxyUrl.hostname, + port: parsedProxyUrl.port, + protocol: parsedProxyUrl.protocol + }; + + if (parsedProxyUrl.auth) { + var proxyUrlAuth = parsedProxyUrl.auth.split(':'); + proxy.auth = { + username: proxyUrlAuth[0], + password: proxyUrlAuth[1] + }; + } + } + } + } + + if (proxy) { + options.headers.host = parsed.hostname + (parsed.port ? ':' + parsed.port : ''); + setProxy(options, proxy, protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path); + } + + var transport; + var isHttpsProxy = isHttpsRequest && (proxy ? isHttps.test(proxy.protocol) : true); + if (config.transport) { + transport = config.transport; + } else if (config.maxRedirects === 0) { + transport = isHttpsProxy ? https : http; + } else { + if (config.maxRedirects) { + options.maxRedirects = config.maxRedirects; + } + if (config.beforeRedirect) { + options.beforeRedirect = config.beforeRedirect; + } + transport = isHttpsProxy ? httpsFollow : httpFollow; + } + + if (config.maxBodyLength > -1) { + options.maxBodyLength = config.maxBodyLength; + } + + if (config.insecureHTTPParser) { + options.insecureHTTPParser = config.insecureHTTPParser; + } + + // Create the request + var req = transport.request(options, function handleResponse(res) { + if (req.aborted) return; + + // uncompress the response body transparently if required + var stream = res; + + // return the last request in case of redirects + var lastRequest = res.req || req; + + + // if no content, is HEAD request or decompress disabled we should not decompress + if (res.statusCode !== 204 && lastRequest.method !== 'HEAD' && config.decompress !== false) { + switch (res.headers['content-encoding']) { + /*eslint default-case:0*/ + case 'gzip': + case 'compress': + case 'deflate': + // add the unzipper to the body stream processing pipeline + stream = stream.pipe(zlib.createUnzip()); + + // remove the content-encoding in order to not confuse downstream operations + delete res.headers['content-encoding']; + break; + } + } + + var response = { + status: res.statusCode, + statusText: res.statusMessage, + headers: res.headers, + config: config, + request: lastRequest + }; + + if (config.responseType === 'stream') { + response.data = stream; + settle(resolve, reject, response); + } else { + var responseBuffer = []; + var totalResponseBytes = 0; + stream.on('data', function handleStreamData(chunk) { + responseBuffer.push(chunk); + totalResponseBytes += chunk.length; + + // make sure the content length is not over the maxContentLength if specified + if (config.maxContentLength > -1 && totalResponseBytes > config.maxContentLength) { + // stream.destoy() emit aborted event before calling reject() on Node.js v16 + rejected = true; + stream.destroy(); + reject(new AxiosError('maxContentLength size of ' + config.maxContentLength + ' exceeded', + AxiosError.ERR_BAD_RESPONSE, config, lastRequest)); + } + }); + + stream.on('aborted', function handlerStreamAborted() { + if (rejected) { + return; + } + stream.destroy(); + reject(new AxiosError( + 'maxContentLength size of ' + config.maxContentLength + ' exceeded', + AxiosError.ERR_BAD_RESPONSE, + config, + lastRequest + )); + }); + + stream.on('error', function handleStreamError(err) { + if (req.aborted) return; + reject(AxiosError.from(err, null, config, lastRequest)); + }); + + stream.on('end', function handleStreamEnd() { + try { + var responseData = responseBuffer.length === 1 ? responseBuffer[0] : Buffer.concat(responseBuffer); + if (config.responseType !== 'arraybuffer') { + responseData = responseData.toString(config.responseEncoding); + if (!config.responseEncoding || config.responseEncoding === 'utf8') { + responseData = utils.stripBOM(responseData); + } + } + response.data = responseData; + } catch (err) { + reject(AxiosError.from(err, null, config, response.request, response)); + } + settle(resolve, reject, response); + }); + } + }); + + // Handle errors + req.on('error', function handleRequestError(err) { + // @todo remove + // if (req.aborted && err.code !== AxiosError.ERR_FR_TOO_MANY_REDIRECTS) return; + reject(AxiosError.from(err, null, config, req)); + }); + + // set tcp keep alive to prevent drop connection by peer + req.on('socket', function handleRequestSocket(socket) { + // default interval of sending ack packet is 1 minute + socket.setKeepAlive(true, 1000 * 60); + }); + + // Handle request timeout + if (config.timeout) { + // This is forcing a int timeout to avoid problems if the `req` interface doesn't handle other types. + var timeout = parseInt(config.timeout, 10); + + if (isNaN(timeout)) { + reject(new AxiosError( + 'error trying to parse `config.timeout` to int', + AxiosError.ERR_BAD_OPTION_VALUE, + config, + req + )); + + return; + } + + // Sometime, the response will be very slow, and does not respond, the connect event will be block by event loop system. + // And timer callback will be fired, and abort() will be invoked before connection, then get "socket hang up" and code ECONNRESET. + // At this time, if we have a large number of request, nodejs will hang up some socket on background. and the number will up and up. + // And then these socket which be hang up will devoring CPU little by little. + // ClientRequest.setTimeout will be fired on the specify milliseconds, and can make sure that abort() will be fired after connect. + req.setTimeout(timeout, function handleRequestTimeout() { + req.abort(); + var transitional = config.transitional || transitionalDefaults; + reject(new AxiosError( + 'timeout of ' + timeout + 'ms exceeded', + transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, + config, + req + )); + }); + } + + if (config.cancelToken || config.signal) { + // Handle cancellation + // eslint-disable-next-line func-names + onCanceled = function(cancel) { + if (req.aborted) return; + + req.abort(); + reject(!cancel || (cancel && cancel.type) ? new CanceledError() : cancel); + }; + + config.cancelToken && config.cancelToken.subscribe(onCanceled); + if (config.signal) { + config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled); + } + } + + + // Send the request + if (utils.isStream(data)) { + data.on('error', function handleStreamError(err) { + reject(AxiosError.from(err, config, null, req)); + }).pipe(req); + } else { + req.end(data); + } + }); +}; + + +/***/ }), + +/***/ 3454: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var utils = __nccwpck_require__(328); +var settle = __nccwpck_require__(3211); +var cookies = __nccwpck_require__(1545); +var buildURL = __nccwpck_require__(646); +var buildFullPath = __nccwpck_require__(1934); +var parseHeaders = __nccwpck_require__(6455); +var isURLSameOrigin = __nccwpck_require__(3608); +var transitionalDefaults = __nccwpck_require__(936); +var AxiosError = __nccwpck_require__(2093); +var CanceledError = __nccwpck_require__(4098); +var parseProtocol = __nccwpck_require__(6107); + +module.exports = function xhrAdapter(config) { + return new Promise(function dispatchXhrRequest(resolve, reject) { + var requestData = config.data; + var requestHeaders = config.headers; + var responseType = config.responseType; + var onCanceled; + function done() { + if (config.cancelToken) { + config.cancelToken.unsubscribe(onCanceled); + } + + if (config.signal) { + config.signal.removeEventListener('abort', onCanceled); + } + } + + if (utils.isFormData(requestData) && utils.isStandardBrowserEnv()) { + delete requestHeaders['Content-Type']; // Let the browser set it + } + + var request = new XMLHttpRequest(); + + // HTTP basic authentication + if (config.auth) { + var username = config.auth.username || ''; + var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : ''; + requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password); + } + + var fullPath = buildFullPath(config.baseURL, config.url); + + request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true); + + // Set the request timeout in MS + request.timeout = config.timeout; + + function onloadend() { + if (!request) { + return; + } + // Prepare the response + var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null; + var responseData = !responseType || responseType === 'text' || responseType === 'json' ? + request.responseText : request.response; + var response = { + data: responseData, + status: request.status, + statusText: request.statusText, + headers: responseHeaders, + config: config, + request: request + }; + + settle(function _resolve(value) { + resolve(value); + done(); + }, function _reject(err) { + reject(err); + done(); + }, response); + + // Clean up request + request = null; + } + + if ('onloadend' in request) { + // Use onloadend if available + request.onloadend = onloadend; + } else { + // Listen for ready state to emulate onloadend + request.onreadystatechange = function handleLoad() { + if (!request || request.readyState !== 4) { + return; + } + + // The request errored out and we didn't get a response, this will be + // handled by onerror instead + // With one exception: request that using file: protocol, most browsers + // will return status as 0 even though it's a successful request + if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { + return; + } + // readystate handler is calling before onerror or ontimeout handlers, + // so we should call onloadend on the next 'tick' + setTimeout(onloadend); + }; + } + + // Handle browser request cancellation (as opposed to a manual cancellation) + request.onabort = function handleAbort() { + if (!request) { + return; + } + + reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request)); + + // Clean up request + request = null; + }; + + // Handle low level network errors + request.onerror = function handleError() { + // Real errors are hidden from us by the browser + // onerror should only fire if it's a network error + reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request, request)); + + // Clean up request + request = null; + }; + + // Handle timeout + request.ontimeout = function handleTimeout() { + var timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded'; + var transitional = config.transitional || transitionalDefaults; + if (config.timeoutErrorMessage) { + timeoutErrorMessage = config.timeoutErrorMessage; + } + reject(new AxiosError( + timeoutErrorMessage, + transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, + config, + request)); + + // Clean up request + request = null; + }; + + // Add xsrf header + // This is only done if running in a standard browser environment. + // Specifically not if we're in a web worker, or react-native. + if (utils.isStandardBrowserEnv()) { + // Add xsrf header + var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ? + cookies.read(config.xsrfCookieName) : + undefined; + + if (xsrfValue) { + requestHeaders[config.xsrfHeaderName] = xsrfValue; + } + } + + // Add headers to the request + if ('setRequestHeader' in request) { + utils.forEach(requestHeaders, function setRequestHeader(val, key) { + if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') { + // Remove Content-Type if data is undefined + delete requestHeaders[key]; + } else { + // Otherwise add header to the request + request.setRequestHeader(key, val); + } + }); + } + + // Add withCredentials to request if needed + if (!utils.isUndefined(config.withCredentials)) { + request.withCredentials = !!config.withCredentials; + } + + // Add responseType to request if needed + if (responseType && responseType !== 'json') { + request.responseType = config.responseType; + } + + // Handle progress if needed + if (typeof config.onDownloadProgress === 'function') { + request.addEventListener('progress', config.onDownloadProgress); + } + + // Not all browsers support upload events + if (typeof config.onUploadProgress === 'function' && request.upload) { + request.upload.addEventListener('progress', config.onUploadProgress); + } + + if (config.cancelToken || config.signal) { + // Handle cancellation + // eslint-disable-next-line func-names + onCanceled = function(cancel) { + if (!request) { + return; + } + reject(!cancel || (cancel && cancel.type) ? new CanceledError() : cancel); + request.abort(); + request = null; + }; + + config.cancelToken && config.cancelToken.subscribe(onCanceled); + if (config.signal) { + config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled); + } + } + + if (!requestData) { + requestData = null; + } + + var protocol = parseProtocol(fullPath); + + if (protocol && [ 'http', 'https', 'file' ].indexOf(protocol) === -1) { + reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config)); + return; + } + + + // Send the request + request.send(requestData); + }); +}; + + +/***/ }), + +/***/ 2618: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var utils = __nccwpck_require__(328); +var bind = __nccwpck_require__(7065); +var Axios = __nccwpck_require__(746); +var mergeConfig = __nccwpck_require__(4831); +var defaults = __nccwpck_require__(1626); + +/** + * Create an instance of Axios + * + * @param {Object} defaultConfig The default config for the instance + * @return {Axios} A new instance of Axios + */ +function createInstance(defaultConfig) { + var context = new Axios(defaultConfig); + var instance = bind(Axios.prototype.request, context); + + // Copy axios.prototype to instance + utils.extend(instance, Axios.prototype, context); + + // Copy context to instance + utils.extend(instance, context); + + // Factory for creating new instances + instance.create = function create(instanceConfig) { + return createInstance(mergeConfig(defaultConfig, instanceConfig)); + }; + + return instance; +} + +// Create the default instance to be exported +var axios = createInstance(defaults); + +// Expose Axios class to allow class inheritance +axios.Axios = Axios; + +// Expose Cancel & CancelToken +axios.CanceledError = __nccwpck_require__(4098); +axios.CancelToken = __nccwpck_require__(1587); +axios.isCancel = __nccwpck_require__(4057); +axios.VERSION = (__nccwpck_require__(4322).version); +axios.toFormData = __nccwpck_require__(470); + +// Expose AxiosError class +axios.AxiosError = __nccwpck_require__(2093); + +// alias for CanceledError for backward compatibility +axios.Cancel = axios.CanceledError; + +// Expose all/spread +axios.all = function all(promises) { + return Promise.all(promises); +}; +axios.spread = __nccwpck_require__(4850); + +// Expose isAxiosError +axios.isAxiosError = __nccwpck_require__(650); + +module.exports = axios; + +// Allow use of default import syntax in TypeScript +module.exports["default"] = axios; + + +/***/ }), + +/***/ 1587: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var CanceledError = __nccwpck_require__(4098); + +/** + * A `CancelToken` is an object that can be used to request cancellation of an operation. + * + * @class + * @param {Function} executor The executor function. + */ +function CancelToken(executor) { + if (typeof executor !== 'function') { + throw new TypeError('executor must be a function.'); + } + + var resolvePromise; + + this.promise = new Promise(function promiseExecutor(resolve) { + resolvePromise = resolve; + }); + + var token = this; + + // eslint-disable-next-line func-names + this.promise.then(function(cancel) { + if (!token._listeners) return; + + var i; + var l = token._listeners.length; + + for (i = 0; i < l; i++) { + token._listeners[i](cancel); + } + token._listeners = null; + }); + + // eslint-disable-next-line func-names + this.promise.then = function(onfulfilled) { + var _resolve; + // eslint-disable-next-line func-names + var promise = new Promise(function(resolve) { + token.subscribe(resolve); + _resolve = resolve; + }).then(onfulfilled); + + promise.cancel = function reject() { + token.unsubscribe(_resolve); + }; + + return promise; + }; + + executor(function cancel(message) { + if (token.reason) { + // Cancellation has already been requested + return; + } + + token.reason = new CanceledError(message); + resolvePromise(token.reason); + }); +} + +/** + * Throws a `CanceledError` if cancellation has been requested. + */ +CancelToken.prototype.throwIfRequested = function throwIfRequested() { + if (this.reason) { + throw this.reason; + } +}; + +/** + * Subscribe to the cancel signal + */ + +CancelToken.prototype.subscribe = function subscribe(listener) { + if (this.reason) { + listener(this.reason); + return; + } + + if (this._listeners) { + this._listeners.push(listener); + } else { + this._listeners = [listener]; + } +}; + +/** + * Unsubscribe from the cancel signal + */ + +CancelToken.prototype.unsubscribe = function unsubscribe(listener) { + if (!this._listeners) { + return; + } + var index = this._listeners.indexOf(listener); + if (index !== -1) { + this._listeners.splice(index, 1); + } +}; + +/** + * Returns an object that contains a new `CancelToken` and a function that, when called, + * cancels the `CancelToken`. + */ +CancelToken.source = function source() { + var cancel; + var token = new CancelToken(function executor(c) { + cancel = c; + }); + return { + token: token, + cancel: cancel + }; +}; + +module.exports = CancelToken; + + +/***/ }), + +/***/ 4098: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var AxiosError = __nccwpck_require__(2093); +var utils = __nccwpck_require__(328); + +/** + * A `CanceledError` is an object that is thrown when an operation is canceled. + * + * @class + * @param {string=} message The message. + */ +function CanceledError(message) { + // eslint-disable-next-line no-eq-null,eqeqeq + AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED); + this.name = 'CanceledError'; +} + +utils.inherits(CanceledError, AxiosError, { + __CANCEL__: true +}); + +module.exports = CanceledError; + + +/***/ }), + +/***/ 4057: +/***/ ((module) => { + +"use strict"; + + +module.exports = function isCancel(value) { + return !!(value && value.__CANCEL__); +}; + + +/***/ }), + +/***/ 746: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var utils = __nccwpck_require__(328); +var buildURL = __nccwpck_require__(646); +var InterceptorManager = __nccwpck_require__(3214); +var dispatchRequest = __nccwpck_require__(5062); +var mergeConfig = __nccwpck_require__(4831); +var buildFullPath = __nccwpck_require__(1934); +var validator = __nccwpck_require__(1632); + +var validators = validator.validators; +/** + * Create a new instance of Axios + * + * @param {Object} instanceConfig The default config for the instance + */ +function Axios(instanceConfig) { + this.defaults = instanceConfig; + this.interceptors = { + request: new InterceptorManager(), + response: new InterceptorManager() + }; +} + +/** + * Dispatch a request + * + * @param {Object} config The config specific for this request (merged with this.defaults) + */ +Axios.prototype.request = function request(configOrUrl, config) { + /*eslint no-param-reassign:0*/ + // Allow for axios('example/url'[, config]) a la fetch API + if (typeof configOrUrl === 'string') { + config = config || {}; + config.url = configOrUrl; + } else { + config = configOrUrl || {}; + } + + config = mergeConfig(this.defaults, config); + + // Set config.method + if (config.method) { + config.method = config.method.toLowerCase(); + } else if (this.defaults.method) { + config.method = this.defaults.method.toLowerCase(); + } else { + config.method = 'get'; + } + + var transitional = config.transitional; + + if (transitional !== undefined) { + validator.assertOptions(transitional, { + silentJSONParsing: validators.transitional(validators.boolean), + forcedJSONParsing: validators.transitional(validators.boolean), + clarifyTimeoutError: validators.transitional(validators.boolean) + }, false); + } + + // filter out skipped interceptors + var requestInterceptorChain = []; + var synchronousRequestInterceptors = true; + this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { + if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) { + return; + } + + synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; + + requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); + }); + + var responseInterceptorChain = []; + this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { + responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); + }); + + var promise; + + if (!synchronousRequestInterceptors) { + var chain = [dispatchRequest, undefined]; + + Array.prototype.unshift.apply(chain, requestInterceptorChain); + chain = chain.concat(responseInterceptorChain); + + promise = Promise.resolve(config); + while (chain.length) { + promise = promise.then(chain.shift(), chain.shift()); + } + + return promise; + } + + + var newConfig = config; + while (requestInterceptorChain.length) { + var onFulfilled = requestInterceptorChain.shift(); + var onRejected = requestInterceptorChain.shift(); + try { + newConfig = onFulfilled(newConfig); + } catch (error) { + onRejected(error); + break; + } + } + + try { + promise = dispatchRequest(newConfig); + } catch (error) { + return Promise.reject(error); + } + + while (responseInterceptorChain.length) { + promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift()); + } + + return promise; +}; + +Axios.prototype.getUri = function getUri(config) { + config = mergeConfig(this.defaults, config); + var fullPath = buildFullPath(config.baseURL, config.url); + return buildURL(fullPath, config.params, config.paramsSerializer); +}; + +// Provide aliases for supported request methods +utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { + /*eslint func-names:0*/ + Axios.prototype[method] = function(url, config) { + return this.request(mergeConfig(config || {}, { + method: method, + url: url, + data: (config || {}).data + })); + }; +}); + +utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { + /*eslint func-names:0*/ + + function generateHTTPMethod(isForm) { + return function httpMethod(url, data, config) { + return this.request(mergeConfig(config || {}, { + method: method, + headers: isForm ? { + 'Content-Type': 'multipart/form-data' + } : {}, + url: url, + data: data + })); + }; + } + + Axios.prototype[method] = generateHTTPMethod(); + + Axios.prototype[method + 'Form'] = generateHTTPMethod(true); +}); + +module.exports = Axios; + + +/***/ }), + +/***/ 2093: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var utils = __nccwpck_require__(328); + +/** + * Create an Error with the specified message, config, error code, request and response. + * + * @param {string} message The error message. + * @param {string} [code] The error code (for example, 'ECONNABORTED'). + * @param {Object} [config] The config. + * @param {Object} [request] The request. + * @param {Object} [response] The response. + * @returns {Error} The created error. + */ +function AxiosError(message, code, config, request, response) { + Error.call(this); + this.message = message; + this.name = 'AxiosError'; + code && (this.code = code); + config && (this.config = config); + request && (this.request = request); + response && (this.response = response); +} + +utils.inherits(AxiosError, Error, { + toJSON: function toJSON() { + return { + // Standard + message: this.message, + name: this.name, + // Microsoft + description: this.description, + number: this.number, + // Mozilla + fileName: this.fileName, + lineNumber: this.lineNumber, + columnNumber: this.columnNumber, + stack: this.stack, + // Axios + config: this.config, + code: this.code, + status: this.response && this.response.status ? this.response.status : null + }; + } +}); + +var prototype = AxiosError.prototype; +var descriptors = {}; + +[ + 'ERR_BAD_OPTION_VALUE', + 'ERR_BAD_OPTION', + 'ECONNABORTED', + 'ETIMEDOUT', + 'ERR_NETWORK', + 'ERR_FR_TOO_MANY_REDIRECTS', + 'ERR_DEPRECATED', + 'ERR_BAD_RESPONSE', + 'ERR_BAD_REQUEST', + 'ERR_CANCELED' +// eslint-disable-next-line func-names +].forEach(function(code) { + descriptors[code] = {value: code}; +}); + +Object.defineProperties(AxiosError, descriptors); +Object.defineProperty(prototype, 'isAxiosError', {value: true}); + +// eslint-disable-next-line func-names +AxiosError.from = function(error, code, config, request, response, customProps) { + var axiosError = Object.create(prototype); + + utils.toFlatObject(error, axiosError, function filter(obj) { + return obj !== Error.prototype; + }); + + AxiosError.call(axiosError, error.message, code, config, request, response); + + axiosError.name = error.name; + + customProps && Object.assign(axiosError, customProps); + + return axiosError; +}; + +module.exports = AxiosError; + + +/***/ }), + +/***/ 3214: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var utils = __nccwpck_require__(328); + +function InterceptorManager() { + this.handlers = []; +} + +/** + * Add a new interceptor to the stack + * + * @param {Function} fulfilled The function to handle `then` for a `Promise` + * @param {Function} rejected The function to handle `reject` for a `Promise` + * + * @return {Number} An ID used to remove interceptor later + */ +InterceptorManager.prototype.use = function use(fulfilled, rejected, options) { + this.handlers.push({ + fulfilled: fulfilled, + rejected: rejected, + synchronous: options ? options.synchronous : false, + runWhen: options ? options.runWhen : null + }); + return this.handlers.length - 1; +}; + +/** + * Remove an interceptor from the stack + * + * @param {Number} id The ID that was returned by `use` + */ +InterceptorManager.prototype.eject = function eject(id) { + if (this.handlers[id]) { + this.handlers[id] = null; + } +}; + +/** + * Iterate over all the registered interceptors + * + * This method is particularly useful for skipping over any + * interceptors that may have become `null` calling `eject`. + * + * @param {Function} fn The function to call for each interceptor + */ +InterceptorManager.prototype.forEach = function forEach(fn) { + utils.forEach(this.handlers, function forEachHandler(h) { + if (h !== null) { + fn(h); + } + }); +}; + +module.exports = InterceptorManager; + + +/***/ }), + +/***/ 1934: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var isAbsoluteURL = __nccwpck_require__(1301); +var combineURLs = __nccwpck_require__(7189); + +/** + * Creates a new URL by combining the baseURL with the requestedURL, + * only when the requestedURL is not already an absolute URL. + * If the requestURL is absolute, this function returns the requestedURL untouched. + * + * @param {string} baseURL The base URL + * @param {string} requestedURL Absolute or relative URL to combine + * @returns {string} The combined full path + */ +module.exports = function buildFullPath(baseURL, requestedURL) { + if (baseURL && !isAbsoluteURL(requestedURL)) { + return combineURLs(baseURL, requestedURL); + } + return requestedURL; +}; + + +/***/ }), + +/***/ 5062: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var utils = __nccwpck_require__(328); +var transformData = __nccwpck_require__(9812); +var isCancel = __nccwpck_require__(4057); +var defaults = __nccwpck_require__(1626); +var CanceledError = __nccwpck_require__(4098); + +/** + * Throws a `CanceledError` if cancellation has been requested. + */ +function throwIfCancellationRequested(config) { + if (config.cancelToken) { + config.cancelToken.throwIfRequested(); + } + + if (config.signal && config.signal.aborted) { + throw new CanceledError(); + } +} + +/** + * Dispatch a request to the server using the configured adapter. + * + * @param {object} config The config that is to be used for the request + * @returns {Promise} The Promise to be fulfilled + */ +module.exports = function dispatchRequest(config) { + throwIfCancellationRequested(config); + + // Ensure headers exist + config.headers = config.headers || {}; + + // Transform request data + config.data = transformData.call( + config, + config.data, + config.headers, + config.transformRequest + ); + + // Flatten headers + config.headers = utils.merge( + config.headers.common || {}, + config.headers[config.method] || {}, + config.headers + ); + + utils.forEach( + ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], + function cleanHeaderConfig(method) { + delete config.headers[method]; + } + ); + + var adapter = config.adapter || defaults.adapter; + + return adapter(config).then(function onAdapterResolution(response) { + throwIfCancellationRequested(config); + + // Transform response data + response.data = transformData.call( + config, + response.data, + response.headers, + config.transformResponse + ); + + return response; + }, function onAdapterRejection(reason) { + if (!isCancel(reason)) { + throwIfCancellationRequested(config); + + // Transform response data + if (reason && reason.response) { + reason.response.data = transformData.call( + config, + reason.response.data, + reason.response.headers, + config.transformResponse + ); + } + } + + return Promise.reject(reason); + }); +}; + + +/***/ }), + +/***/ 4831: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var utils = __nccwpck_require__(328); + +/** + * Config-specific merge-function which creates a new config-object + * by merging two configuration objects together. + * + * @param {Object} config1 + * @param {Object} config2 + * @returns {Object} New object resulting from merging config2 to config1 + */ +module.exports = function mergeConfig(config1, config2) { + // eslint-disable-next-line no-param-reassign + config2 = config2 || {}; + var config = {}; + + function getMergedValue(target, source) { + if (utils.isPlainObject(target) && utils.isPlainObject(source)) { + return utils.merge(target, source); + } else if (utils.isPlainObject(source)) { + return utils.merge({}, source); + } else if (utils.isArray(source)) { + return source.slice(); + } + return source; + } + + // eslint-disable-next-line consistent-return + function mergeDeepProperties(prop) { + if (!utils.isUndefined(config2[prop])) { + return getMergedValue(config1[prop], config2[prop]); + } else if (!utils.isUndefined(config1[prop])) { + return getMergedValue(undefined, config1[prop]); + } + } + + // eslint-disable-next-line consistent-return + function valueFromConfig2(prop) { + if (!utils.isUndefined(config2[prop])) { + return getMergedValue(undefined, config2[prop]); + } + } + + // eslint-disable-next-line consistent-return + function defaultToConfig2(prop) { + if (!utils.isUndefined(config2[prop])) { + return getMergedValue(undefined, config2[prop]); + } else if (!utils.isUndefined(config1[prop])) { + return getMergedValue(undefined, config1[prop]); + } + } + + // eslint-disable-next-line consistent-return + function mergeDirectKeys(prop) { + if (prop in config2) { + return getMergedValue(config1[prop], config2[prop]); + } else if (prop in config1) { + return getMergedValue(undefined, config1[prop]); + } + } + + var mergeMap = { + 'url': valueFromConfig2, + 'method': valueFromConfig2, + 'data': valueFromConfig2, + 'baseURL': defaultToConfig2, + 'transformRequest': defaultToConfig2, + 'transformResponse': defaultToConfig2, + 'paramsSerializer': defaultToConfig2, + 'timeout': defaultToConfig2, + 'timeoutMessage': defaultToConfig2, + 'withCredentials': defaultToConfig2, + 'adapter': defaultToConfig2, + 'responseType': defaultToConfig2, + 'xsrfCookieName': defaultToConfig2, + 'xsrfHeaderName': defaultToConfig2, + 'onUploadProgress': defaultToConfig2, + 'onDownloadProgress': defaultToConfig2, + 'decompress': defaultToConfig2, + 'maxContentLength': defaultToConfig2, + 'maxBodyLength': defaultToConfig2, + 'beforeRedirect': defaultToConfig2, + 'transport': defaultToConfig2, + 'httpAgent': defaultToConfig2, + 'httpsAgent': defaultToConfig2, + 'cancelToken': defaultToConfig2, + 'socketPath': defaultToConfig2, + 'responseEncoding': defaultToConfig2, + 'validateStatus': mergeDirectKeys + }; + + utils.forEach(Object.keys(config1).concat(Object.keys(config2)), function computeConfigValue(prop) { + var merge = mergeMap[prop] || mergeDeepProperties; + var configValue = merge(prop); + (utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue); + }); + + return config; +}; + + +/***/ }), + +/***/ 3211: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var AxiosError = __nccwpck_require__(2093); + +/** + * Resolve or reject a Promise based on response status. + * + * @param {Function} resolve A function that resolves the promise. + * @param {Function} reject A function that rejects the promise. + * @param {object} response The response. + */ +module.exports = function settle(resolve, reject, response) { + var validateStatus = response.config.validateStatus; + if (!response.status || !validateStatus || validateStatus(response.status)) { + resolve(response); + } else { + reject(new AxiosError( + 'Request failed with status code ' + response.status, + [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4], + response.config, + response.request, + response + )); + } +}; + + +/***/ }), + +/***/ 9812: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var utils = __nccwpck_require__(328); +var defaults = __nccwpck_require__(1626); + +/** + * Transform the data for a request or a response + * + * @param {Object|String} data The data to be transformed + * @param {Array} headers The headers for the request or response + * @param {Array|Function} fns A single function or Array of functions + * @returns {*} The resulting transformed data + */ +module.exports = function transformData(data, headers, fns) { + var context = this || defaults; + /*eslint no-param-reassign:0*/ + utils.forEach(fns, function transform(fn) { + data = fn.call(context, data, headers); + }); + + return data; +}; + + +/***/ }), + +/***/ 7024: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +// eslint-disable-next-line strict +module.exports = __nccwpck_require__(4334); + + +/***/ }), + +/***/ 1626: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var utils = __nccwpck_require__(328); +var normalizeHeaderName = __nccwpck_require__(6240); +var AxiosError = __nccwpck_require__(2093); +var transitionalDefaults = __nccwpck_require__(936); +var toFormData = __nccwpck_require__(470); + +var DEFAULT_CONTENT_TYPE = { + 'Content-Type': 'application/x-www-form-urlencoded' +}; + +function setContentTypeIfUnset(headers, value) { + if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) { + headers['Content-Type'] = value; + } +} + +function getDefaultAdapter() { + var adapter; + if (typeof XMLHttpRequest !== 'undefined') { + // For browsers use XHR adapter + adapter = __nccwpck_require__(3454); + } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') { + // For node use HTTP adapter + adapter = __nccwpck_require__(8104); + } + return adapter; +} + +function stringifySafely(rawValue, parser, encoder) { + if (utils.isString(rawValue)) { + try { + (parser || JSON.parse)(rawValue); + return utils.trim(rawValue); + } catch (e) { + if (e.name !== 'SyntaxError') { + throw e; + } + } + } + + return (encoder || JSON.stringify)(rawValue); +} + +var defaults = { + + transitional: transitionalDefaults, + + adapter: getDefaultAdapter(), + + transformRequest: [function transformRequest(data, headers) { + normalizeHeaderName(headers, 'Accept'); + normalizeHeaderName(headers, 'Content-Type'); + + if (utils.isFormData(data) || + utils.isArrayBuffer(data) || + utils.isBuffer(data) || + utils.isStream(data) || + utils.isFile(data) || + utils.isBlob(data) + ) { + return data; + } + if (utils.isArrayBufferView(data)) { + return data.buffer; + } + if (utils.isURLSearchParams(data)) { + setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8'); + return data.toString(); + } + + var isObjectPayload = utils.isObject(data); + var contentType = headers && headers['Content-Type']; + + var isFileList; + + if ((isFileList = utils.isFileList(data)) || (isObjectPayload && contentType === 'multipart/form-data')) { + var _FormData = this.env && this.env.FormData; + return toFormData(isFileList ? {'files[]': data} : data, _FormData && new _FormData()); + } else if (isObjectPayload || contentType === 'application/json') { + setContentTypeIfUnset(headers, 'application/json'); + return stringifySafely(data); + } + + return data; + }], + + transformResponse: [function transformResponse(data) { + var transitional = this.transitional || defaults.transitional; + var silentJSONParsing = transitional && transitional.silentJSONParsing; + var forcedJSONParsing = transitional && transitional.forcedJSONParsing; + var strictJSONParsing = !silentJSONParsing && this.responseType === 'json'; + + if (strictJSONParsing || (forcedJSONParsing && utils.isString(data) && data.length)) { + try { + return JSON.parse(data); + } catch (e) { + if (strictJSONParsing) { + if (e.name === 'SyntaxError') { + throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response); + } + throw e; + } + } + } + + return data; + }], + + /** + * A timeout in milliseconds to abort a request. If set to 0 (default) a + * timeout is not created. + */ + timeout: 0, + + xsrfCookieName: 'XSRF-TOKEN', + xsrfHeaderName: 'X-XSRF-TOKEN', + + maxContentLength: -1, + maxBodyLength: -1, + + env: { + FormData: __nccwpck_require__(7024) + }, + + validateStatus: function validateStatus(status) { + return status >= 200 && status < 300; + }, + + headers: { + common: { + 'Accept': 'application/json, text/plain, */*' + } + } +}; + +utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) { + defaults.headers[method] = {}; +}); + +utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { + defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE); +}); + +module.exports = defaults; + + +/***/ }), + +/***/ 936: +/***/ ((module) => { + +"use strict"; + + +module.exports = { + silentJSONParsing: true, + forcedJSONParsing: true, + clarifyTimeoutError: false +}; + + +/***/ }), + +/***/ 4322: +/***/ ((module) => { + +module.exports = { + "version": "0.27.2" +}; + +/***/ }), + +/***/ 7065: +/***/ ((module) => { + +"use strict"; + + +module.exports = function bind(fn, thisArg) { + return function wrap() { + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + return fn.apply(thisArg, args); + }; +}; + + +/***/ }), + +/***/ 646: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var utils = __nccwpck_require__(328); + +function encode(val) { + return encodeURIComponent(val). + replace(/%3A/gi, ':'). + replace(/%24/g, '$'). + replace(/%2C/gi, ','). + replace(/%20/g, '+'). + replace(/%5B/gi, '['). + replace(/%5D/gi, ']'); +} + +/** + * Build a URL by appending params to the end + * + * @param {string} url The base of the url (e.g., http://www.google.com) + * @param {object} [params] The params to be appended + * @returns {string} The formatted url + */ +module.exports = function buildURL(url, params, paramsSerializer) { + /*eslint no-param-reassign:0*/ + if (!params) { + return url; + } + + var serializedParams; + if (paramsSerializer) { + serializedParams = paramsSerializer(params); + } else if (utils.isURLSearchParams(params)) { + serializedParams = params.toString(); + } else { + var parts = []; + + utils.forEach(params, function serialize(val, key) { + if (val === null || typeof val === 'undefined') { + return; + } + + if (utils.isArray(val)) { + key = key + '[]'; + } else { + val = [val]; + } + + utils.forEach(val, function parseValue(v) { + if (utils.isDate(v)) { + v = v.toISOString(); + } else if (utils.isObject(v)) { + v = JSON.stringify(v); + } + parts.push(encode(key) + '=' + encode(v)); + }); + }); + + serializedParams = parts.join('&'); + } + + if (serializedParams) { + var hashmarkIndex = url.indexOf('#'); + if (hashmarkIndex !== -1) { + url = url.slice(0, hashmarkIndex); + } + + url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; + } + + return url; +}; + + +/***/ }), + +/***/ 7189: +/***/ ((module) => { + +"use strict"; + + +/** + * Creates a new URL by combining the specified URLs + * + * @param {string} baseURL The base URL + * @param {string} relativeURL The relative URL + * @returns {string} The combined URL + */ +module.exports = function combineURLs(baseURL, relativeURL) { + return relativeURL + ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') + : baseURL; +}; + + +/***/ }), + +/***/ 1545: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var utils = __nccwpck_require__(328); + +module.exports = ( + utils.isStandardBrowserEnv() ? + + // Standard browser envs support document.cookie + (function standardBrowserEnv() { + return { + write: function write(name, value, expires, path, domain, secure) { + var cookie = []; + cookie.push(name + '=' + encodeURIComponent(value)); + + if (utils.isNumber(expires)) { + cookie.push('expires=' + new Date(expires).toGMTString()); + } + + if (utils.isString(path)) { + cookie.push('path=' + path); + } + + if (utils.isString(domain)) { + cookie.push('domain=' + domain); + } + + if (secure === true) { + cookie.push('secure'); + } + + document.cookie = cookie.join('; '); + }, + + read: function read(name) { + var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); + return (match ? decodeURIComponent(match[3]) : null); + }, + + remove: function remove(name) { + this.write(name, '', Date.now() - 86400000); + } + }; + })() : + + // Non standard browser env (web workers, react-native) lack needed support. + (function nonStandardBrowserEnv() { + return { + write: function write() {}, + read: function read() { return null; }, + remove: function remove() {} + }; + })() +); + + +/***/ }), + +/***/ 1301: +/***/ ((module) => { + +"use strict"; + + +/** + * Determines whether the specified URL is absolute + * + * @param {string} url The URL to test + * @returns {boolean} True if the specified URL is absolute, otherwise false + */ +module.exports = function isAbsoluteURL(url) { + // A URL is considered absolute if it begins with "://" or "//" (protocol-relative URL). + // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed + // by any combination of letters, digits, plus, period, or hyphen. + return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url); +}; + + +/***/ }), + +/***/ 650: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var utils = __nccwpck_require__(328); + +/** + * Determines whether the payload is an error thrown by Axios + * + * @param {*} payload The value to test + * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false + */ +module.exports = function isAxiosError(payload) { + return utils.isObject(payload) && (payload.isAxiosError === true); +}; + + +/***/ }), + +/***/ 3608: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var utils = __nccwpck_require__(328); + +module.exports = ( + utils.isStandardBrowserEnv() ? + + // Standard browser envs have full support of the APIs needed to test + // whether the request URL is of the same origin as current location. + (function standardBrowserEnv() { + var msie = /(msie|trident)/i.test(navigator.userAgent); + var urlParsingNode = document.createElement('a'); + var originURL; + + /** + * Parse a URL to discover it's components + * + * @param {String} url The URL to be parsed + * @returns {Object} + */ + function resolveURL(url) { + var href = url; + + if (msie) { + // IE needs attribute set twice to normalize properties + urlParsingNode.setAttribute('href', href); + href = urlParsingNode.href; + } + + urlParsingNode.setAttribute('href', href); + + // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils + return { + href: urlParsingNode.href, + protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', + host: urlParsingNode.host, + search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', + hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', + hostname: urlParsingNode.hostname, + port: urlParsingNode.port, + pathname: (urlParsingNode.pathname.charAt(0) === '/') ? + urlParsingNode.pathname : + '/' + urlParsingNode.pathname + }; + } + + originURL = resolveURL(window.location.href); + + /** + * Determine if a URL shares the same origin as the current location + * + * @param {String} requestURL The URL to test + * @returns {boolean} True if URL shares the same origin, otherwise false + */ + return function isURLSameOrigin(requestURL) { + var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL; + return (parsed.protocol === originURL.protocol && + parsed.host === originURL.host); + }; + })() : + + // Non standard browser envs (web workers, react-native) lack needed support. + (function nonStandardBrowserEnv() { + return function isURLSameOrigin() { + return true; + }; + })() +); + + +/***/ }), + +/***/ 6240: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var utils = __nccwpck_require__(328); + +module.exports = function normalizeHeaderName(headers, normalizedName) { + utils.forEach(headers, function processHeader(value, name) { + if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) { + headers[normalizedName] = value; + delete headers[name]; + } + }); +}; + + +/***/ }), + +/***/ 6455: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var utils = __nccwpck_require__(328); + +// Headers whose duplicates are ignored by node +// c.f. https://nodejs.org/api/http.html#http_message_headers +var ignoreDuplicateOf = [ + 'age', 'authorization', 'content-length', 'content-type', 'etag', + 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', + 'last-modified', 'location', 'max-forwards', 'proxy-authorization', + 'referer', 'retry-after', 'user-agent' +]; + +/** + * Parse headers into an object + * + * ``` + * Date: Wed, 27 Aug 2014 08:58:49 GMT + * Content-Type: application/json + * Connection: keep-alive + * Transfer-Encoding: chunked + * ``` + * + * @param {String} headers Headers needing to be parsed + * @returns {Object} Headers parsed into an object + */ +module.exports = function parseHeaders(headers) { + var parsed = {}; + var key; + var val; + var i; + + if (!headers) { return parsed; } + + utils.forEach(headers.split('\n'), function parser(line) { + i = line.indexOf(':'); + key = utils.trim(line.substr(0, i)).toLowerCase(); + val = utils.trim(line.substr(i + 1)); + + if (key) { + if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) { + return; + } + if (key === 'set-cookie') { + parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]); + } else { + parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; + } + } + }); + + return parsed; +}; + + +/***/ }), + +/***/ 6107: +/***/ ((module) => { + +"use strict"; + + +module.exports = function parseProtocol(url) { + var match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url); + return match && match[1] || ''; +}; + + +/***/ }), + +/***/ 4850: +/***/ ((module) => { + +"use strict"; + + +/** + * Syntactic sugar for invoking a function and expanding an array for arguments. + * + * Common use case would be to use `Function.prototype.apply`. + * + * ```js + * function f(x, y, z) {} + * var args = [1, 2, 3]; + * f.apply(null, args); + * ``` + * + * With `spread` this example can be re-written. + * + * ```js + * spread(function(x, y, z) {})([1, 2, 3]); + * ``` + * + * @param {Function} callback + * @returns {Function} + */ +module.exports = function spread(callback) { + return function wrap(arr) { + return callback.apply(null, arr); + }; +}; + + +/***/ }), + +/***/ 470: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var utils = __nccwpck_require__(328); + +/** + * Convert a data object to FormData + * @param {Object} obj + * @param {?Object} [formData] + * @returns {Object} + **/ + +function toFormData(obj, formData) { + // eslint-disable-next-line no-param-reassign + formData = formData || new FormData(); + + var stack = []; + + function convertValue(value) { + if (value === null) return ''; + + if (utils.isDate(value)) { + return value.toISOString(); + } + + if (utils.isArrayBuffer(value) || utils.isTypedArray(value)) { + return typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value); + } + + return value; + } + + function build(data, parentKey) { + if (utils.isPlainObject(data) || utils.isArray(data)) { + if (stack.indexOf(data) !== -1) { + throw Error('Circular reference detected in ' + parentKey); + } + + stack.push(data); + + utils.forEach(data, function each(value, key) { + if (utils.isUndefined(value)) return; + var fullKey = parentKey ? parentKey + '.' + key : key; + var arr; + + if (value && !parentKey && typeof value === 'object') { + if (utils.endsWith(key, '{}')) { + // eslint-disable-next-line no-param-reassign + value = JSON.stringify(value); + } else if (utils.endsWith(key, '[]') && (arr = utils.toArray(value))) { + // eslint-disable-next-line func-names + arr.forEach(function(el) { + !utils.isUndefined(el) && formData.append(fullKey, convertValue(el)); + }); + return; + } + } + + build(value, fullKey); + }); + + stack.pop(); + } else { + formData.append(parentKey, convertValue(data)); + } + } + + build(obj); + + return formData; +} + +module.exports = toFormData; + + +/***/ }), + +/***/ 1632: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var VERSION = (__nccwpck_require__(4322).version); +var AxiosError = __nccwpck_require__(2093); + +var validators = {}; + +// eslint-disable-next-line func-names +['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach(function(type, i) { + validators[type] = function validator(thing) { + return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type; + }; +}); + +var deprecatedWarnings = {}; + +/** + * Transitional option validator + * @param {function|boolean?} validator - set to false if the transitional option has been removed + * @param {string?} version - deprecated version / removed since version + * @param {string?} message - some message with additional info + * @returns {function} + */ +validators.transitional = function transitional(validator, version, message) { + function formatMessage(opt, desc) { + return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : ''); + } + + // eslint-disable-next-line func-names + return function(value, opt, opts) { + if (validator === false) { + throw new AxiosError( + formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')), + AxiosError.ERR_DEPRECATED + ); + } + + if (version && !deprecatedWarnings[opt]) { + deprecatedWarnings[opt] = true; + // eslint-disable-next-line no-console + console.warn( + formatMessage( + opt, + ' has been deprecated since v' + version + ' and will be removed in the near future' + ) + ); + } + + return validator ? validator(value, opt, opts) : true; + }; +}; + +/** + * Assert object's properties type + * @param {object} options + * @param {object} schema + * @param {boolean?} allowUnknown + */ + +function assertOptions(options, schema, allowUnknown) { + if (typeof options !== 'object') { + throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE); + } + var keys = Object.keys(options); + var i = keys.length; + while (i-- > 0) { + var opt = keys[i]; + var validator = schema[opt]; + if (validator) { + var value = options[opt]; + var result = value === undefined || validator(value, opt, options); + if (result !== true) { + throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE); + } + continue; + } + if (allowUnknown !== true) { + throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION); + } + } +} + +module.exports = { + assertOptions: assertOptions, + validators: validators +}; + + +/***/ }), + +/***/ 328: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var bind = __nccwpck_require__(7065); + +// utils is a library of generic helper functions non-specific to axios + +var toString = Object.prototype.toString; + +// eslint-disable-next-line func-names +var kindOf = (function(cache) { + // eslint-disable-next-line func-names + return function(thing) { + var str = toString.call(thing); + return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase()); + }; +})(Object.create(null)); + +function kindOfTest(type) { + type = type.toLowerCase(); + return function isKindOf(thing) { + return kindOf(thing) === type; + }; +} + +/** + * Determine if a value is an Array + * + * @param {Object} val The value to test + * @returns {boolean} True if value is an Array, otherwise false + */ +function isArray(val) { + return Array.isArray(val); +} + +/** + * Determine if a value is undefined + * + * @param {Object} val The value to test + * @returns {boolean} True if the value is undefined, otherwise false + */ +function isUndefined(val) { + return typeof val === 'undefined'; +} + +/** + * Determine if a value is a Buffer + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Buffer, otherwise false + */ +function isBuffer(val) { + return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) + && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val); +} + +/** + * Determine if a value is an ArrayBuffer + * + * @function + * @param {Object} val The value to test + * @returns {boolean} True if value is an ArrayBuffer, otherwise false + */ +var isArrayBuffer = kindOfTest('ArrayBuffer'); + + +/** + * Determine if a value is a view on an ArrayBuffer + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false + */ +function isArrayBufferView(val) { + var result; + if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { + result = ArrayBuffer.isView(val); + } else { + result = (val) && (val.buffer) && (isArrayBuffer(val.buffer)); + } + return result; +} + +/** + * Determine if a value is a String + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a String, otherwise false + */ +function isString(val) { + return typeof val === 'string'; +} + +/** + * Determine if a value is a Number + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Number, otherwise false + */ +function isNumber(val) { + return typeof val === 'number'; +} + +/** + * Determine if a value is an Object + * + * @param {Object} val The value to test + * @returns {boolean} True if value is an Object, otherwise false + */ +function isObject(val) { + return val !== null && typeof val === 'object'; +} + +/** + * Determine if a value is a plain Object + * + * @param {Object} val The value to test + * @return {boolean} True if value is a plain Object, otherwise false + */ +function isPlainObject(val) { + if (kindOf(val) !== 'object') { + return false; + } + + var prototype = Object.getPrototypeOf(val); + return prototype === null || prototype === Object.prototype; +} + +/** + * Determine if a value is a Date + * + * @function + * @param {Object} val The value to test + * @returns {boolean} True if value is a Date, otherwise false + */ +var isDate = kindOfTest('Date'); + +/** + * Determine if a value is a File + * + * @function + * @param {Object} val The value to test + * @returns {boolean} True if value is a File, otherwise false + */ +var isFile = kindOfTest('File'); + +/** + * Determine if a value is a Blob + * + * @function + * @param {Object} val The value to test + * @returns {boolean} True if value is a Blob, otherwise false + */ +var isBlob = kindOfTest('Blob'); + +/** + * Determine if a value is a FileList + * + * @function + * @param {Object} val The value to test + * @returns {boolean} True if value is a File, otherwise false + */ +var isFileList = kindOfTest('FileList'); + +/** + * Determine if a value is a Function + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Function, otherwise false + */ +function isFunction(val) { + return toString.call(val) === '[object Function]'; +} + +/** + * Determine if a value is a Stream + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Stream, otherwise false + */ +function isStream(val) { + return isObject(val) && isFunction(val.pipe); +} + +/** + * Determine if a value is a FormData + * + * @param {Object} thing The value to test + * @returns {boolean} True if value is an FormData, otherwise false + */ +function isFormData(thing) { + var pattern = '[object FormData]'; + return thing && ( + (typeof FormData === 'function' && thing instanceof FormData) || + toString.call(thing) === pattern || + (isFunction(thing.toString) && thing.toString() === pattern) + ); +} + +/** + * Determine if a value is a URLSearchParams object + * @function + * @param {Object} val The value to test + * @returns {boolean} True if value is a URLSearchParams object, otherwise false + */ +var isURLSearchParams = kindOfTest('URLSearchParams'); + +/** + * Trim excess whitespace off the beginning and end of a string + * + * @param {String} str The String to trim + * @returns {String} The String freed of excess whitespace + */ +function trim(str) { + return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, ''); +} + +/** + * Determine if we're running in a standard browser environment + * + * This allows axios to run in a web worker, and react-native. + * Both environments support XMLHttpRequest, but not fully standard globals. + * + * web workers: + * typeof window -> undefined + * typeof document -> undefined + * + * react-native: + * navigator.product -> 'ReactNative' + * nativescript + * navigator.product -> 'NativeScript' or 'NS' + */ +function isStandardBrowserEnv() { + if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' || + navigator.product === 'NativeScript' || + navigator.product === 'NS')) { + return false; + } + return ( + typeof window !== 'undefined' && + typeof document !== 'undefined' + ); +} + +/** + * Iterate over an Array or an Object invoking a function for each item. + * + * If `obj` is an Array callback will be called passing + * the value, index, and complete array for each item. + * + * If 'obj' is an Object callback will be called passing + * the value, key, and complete object for each property. + * + * @param {Object|Array} obj The object to iterate + * @param {Function} fn The callback to invoke for each item + */ +function forEach(obj, fn) { + // Don't bother if no value provided + if (obj === null || typeof obj === 'undefined') { + return; + } + + // Force an array if not already something iterable + if (typeof obj !== 'object') { + /*eslint no-param-reassign:0*/ + obj = [obj]; + } + + if (isArray(obj)) { + // Iterate over array values + for (var i = 0, l = obj.length; i < l; i++) { + fn.call(null, obj[i], i, obj); + } + } else { + // Iterate over object keys + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + fn.call(null, obj[key], key, obj); + } + } + } +} + +/** + * Accepts varargs expecting each argument to be an object, then + * immutably merges the properties of each object and returns result. + * + * When multiple objects contain the same key the later object in + * the arguments list will take precedence. + * + * Example: + * + * ```js + * var result = merge({foo: 123}, {foo: 456}); + * console.log(result.foo); // outputs 456 + * ``` + * + * @param {Object} obj1 Object to merge + * @returns {Object} Result of all merge properties + */ +function merge(/* obj1, obj2, obj3, ... */) { + var result = {}; + function assignValue(val, key) { + if (isPlainObject(result[key]) && isPlainObject(val)) { + result[key] = merge(result[key], val); + } else if (isPlainObject(val)) { + result[key] = merge({}, val); + } else if (isArray(val)) { + result[key] = val.slice(); + } else { + result[key] = val; + } + } + + for (var i = 0, l = arguments.length; i < l; i++) { + forEach(arguments[i], assignValue); + } + return result; +} + +/** + * Extends object a by mutably adding to it the properties of object b. + * + * @param {Object} a The object to be extended + * @param {Object} b The object to copy properties from + * @param {Object} thisArg The object to bind function to + * @return {Object} The resulting value of object a + */ +function extend(a, b, thisArg) { + forEach(b, function assignValue(val, key) { + if (thisArg && typeof val === 'function') { + a[key] = bind(val, thisArg); + } else { + a[key] = val; + } + }); + return a; +} + +/** + * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) + * + * @param {string} content with BOM + * @return {string} content value without BOM + */ +function stripBOM(content) { + if (content.charCodeAt(0) === 0xFEFF) { + content = content.slice(1); + } + return content; +} + +/** + * Inherit the prototype methods from one constructor into another + * @param {function} constructor + * @param {function} superConstructor + * @param {object} [props] + * @param {object} [descriptors] + */ + +function inherits(constructor, superConstructor, props, descriptors) { + constructor.prototype = Object.create(superConstructor.prototype, descriptors); + constructor.prototype.constructor = constructor; + props && Object.assign(constructor.prototype, props); +} + +/** + * Resolve object with deep prototype chain to a flat object + * @param {Object} sourceObj source object + * @param {Object} [destObj] + * @param {Function} [filter] + * @returns {Object} + */ + +function toFlatObject(sourceObj, destObj, filter) { + var props; + var i; + var prop; + var merged = {}; + + destObj = destObj || {}; + + do { + props = Object.getOwnPropertyNames(sourceObj); + i = props.length; + while (i-- > 0) { + prop = props[i]; + if (!merged[prop]) { + destObj[prop] = sourceObj[prop]; + merged[prop] = true; + } + } + sourceObj = Object.getPrototypeOf(sourceObj); + } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype); + + return destObj; +} + +/* + * determines whether a string ends with the characters of a specified string + * @param {String} str + * @param {String} searchString + * @param {Number} [position= 0] + * @returns {boolean} + */ +function endsWith(str, searchString, position) { + str = String(str); + if (position === undefined || position > str.length) { + position = str.length; + } + position -= searchString.length; + var lastIndex = str.indexOf(searchString, position); + return lastIndex !== -1 && lastIndex === position; +} + + +/** + * Returns new array from array like object + * @param {*} [thing] + * @returns {Array} + */ +function toArray(thing) { + if (!thing) return null; + var i = thing.length; + if (isUndefined(i)) return null; + var arr = new Array(i); + while (i-- > 0) { + arr[i] = thing[i]; + } + return arr; +} + +// eslint-disable-next-line func-names +var isTypedArray = (function(TypedArray) { + // eslint-disable-next-line func-names + return function(thing) { + return TypedArray && thing instanceof TypedArray; + }; +})(typeof Uint8Array !== 'undefined' && Object.getPrototypeOf(Uint8Array)); + +module.exports = { + isArray: isArray, + isArrayBuffer: isArrayBuffer, + isBuffer: isBuffer, + isFormData: isFormData, + isArrayBufferView: isArrayBufferView, + isString: isString, + isNumber: isNumber, + isObject: isObject, + isPlainObject: isPlainObject, + isUndefined: isUndefined, + isDate: isDate, + isFile: isFile, + isBlob: isBlob, + isFunction: isFunction, + isStream: isStream, + isURLSearchParams: isURLSearchParams, + isStandardBrowserEnv: isStandardBrowserEnv, + forEach: forEach, + merge: merge, + extend: extend, + trim: trim, + stripBOM: stripBOM, + inherits: inherits, + toFlatObject: toFlatObject, + kindOf: kindOf, + kindOfTest: kindOfTest, + endsWith: endsWith, + toArray: toArray, + isTypedArray: isTypedArray, + isFileList: isFileList +}; + + +/***/ }), + +/***/ 9417: +/***/ ((module) => { + +"use strict"; + +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 r = range(a, b, str); + + 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) + }; +} + +function maybeMatch(reg, str) { + var m = str.match(reg); + return m ? m[0] : null; +} + +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; + + if (ai >= 0 && bi > 0) { + if(a===b) { + return [ai, bi]; + } + 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); + } + + i = ai < bi && ai >= 0 ? ai : bi; + } + + if (begs.length) { + result = [ left, right ]; + } + } + + return result; +} + + +/***/ }), + +/***/ 9030: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/** + * @author shaozilee + * + * support 1bit 4bit 8bit 24bit decode + * encode with 24bit + * + */ + +var encode = __nccwpck_require__(4551), + decode = __nccwpck_require__(2767); + +module.exports = { + encode: encode, + decode: decode +}; + + +/***/ }), + +/***/ 2767: +/***/ ((module) => { + +/** + * @author shaozilee + * + * Bmp format decoder,support 1bit 4bit 8bit 24bit bmp + * + */ + +function BmpDecoder(buffer,is_with_alpha) { + this.pos = 0; + this.buffer = buffer; + this.is_with_alpha = !!is_with_alpha; + this.bottom_up = true; + this.flag = this.buffer.toString("utf-8", 0, this.pos += 2); + if (this.flag != "BM") throw new Error("Invalid BMP File"); + this.parseHeader(); + this.parseRGBA(); +} + +BmpDecoder.prototype.parseHeader = function() { + this.fileSize = this.buffer.readUInt32LE(this.pos); + this.pos += 4; + this.reserved = this.buffer.readUInt32LE(this.pos); + this.pos += 4; + this.offset = this.buffer.readUInt32LE(this.pos); + this.pos += 4; + this.headerSize = this.buffer.readUInt32LE(this.pos); + this.pos += 4; + this.width = this.buffer.readUInt32LE(this.pos); + this.pos += 4; + this.height = this.buffer.readInt32LE(this.pos); + this.pos += 4; + this.planes = this.buffer.readUInt16LE(this.pos); + this.pos += 2; + this.bitPP = this.buffer.readUInt16LE(this.pos); + this.pos += 2; + this.compress = this.buffer.readUInt32LE(this.pos); + this.pos += 4; + this.rawSize = this.buffer.readUInt32LE(this.pos); + this.pos += 4; + this.hr = this.buffer.readUInt32LE(this.pos); + this.pos += 4; + this.vr = this.buffer.readUInt32LE(this.pos); + this.pos += 4; + this.colors = this.buffer.readUInt32LE(this.pos); + this.pos += 4; + this.importantColors = this.buffer.readUInt32LE(this.pos); + this.pos += 4; + + if(this.bitPP === 16 && this.is_with_alpha){ + this.bitPP = 15 + } + if (this.bitPP < 15) { + var len = this.colors === 0 ? 1 << this.bitPP : this.colors; + this.palette = new Array(len); + for (var i = 0; i < len; i++) { + var blue = this.buffer.readUInt8(this.pos++); + var green = this.buffer.readUInt8(this.pos++); + var red = this.buffer.readUInt8(this.pos++); + var quad = this.buffer.readUInt8(this.pos++); + this.palette[i] = { + red: red, + green: green, + blue: blue, + quad: quad + }; + } + } + if(this.height < 0) { + this.height *= -1; + this.bottom_up = false; + } + +} + +BmpDecoder.prototype.parseRGBA = function() { + var bitn = "bit" + this.bitPP; + var len = this.width * this.height * 4; + this.data = new Buffer(len); + this[bitn](); +}; + +BmpDecoder.prototype.bit1 = function() { + var xlen = Math.ceil(this.width / 8); + var mode = xlen%4; + var y = this.height >= 0 ? this.height - 1 : -this.height + for (var y = this.height - 1; y >= 0; y--) { + var line = this.bottom_up ? y : this.height - 1 - y + for (var x = 0; x < xlen; x++) { + var b = this.buffer.readUInt8(this.pos++); + var location = line * this.width * 4 + x*8*4; + for (var i = 0; i < 8; i++) { + if(x*8+i>(7-i))&0x1)]; + + this.data[location+i*4] = 0; + this.data[location+i*4 + 1] = rgb.blue; + this.data[location+i*4 + 2] = rgb.green; + this.data[location+i*4 + 3] = rgb.red; + + }else{ + break; + } + } + } + + if (mode != 0){ + this.pos+=(4 - mode); + } + } +}; + +BmpDecoder.prototype.bit4 = function() { + //RLE-4 + if(this.compress == 2){ + this.data.fill(0xff); + + var location = 0; + var lines = this.bottom_up?this.height-1:0; + var low_nibble = false;//for all count of pixel + + while(location>4); + } + + if ((i & 1) && (i+1 < b)){ + c = this.buffer.readUInt8(this.pos++); + } + + low_nibble = !low_nibble; + } + + if ((((b+1) >> 1) & 1 ) == 1){ + this.pos++ + } + } + + }else{//encoded mode + for (var i = 0; i < a; i++) { + if (low_nibble) { + setPixelData.call(this, (b & 0x0f)); + } else { + setPixelData.call(this, (b & 0xf0)>>4); + } + low_nibble = !low_nibble; + } + } + + } + + + + + function setPixelData(rgbIndex){ + var rgb = this.palette[rgbIndex]; + this.data[location] = 0; + this.data[location + 1] = rgb.blue; + this.data[location + 2] = rgb.green; + this.data[location + 3] = rgb.red; + location+=4; + } + }else{ + + var xlen = Math.ceil(this.width/2); + var mode = xlen%4; + for (var y = this.height - 1; y >= 0; y--) { + var line = this.bottom_up ? y : this.height - 1 - y + for (var x = 0; x < xlen; x++) { + var b = this.buffer.readUInt8(this.pos++); + var location = line * this.width * 4 + x*2*4; + + var before = b>>4; + var after = b&0x0F; + + var rgb = this.palette[before]; + this.data[location] = 0; + this.data[location + 1] = rgb.blue; + this.data[location + 2] = rgb.green; + this.data[location + 3] = rgb.red; + + + if(x*2+1>=this.width)break; + + rgb = this.palette[after]; + + this.data[location+4] = 0; + this.data[location+4 + 1] = rgb.blue; + this.data[location+4 + 2] = rgb.green; + this.data[location+4 + 3] = rgb.red; + + } + + if (mode != 0){ + this.pos+=(4 - mode); + } + } + + } + +}; + +BmpDecoder.prototype.bit8 = function() { + //RLE-8 + if(this.compress == 1){ + this.data.fill(0xff); + + var location = 0; + var lines = this.bottom_up?this.height-1:0; + + while(location= 0; y--) { + var line = this.bottom_up ? y : this.height - 1 - y + for (var x = 0; x < this.width; x++) { + var b = this.buffer.readUInt8(this.pos++); + var location = line * this.width * 4 + x * 4; + if (b < this.palette.length) { + var rgb = this.palette[b]; + + this.data[location] = 0; + this.data[location + 1] = rgb.blue; + this.data[location + 2] = rgb.green; + this.data[location + 3] = rgb.red; + + } else { + this.data[location] = 0; + this.data[location + 1] = 0xFF; + this.data[location + 2] = 0xFF; + this.data[location + 3] = 0xFF; + } + } + if (mode != 0) { + this.pos += (4 - mode); + } + } + } +}; + +BmpDecoder.prototype.bit15 = function() { + var dif_w =this.width % 3; + var _11111 = parseInt("11111", 2),_1_5 = _11111; + for (var y = this.height - 1; y >= 0; y--) { + var line = this.bottom_up ? y : this.height - 1 - y + for (var x = 0; x < this.width; x++) { + + var B = this.buffer.readUInt16LE(this.pos); + this.pos+=2; + var blue = (B & _1_5) / _1_5 * 255 | 0; + var green = (B >> 5 & _1_5 ) / _1_5 * 255 | 0; + var red = (B >> 10 & _1_5) / _1_5 * 255 | 0; + var alpha = (B>>15)?0xFF:0x00; + + var location = line * this.width * 4 + x * 4; + + this.data[location] = alpha; + this.data[location + 1] = blue; + this.data[location + 2] = green; + this.data[location + 3] = red; + } + //skip extra bytes + this.pos += dif_w; + } +}; + +BmpDecoder.prototype.bit16 = function() { + var dif_w =(this.width % 2)*2; + //default xrgb555 + this.maskRed = 0x7C00; + this.maskGreen = 0x3E0; + this.maskBlue =0x1F; + this.mask0 = 0; + + if(this.compress == 3){ + this.maskRed = this.buffer.readUInt32LE(this.pos); + this.pos+=4; + this.maskGreen = this.buffer.readUInt32LE(this.pos); + this.pos+=4; + this.maskBlue = this.buffer.readUInt32LE(this.pos); + this.pos+=4; + this.mask0 = this.buffer.readUInt32LE(this.pos); + this.pos+=4; + } + + + var ns=[0,0,0]; + for (var i=0;i<16;i++){ + if ((this.maskRed>>i)&0x01) ns[0]++; + if ((this.maskGreen>>i)&0x01) ns[1]++; + if ((this.maskBlue>>i)&0x01) ns[2]++; + } + ns[1]+=ns[0]; ns[2]+=ns[1]; ns[0]=8-ns[0]; ns[1]-=8; ns[2]-=8; + + for (var y = this.height - 1; y >= 0; y--) { + var line = this.bottom_up ? y : this.height - 1 - y; + for (var x = 0; x < this.width; x++) { + + var B = this.buffer.readUInt16LE(this.pos); + this.pos+=2; + + var blue = (B&this.maskBlue)<>ns[1]; + var red = (B&this.maskRed)>>ns[2]; + + var location = line * this.width * 4 + x * 4; + + this.data[location] = 0; + this.data[location + 1] = blue; + this.data[location + 2] = green; + this.data[location + 3] = red; + } + //skip extra bytes + this.pos += dif_w; + } +}; + +BmpDecoder.prototype.bit24 = function() { + for (var y = this.height - 1; y >= 0; y--) { + var line = this.bottom_up ? y : this.height - 1 - y + for (var x = 0; x < this.width; x++) { + //Little Endian rgb + var blue = this.buffer.readUInt8(this.pos++); + var green = this.buffer.readUInt8(this.pos++); + var red = this.buffer.readUInt8(this.pos++); + var location = line * this.width * 4 + x * 4; + this.data[location] = 0; + this.data[location + 1] = blue; + this.data[location + 2] = green; + this.data[location + 3] = red; + } + //skip extra bytes + this.pos += (this.width % 4); + } + +}; + +/** + * add 32bit decode func + * @author soubok + */ +BmpDecoder.prototype.bit32 = function() { + //BI_BITFIELDS + if(this.compress == 3){ + this.maskRed = this.buffer.readUInt32LE(this.pos); + this.pos+=4; + this.maskGreen = this.buffer.readUInt32LE(this.pos); + this.pos+=4; + this.maskBlue = this.buffer.readUInt32LE(this.pos); + this.pos+=4; + this.mask0 = this.buffer.readUInt32LE(this.pos); + this.pos+=4; + for (var y = this.height - 1; y >= 0; y--) { + var line = this.bottom_up ? y : this.height - 1 - y; + for (var x = 0; x < this.width; x++) { + //Little Endian rgba + var alpha = this.buffer.readUInt8(this.pos++); + var blue = this.buffer.readUInt8(this.pos++); + var green = this.buffer.readUInt8(this.pos++); + var red = this.buffer.readUInt8(this.pos++); + var location = line * this.width * 4 + x * 4; + this.data[location] = alpha; + this.data[location + 1] = blue; + this.data[location + 2] = green; + this.data[location + 3] = red; + } + } + + }else{ + for (var y = this.height - 1; y >= 0; y--) { + var line = this.bottom_up ? y : this.height - 1 - y; + for (var x = 0; x < this.width; x++) { + //Little Endian argb + var blue = this.buffer.readUInt8(this.pos++); + var green = this.buffer.readUInt8(this.pos++); + var red = this.buffer.readUInt8(this.pos++); + var alpha = this.buffer.readUInt8(this.pos++); + var location = line * this.width * 4 + x * 4; + this.data[location] = alpha; + this.data[location + 1] = blue; + this.data[location + 2] = green; + this.data[location + 3] = red; + } + } + + } + + + + +}; + +BmpDecoder.prototype.getData = function() { + return this.data; +}; + +module.exports = function(bmpData) { + var decoder = new BmpDecoder(bmpData); + return decoder; +}; + + +/***/ }), + +/***/ 4551: +/***/ ((module) => { + +/** + * @author shaozilee + * + * BMP format encoder,encode 24bit BMP + * Not support quality compression + * + */ + +function BmpEncoder(imgData){ + this.buffer = imgData.data; + this.width = imgData.width; + this.height = imgData.height; + this.extraBytes = this.width%4; + this.rgbSize = this.height*(3*this.width+this.extraBytes); + this.headerInfoSize = 40; + + this.data = []; + /******************header***********************/ + this.flag = "BM"; + this.reserved = 0; + this.offset = 54; + this.fileSize = this.rgbSize+this.offset; + this.planes = 1; + this.bitPP = 24; + this.compress = 0; + this.hr = 0; + this.vr = 0; + this.colors = 0; + this.importantColors = 0; +} + +BmpEncoder.prototype.encode = function() { + var tempBuffer = new Buffer(this.offset+this.rgbSize); + this.pos = 0; + tempBuffer.write(this.flag,this.pos,2);this.pos+=2; + tempBuffer.writeUInt32LE(this.fileSize,this.pos);this.pos+=4; + tempBuffer.writeUInt32LE(this.reserved,this.pos);this.pos+=4; + tempBuffer.writeUInt32LE(this.offset,this.pos);this.pos+=4; + + tempBuffer.writeUInt32LE(this.headerInfoSize,this.pos);this.pos+=4; + tempBuffer.writeUInt32LE(this.width,this.pos);this.pos+=4; + tempBuffer.writeInt32LE(-this.height,this.pos);this.pos+=4; + tempBuffer.writeUInt16LE(this.planes,this.pos);this.pos+=2; + tempBuffer.writeUInt16LE(this.bitPP,this.pos);this.pos+=2; + tempBuffer.writeUInt32LE(this.compress,this.pos);this.pos+=4; + tempBuffer.writeUInt32LE(this.rgbSize,this.pos);this.pos+=4; + tempBuffer.writeUInt32LE(this.hr,this.pos);this.pos+=4; + tempBuffer.writeUInt32LE(this.vr,this.pos);this.pos+=4; + tempBuffer.writeUInt32LE(this.colors,this.pos);this.pos+=4; + tempBuffer.writeUInt32LE(this.importantColors,this.pos);this.pos+=4; + + var i=0; + var rowBytes = 3*this.width+this.extraBytes; + + for (var y = 0; y 0){ + var fillOffset = this.pos+y*rowBytes+this.width*3; + tempBuffer.fill(0,fillOffset,fillOffset+this.extraBytes); + } + } + + return tempBuffer; +}; + +module.exports = function(imgData, quality) { + if (typeof quality === 'undefined') quality = 100; + var encoder = new BmpEncoder(imgData); + var data = encoder.encode(); + return { + data: data, + width: imgData.width, + height: imgData.height + }; +}; + + +/***/ }), + +/***/ 4664: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var Buffer = (__nccwpck_require__(4300).Buffer); // for use with browserify + +module.exports = function (a, b) { + if (!Buffer.isBuffer(a)) return undefined; + if (!Buffer.isBuffer(b)) return undefined; + if (typeof a.equals === 'function') return a.equals(b); + if (a.length !== b.length) return false; + + for (var i = 0; i < a.length; i++) { + if (a[i] !== b[i]) return false; + } + + return true; +}; + + +/***/ }), + +/***/ 5443: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var util = __nccwpck_require__(3837); +var Stream = (__nccwpck_require__(2781).Stream); +var DelayedStream = __nccwpck_require__(8611); + +module.exports = CombinedStream; +function CombinedStream() { + this.writable = false; + this.readable = true; + this.dataSize = 0; + this.maxDataSize = 2 * 1024 * 1024; + this.pauseStreams = true; + + this._released = false; + this._streams = []; + this._currentStream = null; + this._insideLoop = false; + this._pendingNext = false; +} +util.inherits(CombinedStream, Stream); + +CombinedStream.create = function(options) { + var combinedStream = new this(); + + options = options || {}; + for (var option in options) { + combinedStream[option] = options[option]; + } + + 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); + + 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; + } + + this._handleErrors(stream); + + if (this.pauseStreams) { + stream.pause(); + } + } + + this._streams.push(stream); + return this; +}; + +CombinedStream.prototype.pipe = function(dest, options) { + Stream.prototype.pipe.call(this, dest, options); + this.resume(); + return dest; +}; + +CombinedStream.prototype._getNext = function() { + this._currentStream = null; + + if (this._insideLoop) { + this._pendingNext = true; + return; // defer call + } + + this._insideLoop = true; + try { + do { + this._pendingNext = false; + this._realGetNext(); + } while (this._pendingNext); + } finally { + this._insideLoop = false; + } +}; + +CombinedStream.prototype._realGetNext = function() { + var stream = this._streams.shift(); + + + if (typeof stream == 'undefined') { + this.end(); + return; + } + + if (typeof stream !== 'function') { + this._pipeNext(stream); + return; + } + + var getStream = stream; + getStream(function(stream) { + var isStreamLike = CombinedStream.isStreamLike(stream); + if (isStreamLike) { + stream.on('data', this._checkDataSize.bind(this)); + this._handleErrors(stream); + } + + this._pipeNext(stream); + }.bind(this)); +}; + +CombinedStream.prototype._pipeNext = function(stream) { + this._currentStream = stream; + + var isStreamLike = CombinedStream.isStreamLike(stream); + if (isStreamLike) { + stream.on('end', this._getNext.bind(this)); + stream.pipe(this, {end: false}); + return; + } + + var value = stream; + this.write(value); + this._getNext(); +}; + +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; + } + + if(this.pauseStreams && this._currentStream && typeof(this._currentStream.pause) == 'function') this._currentStream.pause(); + this.emit('pause'); +}; + +CombinedStream.prototype.resume = function() { + if (!this._released) { + this._released = true; + this.writable = true; + this._getNext(); + } + + 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; +}; + +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; + + var self = this; + this._streams.forEach(function(stream) { + if (!stream.dataSize) { + return; + } + + self.dataSize += stream.dataSize; + }); + + if (this._currentStream && this._currentStream.dataSize) { + this.dataSize += this._currentStream.dataSize; + } +}; + +CombinedStream.prototype._emitError = function(err) { + this._reset(); + this.emit('error', err); +}; + + +/***/ }), + +/***/ 8222: +/***/ ((module, exports, __nccwpck_require__) => { + +/* eslint-env browser */ + +/** + * This is the web browser implementation of `debug()`. + */ + +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = localstorage(); +exports.destroy = (() => { + let warned = false; + + 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' +]; + +/** + * 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 + */ + +// 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+)/)); +} + +/** + * Colorize log arguments if enabled. + * + * @api public + */ + +function formatArgs(args) { + args[0] = (this.useColors ? '%c' : '') + + this.namespace + + (this.useColors ? ' %c' : ' ') + + args[0] + + (this.useColors ? '%c ' : ' ') + + '+' + module.exports.humanize(this.diff); + + if (!this.useColors) { + return; + } + + const c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit'); + + // 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; + } + }); + + args.splice(lastC, 0, c); +} + +/** + * 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 || (() => {}); + +/** + * 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? + } +} + +/** + * 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? + } + + // 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; + } + + return r; +} + +/** + * 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 + */ + +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? + } +} + +module.exports = __nccwpck_require__(6243)(exports); + +const {formatters} = module.exports; + +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +formatters.j = function (v) { + try { + return JSON.stringify(v); + } catch (error) { + return '[UnexpectedJSONParseError]: ' + error.message; + } +}; + + +/***/ }), + +/***/ 6243: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + */ + +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; + + Object.keys(env).forEach(key => { + createDebug[key] = env[key]; + }); + + /** + * The currently active debug mode names, and names to skip. + */ + + createDebug.names = []; + createDebug.skips = []; + + /** + * 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 = {}; + + /** + * Selects a color for a debug namespace + * @param {String} namespace The namespace string for the 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 + } + + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; + + /** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + + function debug(...args) { + // Disabled? + if (!debug.enabled) { + return; + } + + const self = debug; + + // Set `diff` timestamp + const curr = Number(new Date()); + const ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + args[0] = createDebug.coerce(args[0]); + + if (typeof args[0] !== 'string') { + // Anything else let's inspect with %O + args.unshift('%O'); + } + + // 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); + + // Now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + // Apply env-specific formatting (colors, etc.) + createDebug.formatArgs.call(self, args); + + const logFn = self.log || createDebug.log; + logFn.apply(self, args); + } + + 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. + + Object.defineProperty(debug, 'enabled', { + enumerable: true, + configurable: false, + get: () => enableOverride === null ? createDebug.enabled(namespace) : enableOverride, + set: v => { + enableOverride = v; + } + }); + + // Env-specific initialization logic for debug instances + if (typeof createDebug.init === 'function') { + createDebug.init(debug); + } + + return debug; + } + + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } + + /** + * 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.names = []; + createDebug.skips = []; + + let i; + const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + const len = split.length; + + for (i = 0; i < len; i++) { + if (!split[i]) { + // ignore empty strings + continue; + } + + namespaces = split[i].replace(/\*/g, '.*?'); + + if (namespaces[0] === '-') { + createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + createDebug.names.push(new RegExp('^' + namespaces + '$')); + } + } + } + + /** + * 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; + } + + /** + * 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; + } + + let i; + let len; + + 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; + } + + /** + * 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(/\.\*\?$/, '*'); + } + + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } + + /** + * 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`.'); + } + + createDebug.enable(createDebug.load()); + + return createDebug; +} + +module.exports = setup; + + +/***/ }), + +/***/ 8237: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/** + * Detect Electron renderer / nwjs process, which is node, but we should + * treat as a browser. + */ + +if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { + module.exports = __nccwpck_require__(8222); +} else { + module.exports = __nccwpck_require__(5332); +} + + +/***/ }), + +/***/ 5332: +/***/ ((module, exports, __nccwpck_require__) => { + +/** + * Module dependencies. + */ + +const tty = __nccwpck_require__(6224); +const util = __nccwpck_require__(3837); + +/** + * This is the Node.js implementation of `debug()`. + */ + +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`.' +); + +/** + * Colors. + */ + +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. +} + +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ + +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(); + }); + + // 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); + } + + obj[prop] = val; + return obj; +}, {}); + +/** + * 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); +} + +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ + +function formatArgs(args) { + const {namespace: name, useColors} = this; + + if (useColors) { + const c = this.color; + const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); + const prefix = ` ${colorCode};1m${name} \u001B[0m`; + + 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]; + } +} + +function getDate() { + if (exports.inspectOpts.hideDate) { + return ''; + } + return new Date().toISOString() + ' '; +} + +/** + * Invokes `util.format()` with the specified arguments and writes to stderr. + */ + +function log(...args) { + return process.stderr.write(util.format(...args) + '\n'); +} + +/** + * 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; + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + return process.env.DEBUG; +} + +/** + * 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]]; + } +} + +module.exports = __nccwpck_require__(6243)(exports); + +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(' '); +}; + +/** + * Map %O to `util.inspect()`, allowing multiple lines if needed. + */ + +formatters.O = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; + + +/***/ }), + +/***/ 8611: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var Stream = (__nccwpck_require__(2781).Stream); +var util = __nccwpck_require__(3837); + +module.exports = DelayedStream; +function DelayedStream() { + this.source = null; + this.dataSize = 0; + this.maxDataSize = 1024 * 1024; + this.pauseStream = true; + + this._maxDataSizeExceeded = false; + this._released = false; + this._bufferedEvents = []; +} +util.inherits(DelayedStream, Stream); + +DelayedStream.create = function(source, options) { + var delayedStream = new this(); + + options = options || {}; + for (var option in options) { + delayedStream[option] = options[option]; + } + + delayedStream.source = source; + + var realEmit = source.emit; + source.emit = function() { + delayedStream._handleEmit(arguments); + return realEmit.apply(source, arguments); + }; + + source.on('error', function() {}); + if (delayedStream.pauseStream) { + source.pause(); + } + + return delayedStream; +}; + +Object.defineProperty(DelayedStream.prototype, 'readable', { + configurable: true, + enumerable: true, + get: function() { + return this.source.readable; + } +}); + +DelayedStream.prototype.setEncoding = function() { + return this.source.setEncoding.apply(this.source, arguments); +}; + +DelayedStream.prototype.resume = function() { + if (!this._released) { + this.release(); + } + + this.source.resume(); +}; + +DelayedStream.prototype.pause = function() { + this.source.pause(); +}; + +DelayedStream.prototype.release = function() { + this._released = true; + + this._bufferedEvents.forEach(function(args) { + this.emit.apply(this, args); + }.bind(this)); + this._bufferedEvents = []; +}; + +DelayedStream.prototype.pipe = function() { + var r = Stream.prototype.pipe.apply(this, arguments); + this.resume(); + return r; +}; + +DelayedStream.prototype._handleEmit = function(args) { + if (this._released) { + this.emit.apply(this, args); + return; + } + + if (args[0] === 'data') { + this.dataSize += args[1].length; + this._checkIfMaxDataSizeExceeded(); + } + + this._bufferedEvents.push(args); +}; + +DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() { + if (this._maxDataSizeExceeded) { + return; + } + + if (this.dataSize <= this.maxDataSize) { + return; + } + + this._maxDataSizeExceeded = true; + var message = + 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.' + this.emit('error', new Error(message)); +}; + + +/***/ }), + +/***/ 6621: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var Parser = __nccwpck_require__(4898); + +function getGlobal() { + return (1,eval)('this'); +} + +module.exports = { + create: function(buffer, global) { + global = global || getGlobal(); + if(buffer instanceof global.ArrayBuffer) { + var DOMBufferStream = __nccwpck_require__(4674); + return new Parser(new DOMBufferStream(buffer, 0, buffer.byteLength, true, global)); + } else { + var NodeBufferStream = __nccwpck_require__(7525); + return new Parser(new NodeBufferStream(buffer, 0, buffer.length, true)); + } + } +}; + + +/***/ }), + +/***/ 7525: +/***/ ((module) => { + +function BufferStream(buffer, offset, length, bigEndian) { + this.buffer = buffer; + this.offset = offset || 0; + length = typeof length === 'number' ? length : buffer.length; + this.endPosition = this.offset + length; + this.setBigEndian(bigEndian); +} + +BufferStream.prototype = { + setBigEndian: function(bigEndian) { + this.bigEndian = !!bigEndian; + }, + nextUInt8: function() { + var value = this.buffer.readUInt8(this.offset); + this.offset += 1; + return value; + }, + nextInt8: function() { + var value = this.buffer.readInt8(this.offset); + this.offset += 1; + return value; + }, + nextUInt16: function() { + var value = this.bigEndian ? this.buffer.readUInt16BE(this.offset) : this.buffer.readUInt16LE(this.offset); + this.offset += 2; + return value; + }, + nextUInt32: function() { + var value = this.bigEndian ? this.buffer.readUInt32BE(this.offset) : this.buffer.readUInt32LE(this.offset); + this.offset += 4; + return value; + }, + nextInt16: function() { + var value = this.bigEndian ? this.buffer.readInt16BE(this.offset) : this.buffer.readInt16LE(this.offset); + this.offset += 2; + return value; + }, + nextInt32: function() { + var value = this.bigEndian ? this.buffer.readInt32BE(this.offset) : this.buffer.readInt32LE(this.offset); + this.offset += 4; + return value; + }, + nextFloat: function() { + var value = this.bigEndian ? this.buffer.readFloatBE(this.offset) : this.buffer.readFloatLE(this.offset); + this.offset += 4; + return value; + }, + nextDouble: function() { + var value = this.bigEndian ? this.buffer.readDoubleBE(this.offset) : this.buffer.readDoubleLE(this.offset); + this.offset += 8; + return value; + }, + nextBuffer: function(length) { + var value = this.buffer.slice(this.offset, this.offset + length); + this.offset += length; + return value; + }, + remainingLength: function() { + return this.endPosition - this.offset; + }, + nextString: function(length) { + var value = this.buffer.toString('utf8', this.offset, this.offset + length); + this.offset += length; + return value; + }, + mark: function() { + var self = this; + return { + openWithOffset: function(offset) { + offset = (offset || 0) + this.offset; + return new BufferStream(self.buffer, offset, self.endPosition - offset, self.bigEndian); + }, + offset: this.offset + }; + }, + offsetFrom: function(marker) { + return this.offset - marker.offset; + }, + skip: function(amount) { + this.offset += amount; + }, + branch: function(offset, length) { + length = typeof length === 'number' ? length : this.endPosition - (this.offset + offset); + return new BufferStream(this.buffer, this.offset + offset, length, this.bigEndian); + } +}; + +module.exports = BufferStream; + + +/***/ }), + +/***/ 610: +/***/ ((module) => { + +function parseNumber(s) { + return parseInt(s, 10); +} + +//in seconds +var hours = 3600; +var minutes = 60; + +//take date (year, month, day) and time (hour, minutes, seconds) digits in UTC +//and return a timestamp in seconds +function parseDateTimeParts(dateParts, timeParts) { + dateParts = dateParts.map(parseNumber); + timeParts = timeParts.map(parseNumber); + var year = dateParts[0]; + var month = dateParts[1] - 1; + var day = dateParts[2]; + var hours = timeParts[0]; + var minutes = timeParts[1]; + var seconds = timeParts[2]; + var date = Date.UTC(year, month, day, hours, minutes, seconds, 0); + var timestamp = date / 1000; + return timestamp; +} + +//parse date with "2004-09-04T23:39:06-08:00" format, +//one of the formats supported by ISO 8601, and +//convert to utc timestamp in seconds +function parseDateWithTimezoneFormat(dateTimeStr) { + + var dateParts = dateTimeStr.substr(0, 10).split('-'); + var timeParts = dateTimeStr.substr(11, 8).split(':'); + var timezoneStr = dateTimeStr.substr(19, 6); + var timezoneParts = timezoneStr.split(':').map(parseNumber); + var timezoneOffset = (timezoneParts[0] * hours) + + (timezoneParts[1] * minutes); + + var timestamp = parseDateTimeParts(dateParts, timeParts); + //minus because the timezoneOffset describes + //how much the described time is ahead of UTC + timestamp -= timezoneOffset; + + if(typeof timestamp === 'number' && !isNaN(timestamp)) { + return timestamp; + } +} + +//parse date with "YYYY:MM:DD hh:mm:ss" format, convert to utc timestamp in seconds +function parseDateWithSpecFormat(dateTimeStr) { + var parts = dateTimeStr.split(' '), + dateParts = parts[0].split(':'), + timeParts = parts[1].split(':'); + + var timestamp = parseDateTimeParts(dateParts, timeParts); + + if(typeof timestamp === 'number' && !isNaN(timestamp)) { + return timestamp; + } +} + +function parseExifDate(dateTimeStr) { + //some easy checks to determine two common date formats + + //is the date in the standard "YYYY:MM:DD hh:mm:ss" format? + var isSpecFormat = dateTimeStr.length === 19 && + dateTimeStr.charAt(4) === ':'; + //is the date in the non-standard format, + //"2004-09-04T23:39:06-08:00" to include a timezone? + var isTimezoneFormat = dateTimeStr.length === 25 && + dateTimeStr.charAt(10) === 'T'; + var timestamp; + + if(isTimezoneFormat) { + return parseDateWithTimezoneFormat(dateTimeStr); + } + else if(isSpecFormat) { + return parseDateWithSpecFormat(dateTimeStr); + } +} + +module.exports = { + parseDateWithSpecFormat: parseDateWithSpecFormat, + parseDateWithTimezoneFormat: parseDateWithTimezoneFormat, + parseExifDate: parseExifDate +}; + + +/***/ }), + +/***/ 4674: +/***/ ((module) => { + +/*jslint browser: true, devel: true, bitwise: false, debug: true, eqeq: false, es5: true, evil: false, forin: false, newcap: false, nomen: true, plusplus: true, regexp: false, unparam: false, sloppy: true, stupid: false, sub: false, todo: true, vars: true, white: true */ + +function DOMBufferStream(arrayBuffer, offset, length, bigEndian, global, parentOffset) { + this.global = global; + offset = offset || 0; + length = length || (arrayBuffer.byteLength - offset); + this.arrayBuffer = arrayBuffer.slice(offset, offset + length); + this.view = new global.DataView(this.arrayBuffer, 0, this.arrayBuffer.byteLength); + this.setBigEndian(bigEndian); + this.offset = 0; + this.parentOffset = (parentOffset || 0) + offset; +} + +DOMBufferStream.prototype = { + setBigEndian: function(bigEndian) { + this.littleEndian = !bigEndian; + }, + nextUInt8: function() { + var value = this.view.getUint8(this.offset); + this.offset += 1; + return value; + }, + nextInt8: function() { + var value = this.view.getInt8(this.offset); + this.offset += 1; + return value; + }, + nextUInt16: function() { + var value = this.view.getUint16(this.offset, this.littleEndian); + this.offset += 2; + return value; + }, + nextUInt32: function() { + var value = this.view.getUint32(this.offset, this.littleEndian); + this.offset += 4; + return value; + }, + nextInt16: function() { + var value = this.view.getInt16(this.offset, this.littleEndian); + this.offset += 2; + return value; + }, + nextInt32: function() { + var value = this.view.getInt32(this.offset, this.littleEndian); + this.offset += 4; + return value; + }, + nextFloat: function() { + var value = this.view.getFloat32(this.offset, this.littleEndian); + this.offset += 4; + return value; + }, + nextDouble: function() { + var value = this.view.getFloat64(this.offset, this.littleEndian); + this.offset += 8; + return value; + }, + nextBuffer: function(length) { + //this won't work in IE10 + var value = this.arrayBuffer.slice(this.offset, this.offset + length); + this.offset += length; + return value; + }, + remainingLength: function() { + return this.arrayBuffer.byteLength - this.offset; + }, + nextString: function(length) { + var value = this.arrayBuffer.slice(this.offset, this.offset + length); + value = String.fromCharCode.apply(null, new this.global.Uint8Array(value)); + this.offset += length; + return value; + }, + mark: function() { + var self = this; + return { + openWithOffset: function(offset) { + offset = (offset || 0) + this.offset; + return new DOMBufferStream(self.arrayBuffer, offset, self.arrayBuffer.byteLength - offset, !self.littleEndian, self.global, self.parentOffset); + }, + offset: this.offset, + getParentOffset: function() { + return self.parentOffset; + } + }; + }, + offsetFrom: function(marker) { + return this.parentOffset + this.offset - (marker.offset + marker.getParentOffset()); + }, + skip: function(amount) { + this.offset += amount; + }, + branch: function(offset, length) { + length = typeof length === 'number' ? length : this.arrayBuffer.byteLength - (this.offset + offset); + return new DOMBufferStream(this.arrayBuffer, this.offset + offset, length, !this.littleEndian, this.global, this.parentOffset); + } +}; + +module.exports = DOMBufferStream; + + +/***/ }), + +/***/ 1494: +/***/ ((module) => { + +module.exports = { + exif : { + 0x0001 : "InteropIndex", + 0x0002 : "InteropVersion", + 0x000B : "ProcessingSoftware", + 0x00FE : "SubfileType", + 0x00FF : "OldSubfileType", + 0x0100 : "ImageWidth", + 0x0101 : "ImageHeight", + 0x0102 : "BitsPerSample", + 0x0103 : "Compression", + 0x0106 : "PhotometricInterpretation", + 0x0107 : "Thresholding", + 0x0108 : "CellWidth", + 0x0109 : "CellLength", + 0x010A : "FillOrder", + 0x010D : "DocumentName", + 0x010E : "ImageDescription", + 0x010F : "Make", + 0x0110 : "Model", + 0x0111 : "StripOffsets", + 0x0112 : "Orientation", + 0x0115 : "SamplesPerPixel", + 0x0116 : "RowsPerStrip", + 0x0117 : "StripByteCounts", + 0x0118 : "MinSampleValue", + 0x0119 : "MaxSampleValue", + 0x011A : "XResolution", + 0x011B : "YResolution", + 0x011C : "PlanarConfiguration", + 0x011D : "PageName", + 0x011E : "XPosition", + 0x011F : "YPosition", + 0x0120 : "FreeOffsets", + 0x0121 : "FreeByteCounts", + 0x0122 : "GrayResponseUnit", + 0x0123 : "GrayResponseCurve", + 0x0124 : "T4Options", + 0x0125 : "T6Options", + 0x0128 : "ResolutionUnit", + 0x0129 : "PageNumber", + 0x012C : "ColorResponseUnit", + 0x012D : "TransferFunction", + 0x0131 : "Software", + 0x0132 : "ModifyDate", + 0x013B : "Artist", + 0x013C : "HostComputer", + 0x013D : "Predictor", + 0x013E : "WhitePoint", + 0x013F : "PrimaryChromaticities", + 0x0140 : "ColorMap", + 0x0141 : "HalftoneHints", + 0x0142 : "TileWidth", + 0x0143 : "TileLength", + 0x0144 : "TileOffsets", + 0x0145 : "TileByteCounts", + 0x0146 : "BadFaxLines", + 0x0147 : "CleanFaxData", + 0x0148 : "ConsecutiveBadFaxLines", + 0x014A : "SubIFD", + 0x014C : "InkSet", + 0x014D : "InkNames", + 0x014E : "NumberofInks", + 0x0150 : "DotRange", + 0x0151 : "TargetPrinter", + 0x0152 : "ExtraSamples", + 0x0153 : "SampleFormat", + 0x0154 : "SMinSampleValue", + 0x0155 : "SMaxSampleValue", + 0x0156 : "TransferRange", + 0x0157 : "ClipPath", + 0x0158 : "XClipPathUnits", + 0x0159 : "YClipPathUnits", + 0x015A : "Indexed", + 0x015B : "JPEGTables", + 0x015F : "OPIProxy", + 0x0190 : "GlobalParametersIFD", + 0x0191 : "ProfileType", + 0x0192 : "FaxProfile", + 0x0193 : "CodingMethods", + 0x0194 : "VersionYear", + 0x0195 : "ModeNumber", + 0x01B1 : "Decode", + 0x01B2 : "DefaultImageColor", + 0x01B3 : "T82Options", + 0x01B5 : "JPEGTables", + 0x0200 : "JPEGProc", + 0x0201 : "ThumbnailOffset", + 0x0202 : "ThumbnailLength", + 0x0203 : "JPEGRestartInterval", + 0x0205 : "JPEGLosslessPredictors", + 0x0206 : "JPEGPointTransforms", + 0x0207 : "JPEGQTables", + 0x0208 : "JPEGDCTables", + 0x0209 : "JPEGACTables", + 0x0211 : "YCbCrCoefficients", + 0x0212 : "YCbCrSubSampling", + 0x0213 : "YCbCrPositioning", + 0x0214 : "ReferenceBlackWhite", + 0x022F : "StripRowCounts", + 0x02BC : "ApplicationNotes", + 0x03E7 : "USPTOMiscellaneous", + 0x1000 : "RelatedImageFileFormat", + 0x1001 : "RelatedImageWidth", + 0x1002 : "RelatedImageHeight", + 0x4746 : "Rating", + 0x4747 : "XP_DIP_XML", + 0x4748 : "StitchInfo", + 0x4749 : "RatingPercent", + 0x800D : "ImageID", + 0x80A3 : "WangTag1", + 0x80A4 : "WangAnnotation", + 0x80A5 : "WangTag3", + 0x80A6 : "WangTag4", + 0x80E3 : "Matteing", + 0x80E4 : "DataType", + 0x80E5 : "ImageDepth", + 0x80E6 : "TileDepth", + 0x827D : "Model2", + 0x828D : "CFARepeatPatternDim", + 0x828E : "CFAPattern2", + 0x828F : "BatteryLevel", + 0x8290 : "KodakIFD", + 0x8298 : "Copyright", + 0x829A : "ExposureTime", + 0x829D : "FNumber", + 0x82A5 : "MDFileTag", + 0x82A6 : "MDScalePixel", + 0x82A7 : "MDColorTable", + 0x82A8 : "MDLabName", + 0x82A9 : "MDSampleInfo", + 0x82AA : "MDPrepDate", + 0x82AB : "MDPrepTime", + 0x82AC : "MDFileUnits", + 0x830E : "PixelScale", + 0x8335 : "AdventScale", + 0x8336 : "AdventRevision", + 0x835C : "UIC1Tag", + 0x835D : "UIC2Tag", + 0x835E : "UIC3Tag", + 0x835F : "UIC4Tag", + 0x83BB : "IPTC-NAA", + 0x847E : "IntergraphPacketData", + 0x847F : "IntergraphFlagRegisters", + 0x8480 : "IntergraphMatrix", + 0x8481 : "INGRReserved", + 0x8482 : "ModelTiePoint", + 0x84E0 : "Site", + 0x84E1 : "ColorSequence", + 0x84E2 : "IT8Header", + 0x84E3 : "RasterPadding", + 0x84E4 : "BitsPerRunLength", + 0x84E5 : "BitsPerExtendedRunLength", + 0x84E6 : "ColorTable", + 0x84E7 : "ImageColorIndicator", + 0x84E8 : "BackgroundColorIndicator", + 0x84E9 : "ImageColorValue", + 0x84EA : "BackgroundColorValue", + 0x84EB : "PixelIntensityRange", + 0x84EC : "TransparencyIndicator", + 0x84ED : "ColorCharacterization", + 0x84EE : "HCUsage", + 0x84EF : "TrapIndicator", + 0x84F0 : "CMYKEquivalent", + 0x8546 : "SEMInfo", + 0x8568 : "AFCP_IPTC", + 0x85B8 : "PixelMagicJBIGOptions", + 0x85D8 : "ModelTransform", + 0x8602 : "WB_GRGBLevels", + 0x8606 : "LeafData", + 0x8649 : "PhotoshopSettings", + 0x8769 : "ExifOffset", + 0x8773 : "ICC_Profile", + 0x877F : "TIFF_FXExtensions", + 0x8780 : "MultiProfiles", + 0x8781 : "SharedData", + 0x8782 : "T88Options", + 0x87AC : "ImageLayer", + 0x87AF : "GeoTiffDirectory", + 0x87B0 : "GeoTiffDoubleParams", + 0x87B1 : "GeoTiffAsciiParams", + 0x8822 : "ExposureProgram", + 0x8824 : "SpectralSensitivity", + 0x8825 : "GPSInfo", + 0x8827 : "ISO", + 0x8828 : "Opto-ElectricConvFactor", + 0x8829 : "Interlace", + 0x882A : "TimeZoneOffset", + 0x882B : "SelfTimerMode", + 0x8830 : "SensitivityType", + 0x8831 : "StandardOutputSensitivity", + 0x8832 : "RecommendedExposureIndex", + 0x8833 : "ISOSpeed", + 0x8834 : "ISOSpeedLatitudeyyy", + 0x8835 : "ISOSpeedLatitudezzz", + 0x885C : "FaxRecvParams", + 0x885D : "FaxSubAddress", + 0x885E : "FaxRecvTime", + 0x888A : "LeafSubIFD", + 0x9000 : "ExifVersion", + 0x9003 : "DateTimeOriginal", + 0x9004 : "CreateDate", + 0x9101 : "ComponentsConfiguration", + 0x9102 : "CompressedBitsPerPixel", + 0x9201 : "ShutterSpeedValue", + 0x9202 : "ApertureValue", + 0x9203 : "BrightnessValue", + 0x9204 : "ExposureCompensation", + 0x9205 : "MaxApertureValue", + 0x9206 : "SubjectDistance", + 0x9207 : "MeteringMode", + 0x9208 : "LightSource", + 0x9209 : "Flash", + 0x920A : "FocalLength", + 0x920B : "FlashEnergy", + 0x920C : "SpatialFrequencyResponse", + 0x920D : "Noise", + 0x920E : "FocalPlaneXResolution", + 0x920F : "FocalPlaneYResolution", + 0x9210 : "FocalPlaneResolutionUnit", + 0x9211 : "ImageNumber", + 0x9212 : "SecurityClassification", + 0x9213 : "ImageHistory", + 0x9214 : "SubjectArea", + 0x9215 : "ExposureIndex", + 0x9216 : "TIFF-EPStandardID", + 0x9217 : "SensingMethod", + 0x923A : "CIP3DataFile", + 0x923B : "CIP3Sheet", + 0x923C : "CIP3Side", + 0x923F : "StoNits", + 0x927C : "MakerNote", + 0x9286 : "UserComment", + 0x9290 : "SubSecTime", + 0x9291 : "SubSecTimeOriginal", + 0x9292 : "SubSecTimeDigitized", + 0x932F : "MSDocumentText", + 0x9330 : "MSPropertySetStorage", + 0x9331 : "MSDocumentTextPosition", + 0x935C : "ImageSourceData", + 0x9C9B : "XPTitle", + 0x9C9C : "XPComment", + 0x9C9D : "XPAuthor", + 0x9C9E : "XPKeywords", + 0x9C9F : "XPSubject", + 0xA000 : "FlashpixVersion", + 0xA001 : "ColorSpace", + 0xA002 : "ExifImageWidth", + 0xA003 : "ExifImageHeight", + 0xA004 : "RelatedSoundFile", + 0xA005 : "InteropOffset", + 0xA20B : "FlashEnergy", + 0xA20C : "SpatialFrequencyResponse", + 0xA20D : "Noise", + 0xA20E : "FocalPlaneXResolution", + 0xA20F : "FocalPlaneYResolution", + 0xA210 : "FocalPlaneResolutionUnit", + 0xA211 : "ImageNumber", + 0xA212 : "SecurityClassification", + 0xA213 : "ImageHistory", + 0xA214 : "SubjectLocation", + 0xA215 : "ExposureIndex", + 0xA216 : "TIFF-EPStandardID", + 0xA217 : "SensingMethod", + 0xA300 : "FileSource", + 0xA301 : "SceneType", + 0xA302 : "CFAPattern", + 0xA401 : "CustomRendered", + 0xA402 : "ExposureMode", + 0xA403 : "WhiteBalance", + 0xA404 : "DigitalZoomRatio", + 0xA405 : "FocalLengthIn35mmFormat", + 0xA406 : "SceneCaptureType", + 0xA407 : "GainControl", + 0xA408 : "Contrast", + 0xA409 : "Saturation", + 0xA40A : "Sharpness", + 0xA40B : "DeviceSettingDescription", + 0xA40C : "SubjectDistanceRange", + 0xA420 : "ImageUniqueID", + 0xA430 : "OwnerName", + 0xA431 : "SerialNumber", + 0xA432 : "LensInfo", + 0xA433 : "LensMake", + 0xA434 : "LensModel", + 0xA435 : "LensSerialNumber", + 0xA480 : "GDALMetadata", + 0xA481 : "GDALNoData", + 0xA500 : "Gamma", + 0xAFC0 : "ExpandSoftware", + 0xAFC1 : "ExpandLens", + 0xAFC2 : "ExpandFilm", + 0xAFC3 : "ExpandFilterLens", + 0xAFC4 : "ExpandScanner", + 0xAFC5 : "ExpandFlashLamp", + 0xBC01 : "PixelFormat", + 0xBC02 : "Transformation", + 0xBC03 : "Uncompressed", + 0xBC04 : "ImageType", + 0xBC80 : "ImageWidth", + 0xBC81 : "ImageHeight", + 0xBC82 : "WidthResolution", + 0xBC83 : "HeightResolution", + 0xBCC0 : "ImageOffset", + 0xBCC1 : "ImageByteCount", + 0xBCC2 : "AlphaOffset", + 0xBCC3 : "AlphaByteCount", + 0xBCC4 : "ImageDataDiscard", + 0xBCC5 : "AlphaDataDiscard", + 0xC427 : "OceScanjobDesc", + 0xC428 : "OceApplicationSelector", + 0xC429 : "OceIDNumber", + 0xC42A : "OceImageLogic", + 0xC44F : "Annotations", + 0xC4A5 : "PrintIM", + 0xC580 : "USPTOOriginalContentType", + 0xC612 : "DNGVersion", + 0xC613 : "DNGBackwardVersion", + 0xC614 : "UniqueCameraModel", + 0xC615 : "LocalizedCameraModel", + 0xC616 : "CFAPlaneColor", + 0xC617 : "CFALayout", + 0xC618 : "LinearizationTable", + 0xC619 : "BlackLevelRepeatDim", + 0xC61A : "BlackLevel", + 0xC61B : "BlackLevelDeltaH", + 0xC61C : "BlackLevelDeltaV", + 0xC61D : "WhiteLevel", + 0xC61E : "DefaultScale", + 0xC61F : "DefaultCropOrigin", + 0xC620 : "DefaultCropSize", + 0xC621 : "ColorMatrix1", + 0xC622 : "ColorMatrix2", + 0xC623 : "CameraCalibration1", + 0xC624 : "CameraCalibration2", + 0xC625 : "ReductionMatrix1", + 0xC626 : "ReductionMatrix2", + 0xC627 : "AnalogBalance", + 0xC628 : "AsShotNeutral", + 0xC629 : "AsShotWhiteXY", + 0xC62A : "BaselineExposure", + 0xC62B : "BaselineNoise", + 0xC62C : "BaselineSharpness", + 0xC62D : "BayerGreenSplit", + 0xC62E : "LinearResponseLimit", + 0xC62F : "CameraSerialNumber", + 0xC630 : "DNGLensInfo", + 0xC631 : "ChromaBlurRadius", + 0xC632 : "AntiAliasStrength", + 0xC633 : "ShadowScale", + 0xC634 : "DNGPrivateData", + 0xC635 : "MakerNoteSafety", + 0xC640 : "RawImageSegmentation", + 0xC65A : "CalibrationIlluminant1", + 0xC65B : "CalibrationIlluminant2", + 0xC65C : "BestQualityScale", + 0xC65D : "RawDataUniqueID", + 0xC660 : "AliasLayerMetadata", + 0xC68B : "OriginalRawFileName", + 0xC68C : "OriginalRawFileData", + 0xC68D : "ActiveArea", + 0xC68E : "MaskedAreas", + 0xC68F : "AsShotICCProfile", + 0xC690 : "AsShotPreProfileMatrix", + 0xC691 : "CurrentICCProfile", + 0xC692 : "CurrentPreProfileMatrix", + 0xC6BF : "ColorimetricReference", + 0xC6D2 : "PanasonicTitle", + 0xC6D3 : "PanasonicTitle2", + 0xC6F3 : "CameraCalibrationSig", + 0xC6F4 : "ProfileCalibrationSig", + 0xC6F5 : "ProfileIFD", + 0xC6F6 : "AsShotProfileName", + 0xC6F7 : "NoiseReductionApplied", + 0xC6F8 : "ProfileName", + 0xC6F9 : "ProfileHueSatMapDims", + 0xC6FA : "ProfileHueSatMapData1", + 0xC6FB : "ProfileHueSatMapData2", + 0xC6FC : "ProfileToneCurve", + 0xC6FD : "ProfileEmbedPolicy", + 0xC6FE : "ProfileCopyright", + 0xC714 : "ForwardMatrix1", + 0xC715 : "ForwardMatrix2", + 0xC716 : "PreviewApplicationName", + 0xC717 : "PreviewApplicationVersion", + 0xC718 : "PreviewSettingsName", + 0xC719 : "PreviewSettingsDigest", + 0xC71A : "PreviewColorSpace", + 0xC71B : "PreviewDateTime", + 0xC71C : "RawImageDigest", + 0xC71D : "OriginalRawFileDigest", + 0xC71E : "SubTileBlockSize", + 0xC71F : "RowInterleaveFactor", + 0xC725 : "ProfileLookTableDims", + 0xC726 : "ProfileLookTableData", + 0xC740 : "OpcodeList1", + 0xC741 : "OpcodeList2", + 0xC74E : "OpcodeList3", + 0xC761 : "NoiseProfile", + 0xC763 : "TimeCodes", + 0xC764 : "FrameRate", + 0xC772 : "TStop", + 0xC789 : "ReelName", + 0xC791 : "OriginalDefaultFinalSize", + 0xC792 : "OriginalBestQualitySize", + 0xC793 : "OriginalDefaultCropSize", + 0xC7A1 : "CameraLabel", + 0xC7A3 : "ProfileHueSatMapEncoding", + 0xC7A4 : "ProfileLookTableEncoding", + 0xC7A5 : "BaselineExposureOffset", + 0xC7A6 : "DefaultBlackRender", + 0xC7A7 : "NewRawImageDigest", + 0xC7A8 : "RawToPreviewGain", + 0xC7B5 : "DefaultUserCrop", + 0xEA1C : "Padding", + 0xEA1D : "OffsetSchema", + 0xFDE8 : "OwnerName", + 0xFDE9 : "SerialNumber", + 0xFDEA : "Lens", + 0xFE00 : "KDC_IFD", + 0xFE4C : "RawFile", + 0xFE4D : "Converter", + 0xFE4E : "WhiteBalance", + 0xFE51 : "Exposure", + 0xFE52 : "Shadows", + 0xFE53 : "Brightness", + 0xFE54 : "Contrast", + 0xFE55 : "Saturation", + 0xFE56 : "Sharpness", + 0xFE57 : "Smoothness", + 0xFE58 : "MoireFilter" + + }, + gps : { + 0x0000 : 'GPSVersionID', + 0x0001 : 'GPSLatitudeRef', + 0x0002 : 'GPSLatitude', + 0x0003 : 'GPSLongitudeRef', + 0x0004 : 'GPSLongitude', + 0x0005 : 'GPSAltitudeRef', + 0x0006 : 'GPSAltitude', + 0x0007 : 'GPSTimeStamp', + 0x0008 : 'GPSSatellites', + 0x0009 : 'GPSStatus', + 0x000A : 'GPSMeasureMode', + 0x000B : 'GPSDOP', + 0x000C : 'GPSSpeedRef', + 0x000D : 'GPSSpeed', + 0x000E : 'GPSTrackRef', + 0x000F : 'GPSTrack', + 0x0010 : 'GPSImgDirectionRef', + 0x0011 : 'GPSImgDirection', + 0x0012 : 'GPSMapDatum', + 0x0013 : 'GPSDestLatitudeRef', + 0x0014 : 'GPSDestLatitude', + 0x0015 : 'GPSDestLongitudeRef', + 0x0016 : 'GPSDestLongitude', + 0x0017 : 'GPSDestBearingRef', + 0x0018 : 'GPSDestBearing', + 0x0019 : 'GPSDestDistanceRef', + 0x001A : 'GPSDestDistance', + 0x001B : 'GPSProcessingMethod', + 0x001C : 'GPSAreaInformation', + 0x001D : 'GPSDateStamp', + 0x001E : 'GPSDifferential', + 0x001F : 'GPSHPositioningError' + } +}; + +/***/ }), + +/***/ 5506: +/***/ ((module) => { + +/*jslint browser: true, devel: true, bitwise: false, debug: true, eqeq: false, es5: true, evil: false, forin: false, newcap: false, nomen: true, plusplus: true, regexp: false, unparam: false, sloppy: true, stupid: false, sub: false, todo: true, vars: true, white: true */ + +function readExifValue(format, stream) { + switch(format) { + case 1: return stream.nextUInt8(); + case 3: return stream.nextUInt16(); + case 4: return stream.nextUInt32(); + case 5: return [stream.nextUInt32(), stream.nextUInt32()]; + case 6: return stream.nextInt8(); + case 8: return stream.nextUInt16(); + case 9: return stream.nextUInt32(); + case 10: return [stream.nextInt32(), stream.nextInt32()]; + case 11: return stream.nextFloat(); + case 12: return stream.nextDouble(); + default: throw new Error('Invalid format while decoding: ' + format); + } +} + +function getBytesPerComponent(format) { + switch(format) { + case 1: + case 2: + case 6: + case 7: + return 1; + case 3: + case 8: + return 2; + case 4: + case 9: + case 11: + return 4; + case 5: + case 10: + case 12: + return 8; + default: + return 0; + } +} + +function readExifTag(tiffMarker, stream) { + var tagType = stream.nextUInt16(), + format = stream.nextUInt16(), + bytesPerComponent = getBytesPerComponent(format), + components = stream.nextUInt32(), + valueBytes = bytesPerComponent * components, + values, + value, + c; + + /* if the value is bigger then 4 bytes, the value is in the data section of the IFD + and the value present in the tag is the offset starting from the tiff header. So we replace the stream + with a stream that is located at the given offset in the data section. s*/ + if(valueBytes > 4) { + stream = tiffMarker.openWithOffset(stream.nextUInt32()); + } + //we don't want to read strings as arrays + if(format === 2) { + values = stream.nextString(components); + //cut off \0 characters + var lastNull = values.indexOf('\0'); + if(lastNull !== -1) { + values = values.substr(0, lastNull); + } + } + else if(format === 7) { + values = stream.nextBuffer(components); + } + else if(format !== 0) { + values = []; + for(c = 0; c < components; ++c) { + values.push(readExifValue(format, stream)); + } + } + //since our stream is a stateful object, we need to skip remaining bytes + //so our offset stays correct + if(valueBytes < 4) { + stream.skip(4 - valueBytes); + } + + return [tagType, values, format]; +} + +function readIFDSection(tiffMarker, stream, iterator) { + var numberOfEntries = stream.nextUInt16(), tag, i; + for(i = 0; i < numberOfEntries; ++i) { + tag = readExifTag(tiffMarker, stream); + iterator(tag[0], tag[1], tag[2]); + } +} + +function readHeader(stream) { + var exifHeader = stream.nextString(6); + if(exifHeader !== 'Exif\0\0') { + throw new Error('Invalid EXIF header'); + } + + var tiffMarker = stream.mark(); + var tiffHeader = stream.nextUInt16(); + if(tiffHeader === 0x4949) { + stream.setBigEndian(false); + } else if(tiffHeader === 0x4D4D) { + stream.setBigEndian(true); + } else { + throw new Error('Invalid TIFF header'); + } + if(stream.nextUInt16() !== 0x002A) { + throw new Error('Invalid TIFF data'); + } + return tiffMarker; +} + +module.exports = { + IFD0: 1, + IFD1: 2, + GPSIFD: 3, + SubIFD: 4, + InteropIFD: 5, + parseTags: function(stream, iterator) { + var tiffMarker; + try { + tiffMarker = readHeader(stream); + } catch(e) { + return false; //ignore APP1 sections with invalid headers + } + var subIfdOffset, gpsOffset, interopOffset; + var ifd0Stream = tiffMarker.openWithOffset(stream.nextUInt32()), + IFD0 = this.IFD0; + readIFDSection(tiffMarker, ifd0Stream, function(tagType, value, format) { + switch(tagType) { + case 0x8825: gpsOffset = value[0]; break; + case 0x8769: subIfdOffset = value[0]; break; + default: iterator(IFD0, tagType, value, format); break; + } + }); + var ifd1Offset = ifd0Stream.nextUInt32(); + if(ifd1Offset !== 0) { + var ifd1Stream = tiffMarker.openWithOffset(ifd1Offset); + readIFDSection(tiffMarker, ifd1Stream, iterator.bind(null, this.IFD1)); + } + + if(gpsOffset) { + var gpsStream = tiffMarker.openWithOffset(gpsOffset); + readIFDSection(tiffMarker, gpsStream, iterator.bind(null, this.GPSIFD)); + } + + if(subIfdOffset) { + var subIfdStream = tiffMarker.openWithOffset(subIfdOffset), InteropIFD = this.InteropIFD; + readIFDSection(tiffMarker, subIfdStream, function(tagType, value, format) { + if(tagType === 0xA005) { + interopOffset = value[0]; + } else { + iterator(InteropIFD, tagType, value, format); + } + }); + } + + if(interopOffset) { + var interopStream = tiffMarker.openWithOffset(interopOffset); + readIFDSection(tiffMarker, interopStream, iterator.bind(null, this.InteropIFD)); + } + return true; + } +}; + +/***/ }), + +/***/ 1659: +/***/ ((module) => { + +/*jslint browser: true, devel: true, bitwise: false, debug: true, eqeq: false, es5: true, evil: false, forin: false, newcap: false, nomen: true, plusplus: true, regexp: false, unparam: false, sloppy: true, stupid: false, sub: false, todo: true, vars: true, white: true */ + +module.exports = { + parseSections: function(stream, iterator) { + var len, markerType; + stream.setBigEndian(true); + //stop reading the stream at the SOS (Start of Stream) marker, + //because its length is not stored in the header so we can't + //know where to jump to. The only marker after that is just EOI (End Of Image) anyway + while(stream.remainingLength() > 0 && markerType !== 0xDA) { + if(stream.nextUInt8() !== 0xFF) { + throw new Error('Invalid JPEG section offset'); + } + markerType = stream.nextUInt8(); + //don't read size from markers that have no datas + if((markerType >= 0xD0 && markerType <= 0xD9) || markerType === 0xDA) { + len = 0; + } else { + len = stream.nextUInt16() - 2; + } + iterator(markerType, stream.branch(0, len)); + stream.skip(len); + } + }, + //stream should be located after SOF section size and in big endian mode, like passed to parseSections iterator + getSizeFromSOFSection: function(stream) { + stream.skip(1); + return { + height: stream.nextUInt16(), + width: stream.nextUInt16() + }; + }, + getSectionName: function(markerType) { + var name, index; + switch(markerType) { + case 0xD8: name = 'SOI'; break; + case 0xC4: name = 'DHT'; break; + case 0xDB: name = 'DQT'; break; + case 0xDD: name = 'DRI'; break; + case 0xDA: name = 'SOS'; break; + case 0xFE: name = 'COM'; break; + case 0xD9: name = 'EOI'; break; + default: + if(markerType >= 0xE0 && markerType <= 0xEF) { + name = 'APP'; + index = markerType - 0xE0; + } + else if(markerType >= 0xC0 && markerType <= 0xCF && markerType !== 0xC4 && markerType !== 0xC8 && markerType !== 0xCC) { + name = 'SOF'; + index = markerType - 0xC0; + } + else if(markerType >= 0xD0 && markerType <= 0xD7) { + name = 'RST'; + index = markerType - 0xD0; + } + break; + } + var nameStruct = { + name: name + }; + if(typeof index === 'number') { + nameStruct.index = index; + } + return nameStruct; + } +}; + +/***/ }), + +/***/ 4898: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/*jslint browser: true, devel: true, bitwise: false, debug: true, eqeq: false, es5: true, evil: false, forin: false, newcap: false, nomen: true, plusplus: true, regexp: false, unparam: false, sloppy: true, stupid: false, sub: false, todo: true, vars: true, white: true */ + +var jpeg = __nccwpck_require__(1659), + exif = __nccwpck_require__(5506), + simplify = __nccwpck_require__(8062); + +function ExifResult(startMarker, tags, imageSize, thumbnailOffset, thumbnailLength, thumbnailType, app1Offset) { + this.startMarker = startMarker; + this.tags = tags; + this.imageSize = imageSize; + this.thumbnailOffset = thumbnailOffset; + this.thumbnailLength = thumbnailLength; + this.thumbnailType = thumbnailType; + this.app1Offset = app1Offset; +} + +ExifResult.prototype = { + hasThumbnail: function(mime) { + if(!this.thumbnailOffset || !this.thumbnailLength) { + return false; + } + if(typeof mime !== 'string') { + return true; + } + if(mime.toLowerCase().trim() === 'image/jpeg') { + return this.thumbnailType === 6; + } + if(mime.toLowerCase().trim() === 'image/tiff') { + return this.thumbnailType === 1; + } + return false; + }, + getThumbnailOffset: function() { + return this.app1Offset + 6 + this.thumbnailOffset; + }, + getThumbnailLength: function() { + return this.thumbnailLength; + }, + getThumbnailBuffer: function() { + return this._getThumbnailStream().nextBuffer(this.thumbnailLength); + }, + _getThumbnailStream: function() { + return this.startMarker.openWithOffset(this.getThumbnailOffset()); + }, + getImageSize: function() { + return this.imageSize; + }, + getThumbnailSize: function() { + var stream = this._getThumbnailStream(), size; + jpeg.parseSections(stream, function(sectionType, sectionStream) { + if(jpeg.getSectionName(sectionType).name === 'SOF') { + size = jpeg.getSizeFromSOFSection(sectionStream); + } + }); + return size; + } +}; + +function Parser(stream) { + this.stream = stream; + this.flags = { + readBinaryTags: false, + resolveTagNames: true, + simplifyValues: true, + imageSize: true, + hidePointers: true, + returnTags: true + }; +} + +Parser.prototype = { + enableBinaryFields: function(enable) { + this.flags.readBinaryTags = !!enable; + return this; + }, + enablePointers: function(enable) { + this.flags.hidePointers = !enable; + return this; + }, + enableTagNames: function(enable) { + this.flags.resolveTagNames = !!enable; + return this; + }, + enableImageSize: function(enable) { + this.flags.imageSize = !!enable; + return this; + }, + enableReturnTags: function(enable) { + this.flags.returnTags = !!enable; + return this; + }, + enableSimpleValues: function(enable) { + this.flags.simplifyValues = !!enable; + return this; + }, + parse: function() { + var start = this.stream.mark(), + stream = start.openWithOffset(0), + flags = this.flags, + tags, + imageSize, + thumbnailOffset, + thumbnailLength, + thumbnailType, + app1Offset, + tagNames, + getTagValue, setTagValue; + if(flags.resolveTagNames) { + tagNames = __nccwpck_require__(1494); + } + if(flags.resolveTagNames) { + tags = {}; + getTagValue = function(t) { + return tags[t.name]; + }; + setTagValue = function(t, value) { + tags[t.name] = value; + }; + } else { + tags = []; + getTagValue = function(t) { + var i; + for(i = 0; i < tags.length; ++i) { + if(tags[i].type === t.type && tags[i].section === t.section) { + return tags.value; + } + } + }; + setTagValue = function(t, value) { + var i; + for(i = 0; i < tags.length; ++i) { + if(tags[i].type === t.type && tags[i].section === t.section) { + tags.value = value; + return; + } + } + }; + } + + jpeg.parseSections(stream, function(sectionType, sectionStream) { + var validExifHeaders, sectionOffset = sectionStream.offsetFrom(start); + if(sectionType === 0xE1) { + validExifHeaders = exif.parseTags(sectionStream, function(ifdSection, tagType, value, format) { + //ignore binary fields if disabled + if(!flags.readBinaryTags && format === 7) { + return; + } + + if(tagType === 0x0201) { + thumbnailOffset = value[0]; + if(flags.hidePointers) {return;} + } else if(tagType === 0x0202) { + thumbnailLength = value[0]; + if(flags.hidePointers) {return;} + } else if(tagType === 0x0103) { + thumbnailType = value[0]; + if(flags.hidePointers) {return;} + } + //if flag is set to not store tags, return here after storing pointers + if(!flags.returnTags) { + return; + } + + if(flags.simplifyValues) { + value = simplify.simplifyValue(value, format); + } + if(flags.resolveTagNames) { + var sectionTagNames = ifdSection === exif.GPSIFD ? tagNames.gps : tagNames.exif; + var name = sectionTagNames[tagType]; + if(!name) { + name = tagNames.exif[tagType]; + } + if (!tags.hasOwnProperty(name)) { + tags[name] = value; + } + } else { + tags.push({ + section: ifdSection, + type: tagType, + value: value + }); + } + }); + if(validExifHeaders) { + app1Offset = sectionOffset; + } + } + else if(flags.imageSize && jpeg.getSectionName(sectionType).name === 'SOF') { + imageSize = jpeg.getSizeFromSOFSection(sectionStream); + } + }); + + if(flags.simplifyValues) { + simplify.castDegreeValues(getTagValue, setTagValue); + simplify.castDateValues(getTagValue, setTagValue); + } + + return new ExifResult(start, tags, imageSize, thumbnailOffset, thumbnailLength, thumbnailType, app1Offset); + } +}; + + + +module.exports = Parser; + + +/***/ }), + +/***/ 8062: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var exif = __nccwpck_require__(5506); +var date = __nccwpck_require__(610); + +var degreeTags = [{ + section: exif.GPSIFD, + type: 0x0002, + name: 'GPSLatitude', + refType: 0x0001, + refName: 'GPSLatitudeRef', + posVal: 'N' +}, +{ + section: exif.GPSIFD, + type: 0x0004, + name: 'GPSLongitude', + refType: 0x0003, + refName: 'GPSLongitudeRef', + posVal: 'E' +}]; +var dateTags = [{ + section: exif.SubIFD, + type: 0x0132, + name: 'ModifyDate' +}, +{ + section: exif.SubIFD, + type: 0x9003, + name: 'DateTimeOriginal' +}, +{ + section: exif.SubIFD, + type: 0x9004, + name: 'CreateDate' +}, +{ + section: exif.SubIFD, + type: 0x0132, + name : 'ModifyDate', +}]; + +module.exports = { + castDegreeValues: function(getTagValue, setTagValue) { + degreeTags.forEach(function(t) { + var degreeVal = getTagValue(t); + if(degreeVal) { + var degreeRef = getTagValue({section: t.section, type: t.refType, name: t.refName}); + var degreeNumRef = degreeRef === t.posVal ? 1 : -1; + var degree = (degreeVal[0] + (degreeVal[1] / 60) + (degreeVal[2] / 3600)) * degreeNumRef; + setTagValue(t, degree); + } + }); + }, + castDateValues: function(getTagValue, setTagValue) { + dateTags.forEach(function(t) { + var dateStrVal = getTagValue(t); + if(dateStrVal) { + //some easy checks to determine two common date formats + var timestamp = date.parseExifDate(dateStrVal); + if(typeof timestamp !== 'undefined') { + setTagValue(t, timestamp); + } + } + }); + }, + simplifyValue: function(values, format) { + if(Array.isArray(values)) { + values = values.map(function(value) { + if(format === 10 || format === 5) { + return value[0] / value[1]; + } + return value; + }); + if(values.length === 1) { + values = values[0]; + } + } + return values; + } +}; + + +/***/ }), + +/***/ 4930: +/***/ ((module) => { + +"use strict"; + +const toBytes = s => [...s].map(c => c.charCodeAt(0)); +const xpiZipFilename = toBytes('META-INF/mozilla.rsa'); +const oxmlContentTypes = toBytes('[Content_Types].xml'); +const oxmlRels = toBytes('_rels/.rels'); + +module.exports = input => { + const buf = input instanceof Uint8Array ? input : new Uint8Array(input); + + if (!(buf && buf.length > 1)) { + return null; + } + + const check = (header, options) => { + options = Object.assign({ + offset: 0 + }, options); + + for (let i = 0; i < header.length; i++) { + // If a bitmask is set + if (options.mask) { + // If header doesn't equal `buf` with bits masked off + if (header[i] !== (options.mask[i] & buf[i + options.offset])) { + return false; + } + } else if (header[i] !== buf[i + options.offset]) { + return false; + } + } + + return true; + }; + + const checkString = (header, options) => check(toBytes(header), options); + + if (check([0xFF, 0xD8, 0xFF])) { + return { + ext: 'jpg', + mime: 'image/jpeg' + }; + } + + if (check([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A])) { + return { + ext: 'png', + mime: 'image/png' + }; + } + + if (check([0x47, 0x49, 0x46])) { + return { + ext: 'gif', + mime: 'image/gif' + }; + } + + if (check([0x57, 0x45, 0x42, 0x50], {offset: 8})) { + return { + ext: 'webp', + mime: 'image/webp' + }; + } + + if (check([0x46, 0x4C, 0x49, 0x46])) { + return { + ext: 'flif', + mime: 'image/flif' + }; + } + + // Needs to be before `tif` check + if ( + (check([0x49, 0x49, 0x2A, 0x0]) || check([0x4D, 0x4D, 0x0, 0x2A])) && + check([0x43, 0x52], {offset: 8}) + ) { + return { + ext: 'cr2', + mime: 'image/x-canon-cr2' + }; + } + + if ( + check([0x49, 0x49, 0x2A, 0x0]) || + check([0x4D, 0x4D, 0x0, 0x2A]) + ) { + return { + ext: 'tif', + mime: 'image/tiff' + }; + } + + if (check([0x42, 0x4D])) { + return { + ext: 'bmp', + mime: 'image/bmp' + }; + } + + if (check([0x49, 0x49, 0xBC])) { + return { + ext: 'jxr', + mime: 'image/vnd.ms-photo' + }; + } + + if (check([0x38, 0x42, 0x50, 0x53])) { + return { + ext: 'psd', + mime: 'image/vnd.adobe.photoshop' + }; + } + + // Zip-based file formats + // Need to be before the `zip` check + if (check([0x50, 0x4B, 0x3, 0x4])) { + if ( + check([0x6D, 0x69, 0x6D, 0x65, 0x74, 0x79, 0x70, 0x65, 0x61, 0x70, 0x70, 0x6C, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6F, 0x6E, 0x2F, 0x65, 0x70, 0x75, 0x62, 0x2B, 0x7A, 0x69, 0x70], {offset: 30}) + ) { + return { + ext: 'epub', + mime: 'application/epub+zip' + }; + } + + // Assumes signed `.xpi` from addons.mozilla.org + if (check(xpiZipFilename, {offset: 30})) { + return { + ext: 'xpi', + mime: 'application/x-xpinstall' + }; + } + + if (checkString('mimetypeapplication/vnd.oasis.opendocument.text', {offset: 30})) { + return { + ext: 'odt', + mime: 'application/vnd.oasis.opendocument.text' + }; + } + + if (checkString('mimetypeapplication/vnd.oasis.opendocument.spreadsheet', {offset: 30})) { + return { + ext: 'ods', + mime: 'application/vnd.oasis.opendocument.spreadsheet' + }; + } + + if (checkString('mimetypeapplication/vnd.oasis.opendocument.presentation', {offset: 30})) { + return { + ext: 'odp', + mime: 'application/vnd.oasis.opendocument.presentation' + }; + } + + // The docx, xlsx and pptx file types extend the Office Open XML file format: + // https://en.wikipedia.org/wiki/Office_Open_XML_file_formats + // We look for: + // - one entry named '[Content_Types].xml' or '_rels/.rels', + // - one entry indicating specific type of file. + // MS Office, OpenOffice and LibreOffice may put the parts in different order, so the check should not rely on it. + const findNextZipHeaderIndex = (arr, startAt = 0) => arr.findIndex((el, i, arr) => i >= startAt && arr[i] === 0x50 && arr[i + 1] === 0x4B && arr[i + 2] === 0x3 && arr[i + 3] === 0x4); + + let zipHeaderIndex = 0; // The first zip header was already found at index 0 + let oxmlFound = false; + let type = null; + + do { + const offset = zipHeaderIndex + 30; + + if (!oxmlFound) { + oxmlFound = (check(oxmlContentTypes, {offset}) || check(oxmlRels, {offset})); + } + + if (!type) { + if (checkString('word/', {offset})) { + type = { + ext: 'docx', + mime: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' + }; + } else if (checkString('ppt/', {offset})) { + type = { + ext: 'pptx', + mime: 'application/vnd.openxmlformats-officedocument.presentationml.presentation' + }; + } else if (checkString('xl/', {offset})) { + type = { + ext: 'xlsx', + mime: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' + }; + } + } + + if (oxmlFound && type) { + return type; + } + + zipHeaderIndex = findNextZipHeaderIndex(buf, offset); + } while (zipHeaderIndex >= 0); + + // No more zip parts available in the buffer, but maybe we are almost certain about the type? + if (type) { + return type; + } + } + + if ( + check([0x50, 0x4B]) && + (buf[2] === 0x3 || buf[2] === 0x5 || buf[2] === 0x7) && + (buf[3] === 0x4 || buf[3] === 0x6 || buf[3] === 0x8) + ) { + return { + ext: 'zip', + mime: 'application/zip' + }; + } + + if (check([0x75, 0x73, 0x74, 0x61, 0x72], {offset: 257})) { + return { + ext: 'tar', + mime: 'application/x-tar' + }; + } + + if ( + check([0x52, 0x61, 0x72, 0x21, 0x1A, 0x7]) && + (buf[6] === 0x0 || buf[6] === 0x1) + ) { + return { + ext: 'rar', + mime: 'application/x-rar-compressed' + }; + } + + if (check([0x1F, 0x8B, 0x8])) { + return { + ext: 'gz', + mime: 'application/gzip' + }; + } + + if (check([0x42, 0x5A, 0x68])) { + return { + ext: 'bz2', + mime: 'application/x-bzip2' + }; + } + + if (check([0x37, 0x7A, 0xBC, 0xAF, 0x27, 0x1C])) { + return { + ext: '7z', + mime: 'application/x-7z-compressed' + }; + } + + if (check([0x78, 0x01])) { + return { + ext: 'dmg', + mime: 'application/x-apple-diskimage' + }; + } + + if (check([0x33, 0x67, 0x70, 0x35]) || // 3gp5 + ( + check([0x0, 0x0, 0x0]) && check([0x66, 0x74, 0x79, 0x70], {offset: 4}) && + ( + check([0x6D, 0x70, 0x34, 0x31], {offset: 8}) || // MP41 + check([0x6D, 0x70, 0x34, 0x32], {offset: 8}) || // MP42 + check([0x69, 0x73, 0x6F, 0x6D], {offset: 8}) || // ISOM + check([0x69, 0x73, 0x6F, 0x32], {offset: 8}) || // ISO2 + check([0x6D, 0x6D, 0x70, 0x34], {offset: 8}) || // MMP4 + check([0x4D, 0x34, 0x56], {offset: 8}) || // M4V + check([0x64, 0x61, 0x73, 0x68], {offset: 8}) // DASH + ) + )) { + return { + ext: 'mp4', + mime: 'video/mp4' + }; + } + + if (check([0x4D, 0x54, 0x68, 0x64])) { + return { + ext: 'mid', + mime: 'audio/midi' + }; + } + + // https://github.com/threatstack/libmagic/blob/master/magic/Magdir/matroska + if (check([0x1A, 0x45, 0xDF, 0xA3])) { + const sliced = buf.subarray(4, 4 + 4096); + const idPos = sliced.findIndex((el, i, arr) => arr[i] === 0x42 && arr[i + 1] === 0x82); + + if (idPos !== -1) { + const docTypePos = idPos + 3; + const findDocType = type => [...type].every((c, i) => sliced[docTypePos + i] === c.charCodeAt(0)); + + if (findDocType('matroska')) { + return { + ext: 'mkv', + mime: 'video/x-matroska' + }; + } + + if (findDocType('webm')) { + return { + ext: 'webm', + mime: 'video/webm' + }; + } + } + } + + if (check([0x0, 0x0, 0x0, 0x14, 0x66, 0x74, 0x79, 0x70, 0x71, 0x74, 0x20, 0x20]) || + check([0x66, 0x72, 0x65, 0x65], {offset: 4}) || + check([0x66, 0x74, 0x79, 0x70, 0x71, 0x74, 0x20, 0x20], {offset: 4}) || + check([0x6D, 0x64, 0x61, 0x74], {offset: 4}) || // MJPEG + check([0x77, 0x69, 0x64, 0x65], {offset: 4})) { + return { + ext: 'mov', + mime: 'video/quicktime' + }; + } + + // RIFF file format which might be AVI, WAV, QCP, etc + if (check([0x52, 0x49, 0x46, 0x46])) { + if (check([0x41, 0x56, 0x49], {offset: 8})) { + return { + ext: 'avi', + mime: 'video/vnd.avi' + }; + } + if (check([0x57, 0x41, 0x56, 0x45], {offset: 8})) { + return { + ext: 'wav', + mime: 'audio/vnd.wave' + }; + } + // QLCM, QCP file + if (check([0x51, 0x4C, 0x43, 0x4D], {offset: 8})) { + return { + ext: 'qcp', + mime: 'audio/qcelp' + }; + } + } + + if (check([0x30, 0x26, 0xB2, 0x75, 0x8E, 0x66, 0xCF, 0x11, 0xA6, 0xD9])) { + return { + ext: 'wmv', + mime: 'video/x-ms-wmv' + }; + } + + if ( + check([0x0, 0x0, 0x1, 0xBA]) || + check([0x0, 0x0, 0x1, 0xB3]) + ) { + return { + ext: 'mpg', + mime: 'video/mpeg' + }; + } + + if (check([0x66, 0x74, 0x79, 0x70, 0x33, 0x67], {offset: 4})) { + return { + ext: '3gp', + mime: 'video/3gpp' + }; + } + + // Check for MPEG header at different starting offsets + for (let start = 0; start < 2 && start < (buf.length - 16); start++) { + if ( + check([0x49, 0x44, 0x33], {offset: start}) || // ID3 header + check([0xFF, 0xE2], {offset: start, mask: [0xFF, 0xE2]}) // MPEG 1 or 2 Layer 3 header + ) { + return { + ext: 'mp3', + mime: 'audio/mpeg' + }; + } + + if ( + check([0xFF, 0xE4], {offset: start, mask: [0xFF, 0xE4]}) // MPEG 1 or 2 Layer 2 header + ) { + return { + ext: 'mp2', + mime: 'audio/mpeg' + }; + } + + if ( + check([0xFF, 0xF8], {offset: start, mask: [0xFF, 0xFC]}) // MPEG 2 layer 0 using ADTS + ) { + return { + ext: 'mp2', + mime: 'audio/mpeg' + }; + } + + if ( + check([0xFF, 0xF0], {offset: start, mask: [0xFF, 0xFC]}) // MPEG 4 layer 0 using ADTS + ) { + return { + ext: 'mp4', + mime: 'audio/mpeg' + }; + } + } + + if ( + check([0x66, 0x74, 0x79, 0x70, 0x4D, 0x34, 0x41], {offset: 4}) || + check([0x4D, 0x34, 0x41, 0x20]) + ) { + return { // MPEG-4 layer 3 (audio) + ext: 'm4a', + mime: 'audio/mp4' // RFC 4337 + }; + } + + // Needs to be before `ogg` check + if (check([0x4F, 0x70, 0x75, 0x73, 0x48, 0x65, 0x61, 0x64], {offset: 28})) { + return { + ext: 'opus', + mime: 'audio/opus' + }; + } + + // If 'OggS' in first bytes, then OGG container + if (check([0x4F, 0x67, 0x67, 0x53])) { + // This is a OGG container + + // If ' theora' in header. + if (check([0x80, 0x74, 0x68, 0x65, 0x6F, 0x72, 0x61], {offset: 28})) { + return { + ext: 'ogv', + mime: 'video/ogg' + }; + } + // If '\x01video' in header. + if (check([0x01, 0x76, 0x69, 0x64, 0x65, 0x6F, 0x00], {offset: 28})) { + return { + ext: 'ogm', + mime: 'video/ogg' + }; + } + // If ' FLAC' in header https://xiph.org/flac/faq.html + if (check([0x7F, 0x46, 0x4C, 0x41, 0x43], {offset: 28})) { + return { + ext: 'oga', + mime: 'audio/ogg' + }; + } + + // 'Speex ' in header https://en.wikipedia.org/wiki/Speex + if (check([0x53, 0x70, 0x65, 0x65, 0x78, 0x20, 0x20], {offset: 28})) { + return { + ext: 'spx', + mime: 'audio/ogg' + }; + } + + // If '\x01vorbis' in header + if (check([0x01, 0x76, 0x6F, 0x72, 0x62, 0x69, 0x73], {offset: 28})) { + return { + ext: 'ogg', + mime: 'audio/ogg' + }; + } + + // Default OGG container https://www.iana.org/assignments/media-types/application/ogg + return { + ext: 'ogx', + mime: 'application/ogg' + }; + } + + if (check([0x66, 0x4C, 0x61, 0x43])) { + return { + ext: 'flac', + mime: 'audio/x-flac' + }; + } + + if (check([0x4D, 0x41, 0x43, 0x20])) { // 'MAC ' + return { + ext: 'ape', + mime: 'audio/ape' + }; + } + + if (check([0x77, 0x76, 0x70, 0x6B])) { // 'wvpk' + return { + ext: 'wv', + mime: 'audio/wavpack' + }; + } + + if (check([0x23, 0x21, 0x41, 0x4D, 0x52, 0x0A])) { + return { + ext: 'amr', + mime: 'audio/amr' + }; + } + + if (check([0x25, 0x50, 0x44, 0x46])) { + return { + ext: 'pdf', + mime: 'application/pdf' + }; + } + + if (check([0x4D, 0x5A])) { + return { + ext: 'exe', + mime: 'application/x-msdownload' + }; + } + + if ( + (buf[0] === 0x43 || buf[0] === 0x46) && + check([0x57, 0x53], {offset: 1}) + ) { + return { + ext: 'swf', + mime: 'application/x-shockwave-flash' + }; + } + + if (check([0x7B, 0x5C, 0x72, 0x74, 0x66])) { + return { + ext: 'rtf', + mime: 'application/rtf' + }; + } + + if (check([0x00, 0x61, 0x73, 0x6D])) { + return { + ext: 'wasm', + mime: 'application/wasm' + }; + } + + if ( + check([0x77, 0x4F, 0x46, 0x46]) && + ( + check([0x00, 0x01, 0x00, 0x00], {offset: 4}) || + check([0x4F, 0x54, 0x54, 0x4F], {offset: 4}) + ) + ) { + return { + ext: 'woff', + mime: 'font/woff' + }; + } + + if ( + check([0x77, 0x4F, 0x46, 0x32]) && + ( + check([0x00, 0x01, 0x00, 0x00], {offset: 4}) || + check([0x4F, 0x54, 0x54, 0x4F], {offset: 4}) + ) + ) { + return { + ext: 'woff2', + mime: 'font/woff2' + }; + } + + if ( + check([0x4C, 0x50], {offset: 34}) && + ( + check([0x00, 0x00, 0x01], {offset: 8}) || + check([0x01, 0x00, 0x02], {offset: 8}) || + check([0x02, 0x00, 0x02], {offset: 8}) + ) + ) { + return { + ext: 'eot', + mime: 'application/vnd.ms-fontobject' + }; + } + + if (check([0x00, 0x01, 0x00, 0x00, 0x00])) { + return { + ext: 'ttf', + mime: 'font/ttf' + }; + } + + if (check([0x4F, 0x54, 0x54, 0x4F, 0x00])) { + return { + ext: 'otf', + mime: 'font/otf' + }; + } + + if (check([0x00, 0x00, 0x01, 0x00])) { + return { + ext: 'ico', + mime: 'image/x-icon' + }; + } + + if (check([0x00, 0x00, 0x02, 0x00])) { + return { + ext: 'cur', + mime: 'image/x-icon' + }; + } + + if (check([0x46, 0x4C, 0x56, 0x01])) { + return { + ext: 'flv', + mime: 'video/x-flv' + }; + } + + if (check([0x25, 0x21])) { + return { + ext: 'ps', + mime: 'application/postscript' + }; + } + + if (check([0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00])) { + return { + ext: 'xz', + mime: 'application/x-xz' + }; + } + + if (check([0x53, 0x51, 0x4C, 0x69])) { + return { + ext: 'sqlite', + mime: 'application/x-sqlite3' + }; + } + + if (check([0x4E, 0x45, 0x53, 0x1A])) { + return { + ext: 'nes', + mime: 'application/x-nintendo-nes-rom' + }; + } + + if (check([0x43, 0x72, 0x32, 0x34])) { + return { + ext: 'crx', + mime: 'application/x-google-chrome-extension' + }; + } + + if ( + check([0x4D, 0x53, 0x43, 0x46]) || + check([0x49, 0x53, 0x63, 0x28]) + ) { + return { + ext: 'cab', + mime: 'application/vnd.ms-cab-compressed' + }; + } + + // Needs to be before `ar` check + if (check([0x21, 0x3C, 0x61, 0x72, 0x63, 0x68, 0x3E, 0x0A, 0x64, 0x65, 0x62, 0x69, 0x61, 0x6E, 0x2D, 0x62, 0x69, 0x6E, 0x61, 0x72, 0x79])) { + return { + ext: 'deb', + mime: 'application/x-deb' + }; + } + + if (check([0x21, 0x3C, 0x61, 0x72, 0x63, 0x68, 0x3E])) { + return { + ext: 'ar', + mime: 'application/x-unix-archive' + }; + } + + if (check([0xED, 0xAB, 0xEE, 0xDB])) { + return { + ext: 'rpm', + mime: 'application/x-rpm' + }; + } + + if ( + check([0x1F, 0xA0]) || + check([0x1F, 0x9D]) + ) { + return { + ext: 'Z', + mime: 'application/x-compress' + }; + } + + if (check([0x4C, 0x5A, 0x49, 0x50])) { + return { + ext: 'lz', + mime: 'application/x-lzip' + }; + } + + if (check([0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1])) { + return { + ext: 'msi', + mime: 'application/x-msi' + }; + } + + if (check([0x06, 0x0E, 0x2B, 0x34, 0x02, 0x05, 0x01, 0x01, 0x0D, 0x01, 0x02, 0x01, 0x01, 0x02])) { + return { + ext: 'mxf', + mime: 'application/mxf' + }; + } + + if (check([0x47], {offset: 4}) && (check([0x47], {offset: 192}) || check([0x47], {offset: 196}))) { + return { + ext: 'mts', + mime: 'video/mp2t' + }; + } + + if (check([0x42, 0x4C, 0x45, 0x4E, 0x44, 0x45, 0x52])) { + return { + ext: 'blend', + mime: 'application/x-blender' + }; + } + + if (check([0x42, 0x50, 0x47, 0xFB])) { + return { + ext: 'bpg', + mime: 'image/bpg' + }; + } + + if (check([0x00, 0x00, 0x00, 0x0C, 0x6A, 0x50, 0x20, 0x20, 0x0D, 0x0A, 0x87, 0x0A])) { + // JPEG-2000 family + + if (check([0x6A, 0x70, 0x32, 0x20], {offset: 20})) { + return { + ext: 'jp2', + mime: 'image/jp2' + }; + } + + if (check([0x6A, 0x70, 0x78, 0x20], {offset: 20})) { + return { + ext: 'jpx', + mime: 'image/jpx' + }; + } + + if (check([0x6A, 0x70, 0x6D, 0x20], {offset: 20})) { + return { + ext: 'jpm', + mime: 'image/jpm' + }; + } + + if (check([0x6D, 0x6A, 0x70, 0x32], {offset: 20})) { + return { + ext: 'mj2', + mime: 'image/mj2' + }; + } + } + + if (check([0x46, 0x4F, 0x52, 0x4D, 0x00])) { + return { + ext: 'aif', + mime: 'audio/aiff' + }; + } + + if (checkString(' { + +var debug; + +module.exports = function () { + if (!debug) { + try { + /* eslint global-require: off */ + debug = __nccwpck_require__(8237)("follow-redirects"); + } + catch (error) { /* */ } + if (typeof debug !== "function") { + debug = function () { /* */ }; + } + } + debug.apply(null, arguments); +}; + + +/***/ }), + +/***/ 7707: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +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); + +// 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); + }; +}); + +// 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); + }; + + // Perform the first request + this._performRequest(); +} +RedirectableRequest.prototype = Object.create(Writable.prototype); + +RedirectableRequest.prototype.abort = function () { + abortRequest(this._currentRequest); + this.emit("abort"); +}; + +// 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(); + } + + // Validate input and shift parameters if necessary + if (!(typeof data === "string" || typeof data === "object" && ("length" in data))) { + throw new TypeError("data should be a string, Buffer or Uint8Array"); + } + if (typeof encoding === "function") { + callback = encoding; + encoding = null; + } + + // 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(); + } +}; + +// Ends the current native request +RedirectableRequest.prototype.end = function (data, encoding, callback) { + // Shift parameters if necessary + if (typeof data === "function") { + callback = data; + data = encoding = null; + } + else if (typeof encoding === "function") { + callback = encoding; + encoding = null; + } + + // 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; + + // Destroys the socket on timeout + function destroyOnTimeout(socket) { + socket.setTimeout(msecs); + socket.removeListener("timeout", socket.destroy); + socket.addListener("timeout", socket.destroy); + } + + // 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); + } + } + + // Attach callback if passed + if (callback) { + this.on("timeout", callback); + } + + // Start the timer if or when the socket is opened + if (this.socket) { + startTimer(this.socket); + } + else { + this._currentRequest.once("socket", startTimer); + } + + // Clean up on events + this.on("socket", destroyOnTimeout); + this.on("abort", clearTimer); + this.on("error", clearTimer); + this.on("response", clearTimer); + + return this; +}; + +// 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); + }; +}); + +// Proxy all public ClientRequest properties +["aborted", "connection", "socket"].forEach(function (property) { + Object.defineProperty(RedirectableRequest.prototype, property, { + get: function () { return this._currentRequest[property]; }, + }); +}); + +RedirectableRequest.prototype._sanitizeOptions = function (options) { + // Ensure headers are always present + if (!options.headers) { + options.headers = {}; + } + + // 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; + } + + // 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); + } + } +}; + + +// 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; + } + + // 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]; + } + + // 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]); + } + + // 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._currentUrl = this._options.path; + + // 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. + + // 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; + } + + // 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); + } + + // 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); + } + + // Drop the Host header, as the redirect might lead to a different host + var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers); + + // 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 })); + + // Determine the URL of the redirection + var redirectUrl; + try { + redirectUrl = url.resolve(currentUrl, location); + } + catch (cause) { + this.emit("error", new RedirectionError(cause)); + return; + } + + // Create the redirected request + debug("redirecting to", redirectUrl); + this._isRedirect = true; + var redirectUrlParts = url.parse(redirectUrl); + Object.assign(this._options, redirectUrlParts); + + // 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 (typeof beforeRedirect === "function") { + 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); + } + + // Perform the redirected request + try { + this._performRequest(); + } + catch (cause) { + this.emit("error", new RedirectionError(cause)); + } +}; + +// Wraps the key/value object of protocols with redirect functionality +function wrap(protocols) { + // Default settings + var exports = { + maxRedirects: 21, + maxBodyLength: 10 * 1024 * 1024, + }; + + // 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); + + // Executes a request, following redirects + function request(input, options, callback) { + // Parse parameters + if (typeof input === "string") { + var urlStr = input; + try { + input = urlToOptions(new URL(urlStr)); + } + catch (err) { + /* istanbul ignore next */ + input = url.parse(urlStr); + } + } + else if (URL && (input instanceof URL)) { + input = urlToOptions(input); + } + else { + callback = options; + options = input; + input = { protocol: protocol }; + } + if (typeof options === "function") { + callback = options; + options = null; + } + + // Set defaults + options = Object.assign({ + maxRedirects: exports.maxRedirects, + maxBodyLength: exports.maxBodyLength, + }, input, options); + options.nativeProtocols = nativeProtocols; + + assert.equal(options.protocol, protocol, "protocol mismatch"); + debug("options", options); + return new RedirectableRequest(options, callback); + } + + // Executes a GET request, following redirects + function get(input, options, callback) { + var wrappedRequest = wrappedProtocol.request(input, options, callback); + wrappedRequest.end(); + return wrappedRequest; + } + + // 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; +} + +/* istanbul ignore next */ +function noop() { /* empty */ } + +// 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; +} + +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 createErrorType(code, defaultMessage) { + function CustomError(cause) { + Error.captureStackTrace(this, this.constructor); + if (!cause) { + this.message = defaultMessage; + } + else { + this.message = defaultMessage + ": " + cause.message; + this.cause = cause; + } + } + CustomError.prototype = new Error(); + CustomError.prototype.constructor = CustomError; + CustomError.prototype.name = "Error [" + code + "]"; + CustomError.prototype.code = code; + return CustomError; +} + +function abortRequest(request) { + for (var event of events) { + request.removeListener(event, eventHandlers[event]); + } + request.on("error", noop); + request.abort(); +} + +function isSubdomain(subdomain, domain) { + const dot = subdomain.length - domain.length - 1; + return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain); +} + +// Exports +module.exports = wrap({ http: http, https: https }); +module.exports.wrap = wrap; + + +/***/ }), + +/***/ 4334: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +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); + } + + this._overheadLength = 0; + this._valueLength = 0; + this._valuesToMeasure = []; + + CombinedStream.call(this); + + options = options || {}; + for (var option in options) { + this[option] = options[option]; + } +} + +FormData.LINE_BREAK = '\r\n'; +FormData.DEFAULT_CONTENT_TYPE = 'application/octet-stream'; + +FormData.prototype.append = function(field, value, options) { + + options = options || {}; + + // allow filename as single option + if (typeof options == 'string') { + options = {filename: options}; + } + + var append = CombinedStream.prototype.append.bind(this); + + // all that streamy business can't handle numbers + if (typeof value == 'number') { + value = '' + value; + } + + // 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; + } + + var header = this._multiPartHeader(field, value, options); + var footer = this._multiPartFooter(); + + append(header); + append(value); + append(footer); + + // pass along options.knownLength + this._trackLength(header, value, options); +}; + +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); + } + + this._valueLength += valueLength; + + // @check why add CRLF? does this account for custom/multiple CRLFs? + this._overheadLength += + Buffer.byteLength(header) + + FormData.LINE_BREAK.length; + + // 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; + } + + // no need to bother with the length + if (!options.knownLength) { + this._valuesToMeasure.push(value); + } +}; + +FormData.prototype._lengthRetriever = function(value, callback) { + + if (value.hasOwnProperty('fd')) { + + // 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) { + + // when end specified + // no need to calculate range + // inclusive, starts with 0 + callback(null, value.end + 1 - (value.start ? value.start : 0)); + + // not that fast snoopy + } else { + // still need to fetch file size from fs + fs.stat(value.path, function(err, stat) { + + var fileSize; + + 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']); + + // 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(); + + // 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; + } + + var contentDisposition = this._getContentDisposition(value, options); + var contentType = this._getContentType(value, options); + + 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 || []) + }; + + // allow custom headers. + if (typeof options.header == 'object') { + populate(headers, options.header); + } + + var header; + for (var prop in headers) { + if (!headers.hasOwnProperty(prop)) continue; + header = headers[prop]; + + // 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; + } + } + + return '--' + this.getBoundary() + FormData.LINE_BREAK + contents + FormData.LINE_BREAK; +}; + +FormData.prototype._getContentDisposition = function(value, options) { + + var filename + , contentDisposition + ; + + 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 || ''); + } + + if (filename) { + contentDisposition = 'filename="' + filename + '"'; + } + + return contentDisposition; +}; + +FormData.prototype._getContentType = function(value, options) { + + // use custom content-type above all + var contentType = options.contentType; + + // or try `name` from formidable, browser + if (!contentType && value.name) { + contentType = mime.lookup(value.name); + } + + // or try `path` from fs-, request- streams + if (!contentType && value.path) { + contentType = mime.lookup(value.path); + } + + // or if it's http-reponse + if (!contentType && value.readable && value.hasOwnProperty('httpVersion')) { + contentType = value.headers['content-type']; + } + + // or guess it from the filepath or filename + if (!contentType && (options.filepath || options.filename)) { + contentType = mime.lookup(options.filepath || options.filename); + } + + // 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; + + var lastPart = (this._streams.length === 0); + if (lastPart) { + footer += this._lastBoundary(); + } + + next(footer); + }.bind(this); +}; + +FormData.prototype._lastBoundary = function() { + return '--' + this.getBoundary() + '--' + FormData.LINE_BREAK; +}; + +FormData.prototype.getHeaders = function(userHeaders) { + var header; + var formHeaders = { + 'content-type': 'multipart/form-data; boundary=' + this.getBoundary() + }; + + for (header in userHeaders) { + if (userHeaders.hasOwnProperty(header)) { + formHeaders[header.toLowerCase()] = userHeaders[header]; + } + } + + return formHeaders; +}; + +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)] ); + } + } + } + + // 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; +}; + +// 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; + } + + // 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 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; + } + + return hasKnownLength; +}; + +FormData.prototype.getLength = function(cb) { + var knownLength = this._overheadLength + this._valueLength; + + if (this._streams.length) { + knownLength += this._lastBoundary().length; + } + + if (!this._valuesToMeasure.length) { + process.nextTick(cb.bind(this, null, knownLength)); + return; + } + + asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function(err, values) { + if (err) { + cb(err); + return; + } + + values.forEach(function(length) { + knownLength += length; + }); + + cb(null, knownLength); + }); +}; + +FormData.prototype.submit = function(params, cb) { + var request + , options + , defaults = {method: 'post'} + ; + + // parse provided url if it's string + // or treat it as options object + if (typeof params == 'string') { + + params = parseUrl(params); + options = populate({ + port: params.port, + path: params.pathname, + host: params.hostname, + protocol: params.protocol + }, defaults); + + // use custom params + } else { + + options = populate(params, defaults); + // if no port provided use default one + if (!options.port) { + options.port = options.protocol == 'https:' ? 443 : 80; + } + } + + // put that good code in getHeaders to some use + options.headers = this.getHeaders(params.headers); + + // 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); + } + + this.pipe(request); + if (cb) { + var onResponse; + + var callback = function (error, responce) { + request.removeListener('error', callback); + request.removeListener('response', onResponse); + + return cb.call(this, error, responce); + }; + + onResponse = callback.bind(this, null); + + request.on('error', callback); + request.on('response', onResponse); + } + }.bind(this)); + + return request; +}; + +FormData.prototype._error = function(err) { + if (!this.error) { + this.error = err; + this.pause(); + this.emit('error', err); + } +}; + +FormData.prototype.toString = function () { + return '[object FormData]'; +}; + + +/***/ }), + +/***/ 7142: +/***/ ((module) => { + +// populates missing values +module.exports = function(dst, src) { + + Object.keys(src).forEach(function(prop) + { + dst[prop] = dst[prop] || src[prop]; + }); + + return dst; +}; + + +/***/ }), + +/***/ 2540: +/***/ ((module) => { + +"use strict"; + + +/** @class BitmapImage */ + +class BitmapImage { + + /** + * BitmapImage is a class that hold an RGBA (red, green, blue, alpha) representation of an image. It's shape is borrowed from the Jimp package to make it easy to transfer GIF image frames into Jimp and Jimp images into GIF image frames. Each instance has a `bitmap` property having the following properties: + * + * Property | Description + * --- | --- + * bitmap.width | width of image in pixels + * bitmap.height | height of image in pixels + * bitmap.data | a Buffer whose every four bytes represents a pixel, each sequential byte of a pixel corresponding to the red, green, blue, and alpha values of the pixel + * + * Its constructor supports the following signatures: + * + * * new BitmapImage(bitmap: { width: number, height: number, data: Buffer }) + * * new BitmapImage(bitmapImage: BitmapImage) + * * new BitmapImage(width: number, height: number, buffer: Buffer) + * * new BitmapImage(width: number, height: number, backgroundRGBA?: number) + * + * When a `BitmapImage` is provided, the constructed `BitmapImage` is a deep clone of the provided one, so that each image's pixel data can subsequently be modified without affecting each other. + * + * `backgroundRGBA` is an optional parameter representing a pixel as a single number. In hex, the number is as follows: 0xRRGGBBAA, where RR is the red byte, GG the green byte, BB, the blue byte, and AA the alpha value. An AA of 0x00 is considered transparent, and all non-zero AA values are treated as opaque. + */ + + constructor(...args) { + // don't confirm the number of args, because a subclass may have + // additional args and pass them all to the superclass + if (args.length === 0) { + throw new Error("constructor requires parameters"); + } + const firstArg = args[0]; + if (firstArg !== null && typeof firstArg === 'object') { + if (firstArg instanceof BitmapImage) { + // copy a provided BitmapImage + const sourceBitmap = firstArg.bitmap; + this.bitmap = { + width: sourceBitmap.width, + height: sourceBitmap.height, + data: new Buffer(sourceBitmap.width * sourceBitmap.height * 4) + }; + sourceBitmap.data.copy(this.bitmap.data); + } + else if (firstArg.width && firstArg.height && firstArg.data) { + // share a provided bitmap + this.bitmap = firstArg; + } + else { + throw new Error("unrecognized constructor parameters"); + } + } + else if (typeof firstArg === 'number' && typeof args[1] === 'number') + { + const width = firstArg; + const height = args[1]; + const thirdArg = args[2]; + this.bitmap = { width, height }; + + if (Buffer.isBuffer(thirdArg)) { + this.bitmap.data = thirdArg; + } + else { + this.bitmap.data = new Buffer(width * height * 4); + if (typeof thirdArg === 'number') { + this.fillRGBA(thirdArg); + } + } + } + else { + throw new Error("unrecognized constructor parameters"); + } + } + + /** + * Copy a square portion of this image into another image. + * + * @param {BitmapImage} toImage Image into which to copy the square + * @param {number} toX x-coord in toImage of upper-left corner of receiving square + * @param {number} toY y-coord in toImage of upper-left corner of receiving square + * @param {number} fromX x-coord in this image of upper-left corner of source square + * @param {number} fromY y-coord in this image of upper-left corner of source square + * @return {BitmapImage} The present image to allow for chaining. + */ + + blit(toImage, toX, toY, fromX, fromY, fromWidth, fromHeight) { + if (fromX + fromWidth > this.bitmap.width) { + throw new Error("copy exceeds width of source bitmap"); + } + if (toX + fromWidth > toImage.bitmap.width) { + throw new Error("copy exceeds width of target bitmap"); + } + if (fromY + fromHeight > this.bitmap.height) { + throw new Error("copy exceeds height of source bitmap"); + } + if (toY + fromHeight > toImage.bitmap.height) { + throw new Erro("copy exceeds height of target bitmap"); + } + + const sourceBuf = this.bitmap.data; + const targetBuf = toImage.bitmap.data; + const sourceByteWidth = this.bitmap.width * 4; + const targetByteWidth = toImage.bitmap.width * 4; + const copyByteWidth = fromWidth * 4; + let si = fromY * sourceByteWidth + fromX * 4; + let ti = toY * targetByteWidth + toX * 4; + + while (--fromHeight >= 0) { + sourceBuf.copy(targetBuf, ti, si, si + copyByteWidth); + si += sourceByteWidth; + ti += targetByteWidth; + } + return this; + } + + /** + * Fills the image with a single color. + * + * @param {number} rgba Color with which to fill image, expressed as a singlenumber in the form 0xRRGGBBAA, where AA is 0x00 for transparent and any other value for opaque. + * @return {BitmapImage} The present image to allow for chaining. + */ + + fillRGBA(rgba) { + const buf = this.bitmap.data; + const bufByteWidth = this.bitmap.height * 4; + + let bi = 0; + while (bi < bufByteWidth) { + buf.writeUInt32BE(rgba, bi); + bi += 4; + } + while (bi < buf.length) { + buf.copy(buf, bi, 0, bufByteWidth); + bi += bufByteWidth; + } + return this; + } + + /** + * Gets the RGBA number of the pixel at the given coordinate in the form 0xRRGGBBAA, where AA is the alpha value, with alpha 0x00 encoding to transparency in GIFs. + * + * @param {number} x x-coord of pixel + * @param {number} y y-coord of pixel + * @return {number} RGBA of pixel in 0xRRGGBBAA form + */ + + getRGBA(x, y) { + const bi = (y * this.bitmap.width + x) * 4; + return this.bitmap.data.readUInt32BE(bi); + } + + /** + * Gets a set of all RGBA colors found within the image. + * + * @return {Set} Set of all RGBA colors that the image contains. + */ + + getRGBASet() { + const rgbaSet = new Set(); + const buf = this.bitmap.data; + for (let bi = 0; bi < buf.length; bi += 4) { + rgbaSet.add(buf.readUInt32BE(bi, true)); + } + return rgbaSet; + } + + /** + * Converts the image to greyscale using inferred Adobe metrics. + * + * @return {BitmapImage} The present image to allow for chaining. + */ + + greyscale() { + const buf = this.bitmap.data; + this.scan(0, 0, this.bitmap.width, this.bitmap.height, (x, y, idx) => { + const grey = Math.round( + 0.299 * buf[idx] + + 0.587 * buf[idx + 1] + + 0.114 * buf[idx + 2] + ); + buf[idx] = grey; + buf[idx + 1] = grey; + buf[idx + 2] = grey; + }); + return this; + } + + /** + * Reframes the image as if placing a frame around the original image and replacing the original image with the newly framed image. When the new frame is strictly within the boundaries of the original image, this method crops the image. When any of the new boundaries exceed those of the original image, the `fillRGBA` must be provided to indicate the color with which to fill the extra space added to the image. + * + * @param {number} xOffset The x-coord offset of the upper-left pixel of the desired image relative to the present image. + * @param {number} yOffset The y-coord offset of the upper-left pixel of the desired image relative to the present image. + * @param {number} width The width of the new image after reframing + * @param {number} height The height of the new image after reframing + * @param {number} fillRGBA The color with which to fill space added to the image as a result of the reframing, in 0xRRGGBBAA format, where AA is 0x00 to indicate transparent and a non-zero value to indicate opaque. This parameter is only required when the reframing exceeds the original boundaries (i.e. does not simply perform a crop). + * @return {BitmapImage} The present image to allow for chaining. + */ + + reframe(xOffset, yOffset, width, height, fillRGBA) { + const cropX = (xOffset < 0 ? 0 : xOffset); + const cropY = (yOffset < 0 ? 0 : yOffset); + const cropWidth = (width + cropX > this.bitmap.width ? + this.bitmap.width - cropX : width); + const cropHeight = (height + cropY > this.bitmap.height ? + this.bitmap.height - cropY : height); + const newX = (xOffset < 0 ? -xOffset : 0); + const newY = (yOffset < 0 ? -yOffset : 0); + + let image; + if (fillRGBA === undefined) { + if (cropX !== xOffset || cropY != yOffset || + cropWidth !== width || cropHeight !== height) + { + throw new GifError(`fillRGBA required for this reframing`); + } + image = new BitmapImage(width, height); + } + else { + image = new BitmapImage(width, height, fillRGBA); + } + this.blit(image, newX, newY, cropX, cropY, cropWidth, cropHeight); + this.bitmap = image.bitmap; + return this; + } + + /** + * Scales the image size up by an integer factor. Each pixel of the original image becomes a square of the same color in the new image having a size of `factor` x `factor` pixels. + * + * @param {number} factor The factor by which to scale up the image. Must be an integer >= 1. + * @return {BitmapImage} The present image to allow for chaining. + */ + + scale(factor) { + if (factor === 1) { + return; + } + if (!Number.isInteger(factor) || factor < 1) { + throw new Error("the scale must be an integer >= 1"); + } + const sourceWidth = this.bitmap.width; + const sourceHeight = this.bitmap.height; + const destByteWidth = sourceWidth * factor * 4; + const sourceBuf = this.bitmap.data; + const destBuf = new Buffer(sourceHeight * destByteWidth * factor); + let sourceIndex = 0; + let priorDestRowIndex; + let destIndex = 0; + for (let y = 0; y < sourceHeight; ++y) { + priorDestRowIndex = destIndex; + for (let x = 0; x < sourceWidth; ++x) { + const color = sourceBuf.readUInt32BE(sourceIndex, true); + for (let cx = 0; cx < factor; ++cx) { + destBuf.writeUInt32BE(color, destIndex); + destIndex += 4; + } + sourceIndex += 4; + } + for (let cy = 1; cy < factor; ++cy) { + destBuf.copy(destBuf, destIndex, priorDestRowIndex, destIndex); + destIndex += destByteWidth; + priorDestRowIndex += destByteWidth; + } + } + this.bitmap = { + width: sourceWidth * factor, + height: sourceHeight * factor, + data: destBuf + }; + return this; + } + + /** + * Scans all coordinates of the image, handing each in turn to the provided handler function. + * + * @param {function} scanHandler A function(x: number, y: number, bi: number) to be called for each pixel of the image with that pixel's x-coord, y-coord, and index into the `data` buffer. The function accesses the pixel at this coordinate by accessing the `this.data` at index `bi`. + * @see scanAllIndexes + */ + + scanAllCoords(scanHandler) { + const width = this.bitmap.width; + const bufferLength = this.bitmap.data.length; + let x = 0; + let y = 0; + + for (let bi = 0; bi < bufferLength; bi += 4) { + scanHandler(x, y, bi); + if (++x === width) { + x = 0; + ++y; + } + } + } + + /** + * Scans all pixels of the image, handing the index of each in turn to the provided handler function. Runs a bit faster than `scanAllCoords()`, should the handler not need pixel coordinates. + * + * @param {function} scanHandler A function(bi: number) to be called for each pixel of the image with that pixel's index into the `data` buffer. The pixels is found at index 'bi' within `this.data`. + * @see scanAllCoords + */ + + scanAllIndexes(scanHandler) { + const bufferLength = this.bitmap.data.length; + for (let bi = 0; bi < bufferLength; bi += 4) { + scanHandler(bi); + } + } +} + +module.exports = BitmapImage; + + +/***/ }), + +/***/ 4345: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +/** @class Gif */ + +class Gif { + + // width - width of GIF in pixels + // height - height of GIF in pixels + // loops - 0 = unending; (n > 0) = iterate n times + // usesTransparency - whether any frames have transparent pixels + // colorScope - scope of color tables in GIF + // frames - array of frames + // buffer - GIF-formatted data + + /** + * Gif is a class representing an encoded GIF. It is intended to be a read-only representation of a byte-encoded GIF. Only encoders and decoders should be creating instances of this class. + * + * Property | Description + * --- | --- + * width | width of the GIF at its widest + * height | height of the GIF at its highest + * loops | the number of times the GIF should loop before stopping; 0 => loop indefinately + * usesTransparency | boolean indicating whether at least one frame contains at least one transparent pixel + * colorScope | the scope of the color tables as encoded within the GIF; either Gif.GlobalColorsOnly (== 1) or Gif.LocalColorsOnly (== 2). + * frames | a array of GifFrame instances, one for each frame of the GIF + * buffer | a Buffer holding the encoding's byte data + * + * Its constructor should only ever be called by the GIF encoder or decoder. + * + * @param {Buffer} buffer A Buffer containing the encoded bytes + * @param {GifFrame[]} frames Array of frames found in the encoding + * @param {object} spec Properties of the encoding as listed above + */ + + constructor(buffer, frames, spec) { + this.width = spec.width; + this.height = spec.height; + this.loops = spec.loops; + this.usesTransparency = spec.usesTransparency; + this.colorScope = spec.colorScope; + this.frames = frames; + this.buffer = buffer; + } +} + +Gif.GlobalColorsPreferred = 0; +Gif.GlobalColorsOnly = 1; +Gif.LocalColorsOnly = 2; + +/** @class GifError */ + +class GifError extends Error { + + /** + * GifError is a class representing a GIF-related error + * + * @param {string|Error} messageOrError + */ + + constructor(messageOrError) { + super(messageOrError); + if (messageOrError instanceof Error) { + this.stack = 'Gif' + messageOrError.stack; + } + } +} + +exports.Gif = Gif; +exports.GifError = GifError; + + +/***/ }), + +/***/ 1445: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +const Omggif = __nccwpck_require__(9717); +const { Gif, GifError } = __nccwpck_require__(4345); + +// allow circular dependency with GifUtil +function GifUtil() { + const data = __nccwpck_require__(4511); + + GifUtil = function () { + return data; + }; + + return data; +} + +const { GifFrame } = __nccwpck_require__(1756); + +const PER_GIF_OVERHEAD = 200; // these are guesses at upper limits +const PER_FRAME_OVERHEAD = 100; + +// Note: I experimented with accepting a global color table when encoding and returning the global color table when decoding. Doing this properly greatly increased the complexity of the code and the amount of clock cycles required. The main issue is that each frame can specify any color of the global color table to be transparent within the frame, while this GIF library strives to hide GIF formatting details from its clients. E.g. it's possible to have 256 colors in the global color table and different transparencies in each frame, requiring clients to either provide per-frame transparency indexes, or for arcane reasons that won't be apparent to client developers, encode some GIFs with local color tables that previously decoded with global tables. + +/** @class GifCodec */ + +class GifCodec +{ + // _transparentRGBA - RGB given to transparent pixels (alpha=0) on decode; defaults to null indicating 0x000000, which is fastest + + /** + * GifCodec is a class that both encodes and decodes GIFs. It implements both the `encode()` method expected of an encoder and the `decode()` method expected of a decoder, and it wraps the `omggif` GIF encoder/decoder package. GifCodec serves as this library's default encoder and decoder, but it's possible to wrap other GIF encoders and decoders for use by `gifwrap` as well. GifCodec will not encode GIFs with interlacing. + * + * Instances of this class are stateless and can be shared across multiple encodings and decodings. + * + * Its constructor takes one option argument: + * + * @param {object} options Optionally takes an objection whose only possible property is `transparentRGB`. Images are internally represented in RGBA format, where A is the alpha value of a pixel. When `transparentRGB` is provided, this RGB value (excluding alpha) is assigned to transparent pixels, which are also given alpha value 0x00. (All opaque pixels are given alpha value 0xFF). The RGB color of transparent pixels shouldn't matter for most applications. Defaults to 0x000000. + */ + + constructor(options = {}) { + this._transparentRGB = null; // 0x000000 + if (typeof options.transparentRGB === 'number' && + options.transparentRGB !== 0) + { + this._transparentRGBA = options.transparentRGB * 256; + } + this._testInitialBufferSize = 0; // assume no buffer scaling test + } + + /** + * Decodes a GIF from a Buffer to yield an instance of Gif. Transparent pixels of the GIF are given alpha values of 0x00, and opaque pixels are given alpha values of 0xFF. The RGB values of transparent pixels default to 0x000000 but can be overridden by the constructor's `transparentRGB` option. + * + * @param {Buffer} buffer Bytes of an encoded GIF to decode. + * @return {Promise} A Promise that resolves to an instance of the Gif class, representing the encoded GIF. + * @throws {GifError} Error upon encountered an encoding-related problem with a GIF, so that the caller can distinguish between software errors and problems with GIFs. + */ + + decodeGif(buffer) { + try { + let reader; + try { + reader = new Omggif.GifReader(buffer); + } + catch (err) { + throw new GifError(err); + } + const frameCount = reader.numFrames(); + const frames = []; + const spec = { + width: reader.width, + height: reader.height, + loops: reader.loopCount() + }; + + spec.usesTransparency = false; + for (let i = 0; i < frameCount; ++i) { + const frameInfo = + this._decodeFrame(reader, i, spec.usesTransparency); + frames.push(frameInfo.frame); + if (frameInfo.usesTransparency) { + spec.usesTransparency = true; + } + } + return Promise.resolve(new Gif(buffer, frames, spec)); + } + catch (err) { + return Promise.reject(err); + } + } + + /** + * Encodes a GIF from provided frames. Each pixel having an alpha value of 0x00 renders as transparent within the encoding, while all pixels of non-zero alpha value render as opaque. + * + * @param {GifFrame[]} frames Array of frames to encode + * @param {object} spec An optional object that may provide values for `loops` and `colorScope`, as defined for the Gif class. However, `colorSpace` may also take the value Gif.GlobalColorsPreferred (== 0) to indicate that the encoder should attempt to create only a global color table. `loop` defaults to 0, looping indefinitely, and `colorScope` defaults to Gif.GlobalColorsPreferred. + * @return {Promise} A Promise that resolves to an instance of the Gif class, representing the encoded GIF. + * @throws {GifError} Error upon encountered an encoding-related problem with a GIF, so that the caller can distinguish between software errors and problems with GIFs. + */ + + encodeGif(frames, spec = {}) { + try { + if (frames === null || frames.length === 0) { + throw new GifError("there are no frames"); + } + const dims = GifUtil().getMaxDimensions(frames); + + spec = Object.assign({}, spec); // don't munge caller's spec + spec.width = dims.maxWidth; + spec.height = dims.maxHeight; + spec.loops = spec.loops || 0; + spec.colorScope = spec.colorScope || Gif.GlobalColorsPreferred; + + return Promise.resolve(this._encodeGif(frames, spec)); + } + catch (err) { + return Promise.reject(err); + } + } + + _decodeFrame(reader, frameIndex, alreadyUsedTransparency) { + let info, buffer; + try { + info = reader.frameInfo(frameIndex); + buffer = new Buffer(reader.width * reader.height * 4); + reader.decodeAndBlitFrameRGBA(frameIndex, buffer); + if (info.width !== reader.width || info.height !== reader.height) { + if (info.y) { + // skip unused rows + buffer = buffer.slice(info.y * reader.width * 4); + } + if (reader.width > info.width) { + // skip scanstride + for (let ii = 0; ii < info.height; ++ii) { + buffer.copy(buffer, ii * info.width * 4, + (info.x + ii * reader.width) * 4, + (info.x + ii * reader.width) * 4 + info.width * 4); + } + } + // trim buffer to size + buffer = buffer.slice(0, info.width * info.height * 4); + } + } + catch (err) { + throw new GifError(err); + } + + let usesTransparency = false; + if (this._transparentRGBA === null) { + if (!alreadyUsedTransparency) { + for (let i = 3; i < buffer.length; i += 4) { + if (buffer[i] === 0) { + usesTransparency = true; + i = buffer.length; + } + } + } + } + else { + for (let i = 3; i < buffer.length; i += 4) { + if (buffer[i] === 0) { + buffer.writeUInt32BE(this._transparentRGBA, i - 3); + usesTransparency = true; // GIF might encode unused index + } + } + } + + const frame = new GifFrame(info.width, info.height, buffer, { + xOffset: info.x, + yOffset: info.y, + disposalMethod: info.disposal, + interlaced: info.interlaced, + delayCentisecs: info.delay + }); + return { frame, usesTransparency }; + } + + _encodeGif(frames, spec) { + let colorInfo; + if (spec.colorScope === Gif.LocalColorsOnly) { + colorInfo = GifUtil().getColorInfo(frames, 0); + } + else { + colorInfo = GifUtil().getColorInfo(frames, 256); + if (!colorInfo.colors) { // if global palette impossible + if (spec.colorScope === Gif.GlobalColorsOnly) { + throw new GifError( + "Too many color indexes for global color table"); + } + spec.colorScope = Gif.LocalColorsOnly + } + } + spec.usesTransparency = colorInfo.usesTransparency; + + const localPalettes = colorInfo.palettes; + if (spec.colorScope === Gif.LocalColorsOnly) { + const localSizeEst = 2000; //this._getSizeEstimateLocal(localPalettes, frames); + return _encodeLocal(frames, spec, localSizeEst, localPalettes); + } + + const globalSizeEst = 2000; //this._getSizeEstimateGlobal(colorInfo, frames); + return _encodeGlobal(frames, spec, globalSizeEst, colorInfo); + } + + _getSizeEstimateGlobal(globalPalette, frames) { + if (this._testInitialBufferSize > 0) { + return this._testInitialBufferSize; + } + let sizeEst = PER_GIF_OVERHEAD + 3*256 /* max palette size*/; + const pixelBitWidth = _getPixelBitWidth(globalPalette); + frames.forEach(frame => { + sizeEst += _getFrameSizeEst(frame, pixelBitWidth); + }); + return sizeEst; // should be the upper limit + } + + _getSizeEstimateLocal(palettes, frames) { + if (this._testInitialBufferSize > 0) { + return this._testInitialBufferSize; + } + let sizeEst = PER_GIF_OVERHEAD; + for (let i = 0; i < frames.length; ++i ) { + const palette = palettes[i]; + const pixelBitWidth = _getPixelBitWidth(palette); + sizeEst += _getFrameSizeEst(frames[i], pixelBitWidth); + } + return sizeEst; // should be the upper limit + } +} +exports.GifCodec = GifCodec; + +function _colorLookupLinear(colors, color) { + const index = colors.indexOf(color); + return (index === -1 ? null : index); +} + +function _colorLookupBinary(colors, color) { + // adapted from https://stackoverflow.com/a/10264318/650894 + var lo = 0, hi = colors.length - 1, mid; + while (lo <= hi) { + mid = Math.floor((lo + hi)/2); + if (colors[mid] > color) + hi = mid - 1; + else if (colors[mid] < color) + lo = mid + 1; + else + return mid; + } + return null; +} + +function _encodeGlobal(frames, spec, bufferSizeEst, globalPalette) { + // would be inefficient for frames to lookup colors in extended palette + const extendedGlobalPalette = { + colors: globalPalette.colors.slice(), + usesTransparency: globalPalette.usesTransparency + }; + _extendPaletteToPowerOf2(extendedGlobalPalette); + const options = { + palette: extendedGlobalPalette.colors, + loop: spec.loops + }; + let buffer = new Buffer(bufferSizeEst); + let gifWriter; + try { + gifWriter = new Omggif.GifWriter(buffer, spec.width, spec.height, + options); + } + catch (err) { + throw new GifError(err); + } + for (let i = 0; i < frames.length; ++i) { + buffer = _writeFrame(gifWriter, i, frames[i], globalPalette, false); + } + return new Gif(buffer.slice(0, gifWriter.end()), frames, spec); +} + +function _encodeLocal(frames, spec, bufferSizeEst, localPalettes) { + const options = { + loop: spec.loops + }; + let buffer = new Buffer(bufferSizeEst); + let gifWriter; + try { + gifWriter = new Omggif.GifWriter(buffer, spec.width, spec.height, + options); + } + catch (err) { + throw new GifError(err); + } + for (let i = 0; i < frames.length; ++i) { + buffer = _writeFrame(gifWriter, i, frames[i], localPalettes[i], true); + } + return new Gif(buffer.slice(0, gifWriter.end()), frames, spec); +} + +function _extendPaletteToPowerOf2(palette) { + const colors = palette.colors; + if (palette.usesTransparency) { + colors.push(0); + } + const colorCount = colors.length; + let powerOf2 = 2; + while (colorCount > powerOf2) { + powerOf2 <<= 1; + } + colors.length = powerOf2; + colors.fill(0, colorCount); +} + +function _getFrameSizeEst(frame, pixelBitWidth) { + let byteLength = frame.bitmap.width * frame.bitmap.height; + byteLength = Math.ceil(byteLength * pixelBitWidth / 8); + byteLength += Math.ceil(byteLength / 255); // add block size bytes + // assume maximum palete size because it might get extended for power of 2 + return (PER_FRAME_OVERHEAD + byteLength + 3 * 256 /* largest palette */); +} + +function _getIndexedImage(frameIndex, frame, palette) { + const colors = palette.colors; + const colorToIndexFunc = (colors.length <= 8 ? // guess at the break-even + _colorLookupLinear : _colorLookupBinary); + const colorBuffer = frame.bitmap.data; + const indexBuffer = new Buffer(colorBuffer.length/4); + let transparentIndex = colors.length; + let i = 0, j = 0; + + while (i < colorBuffer.length) { + if (colorBuffer[i + 3] !== 0) { + const color = (colorBuffer.readUInt32BE(i, true) >> 8) & 0xFFFFFF; + // caller guarantees that the color will be in the palette + indexBuffer[j] = colorToIndexFunc(colors, color); + } + else { + indexBuffer[j] = transparentIndex; + } + i += 4; // skip alpha + ++j; + } + + if (palette.usesTransparency) { + if (transparentIndex === 256) { + throw new GifError(`Frame ${frameIndex} already has 256 colors` + + `and so can't use transparency`); + } + } + else { + transparentIndex = null; + } + + return { buffer: indexBuffer, transparentIndex }; +} + +function _getPixelBitWidth(palette) { + let indexCount = palette.indexCount; + let pixelBitWidth = 0; + --indexCount; // start at maximum index + while (indexCount) { + ++pixelBitWidth; + indexCount >>= 1; + } + return (pixelBitWidth > 0 ? pixelBitWidth : 1); +} + +function _writeFrame(gifWriter, frameIndex, frame, palette, isLocalPalette) { + if (frame.interlaced) { + throw new GifError("writing interlaced GIFs is not supported"); + } + const frameInfo = _getIndexedImage(frameIndex, frame, palette); + const options = { + delay: frame.delayCentisecs, + disposal: frame.disposalMethod, + transparent: frameInfo.transparentIndex + }; + if (isLocalPalette) { + _extendPaletteToPowerOf2(palette); // ok 'cause palette never used again + options.palette = palette.colors; + } + try { + let buffer = gifWriter.getOutputBuffer(); + let startOfFrame = gifWriter.getOutputBufferPosition(); + let endOfFrame; + let tryAgain = true; + + while (tryAgain) { + endOfFrame = gifWriter.addFrame(frame.xOffset, frame.yOffset, + frame.bitmap.width, frame.bitmap.height, frameInfo.buffer, options); + tryAgain = false; + if (endOfFrame >= buffer.length - 1) { + const biggerBuffer = new Buffer(buffer.length * 1.5); + buffer.copy(biggerBuffer); + gifWriter.setOutputBuffer(biggerBuffer); + gifWriter.setOutputBufferPosition(startOfFrame); + buffer = biggerBuffer; + tryAgain = true; + } + } + return buffer; + } + catch (err) { + throw new GifError(err); + } +} + + +/***/ }), + +/***/ 1756: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +const BitmapImage = __nccwpck_require__(2540); +const { GifError } = __nccwpck_require__(4345); + +/** @class GifFrame */ + +class GifFrame extends BitmapImage { + + // xOffset - x offset of bitmap on GIF (defaults to 0) + // yOffset - y offset of bitmap on GIF (defaults to 0) + // disposalMethod - pixel disposal method when handling partial images + // delayCentisecs - duration of frame in hundredths of a second + // interlaced - whether the image is interlaced (defaults to false) + + /** + * GifFrame is a class representing an image frame of a GIF. GIFs contain one or more instances of GifFrame. + * + * Property | Description + * --- | --- + * xOffset | x-coord of position within GIF at which to render the image (defaults to 0) + * yOffset | y-coord of position within GIF at which to render the image (defaults to 0) + * disposalMethod | GIF disposal method; only relevant when the frames aren't all the same size (defaults to 2, disposing to background color) + * delayCentisecs | duration of the frame in hundreths of a second + * interlaced | boolean indicating whether the frame renders interlaced + * + * Its constructor supports the following signatures: + * + * * new GifFrame(bitmap: {width: number, height: number, data: Buffer}, options?) + * * new GifFrame(bitmapImage: BitmapImage, options?) + * * new GifFrame(width: number, height: number, buffer: Buffer, options?) + * * new GifFrame(width: number, height: number, backgroundRGBA?: number, options?) + * * new GifFrame(frame: GifFrame) + * + * See the base class BitmapImage for a discussion of all parameters but `options` and `frame`. `options` is an optional argument providing initial values for the above-listed GifFrame properties. Each property within option is itself optional. + * + * Provide a `frame` to the constructor to create a clone of the provided frame. The new frame includes a copy of the provided frame's pixel data so that each can subsequently be modified without affecting each other. + */ + + constructor(...args) { + super(...args); + if (args[0] instanceof GifFrame) { + // copy a provided GifFrame + const source = args[0]; + this.xOffset = source.xOffset; + this.yOffset = source.yOffset; + this.disposalMethod = source.disposalMethod; + this.delayCentisecs = source.delayCentisecs; + this.interlaced = source.interlaced; + } + else { + const lastArg = args[args.length - 1]; + let options = {}; + if (typeof lastArg === 'object' && !(lastArg instanceof BitmapImage)) { + options = lastArg; + } + this.xOffset = options.xOffset || 0; + this.yOffset = options.yOffset || 0; + this.disposalMethod = (options.disposalMethod !== undefined ? + options.disposalMethod : GifFrame.DisposeToBackgroundColor); + this.delayCentisecs = options.delayCentisecs || 8; + this.interlaced = options.interlaced || false; + } + } + + /** + * Get a summary of the colors found within the frame. The return value is an object of the following form: + * + * Property | Description + * --- | --- + * colors | An array of all the opaque colors found within the frame. Each color is given as an RGB number of the form 0xRRGGBB. The array is sorted by increasing number. Will be an empty array when the image is completely transparent. + * usesTransparency | boolean indicating whether there are any transparent pixels within the frame. A pixel is considered transparent if its alpha value is 0x00. + * indexCount | The number of color indexes required to represent this palette of colors. It is equal to the number of opaque colors plus one if the image includes transparency. + * + * @return {object} An object representing a color palette as described above. + */ + + getPalette() { + // returns with colors sorted low to high + const colorSet = new Set(); + const buf = this.bitmap.data; + let i = 0; + let usesTransparency = false; + while (i < buf.length) { + if (buf[i + 3] === 0) { + usesTransparency = true; + } + else { + // can eliminate the bitshift by starting one byte prior + const color = (buf.readUInt32BE(i, true) >> 8) & 0xFFFFFF; + colorSet.add(color); + } + i += 4; // skip alpha + } + const colors = new Array(colorSet.size); + const iter = colorSet.values(); + for (i = 0; i < colors.length; ++i) { + colors[i] = iter.next().value; + } + colors.sort((a, b) => (a - b)); + let indexCount = colors.length; + if (usesTransparency) { + ++indexCount; + } + return { colors, usesTransparency, indexCount }; + } +} + +GifFrame.DisposeToAnything = 0; +GifFrame.DisposeNothing = 1; +GifFrame.DisposeToBackgroundColor = 2; +GifFrame.DisposeToPrevious = 3; + +exports.GifFrame = GifFrame; + + +/***/ }), + +/***/ 4511: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +/** @namespace GifUtil */ + +const fs = __nccwpck_require__(7147); +const ImageQ = __nccwpck_require__(8622); + +const BitmapImage = __nccwpck_require__(2540); +const { GifFrame } = __nccwpck_require__(1756); +const { GifError } = __nccwpck_require__(4345); +const { GifCodec } = __nccwpck_require__(1445); + +const INVALID_SUFFIXES = ['.jpg', '.jpeg', '.png', '.bmp']; + +const defaultCodec = new GifCodec(); + +/** + * cloneFrames() clones provided frames. It's a utility method for cloning an entire array of frames at once. + * + * @function cloneFrames + * @memberof GifUtil + * @param {GifFrame[]} frames An array of GifFrame instances to clone + * @return {GifFrame[]} An array of GifFrame clones of the provided frames. + */ + +exports.cloneFrames = function (frames) { + let clones = []; + frames.forEach(frame => { + + clones.push(new GifFrame(frame)); + }); + return clones; +} + +/** + * getColorInfo() gets information about the colors used in the provided frames. The method is able to return an array of all colors found across all frames. + * + * `maxGlobalIndex` controls whether the computation short-circuits to avoid doing work that the caller doesn't need. The method only returns `colors` and `indexCount` for the colors across all frames when the number of indexes required to store the colors and transparency in a GIF (which is the value of `indexCount`) is less than or equal to `maxGlobalIndex`. Such short-circuiting is useful when the caller just needs to determine whether any frame includes transparency. + * + * @function getColorInfo + * @memberof GifUtil + * @param {GifFrame[]} frames Frames to examine for color and transparency. + * @param {number} maxGlobalIndex Maximum number of color indexes (including one for transparency) allowed among the returned compilation of colors. `colors` and `indexCount` are not returned if the number of color indexes required to accommodate all frames exceeds this number. Returns `colors` and `indexCount` by default. + * @returns {object} Object containing at least `palettes` and `usesTransparency`. `palettes` is an array of all the palettes returned by GifFrame#getPalette(). `usesTransparency` indicates whether at least one frame uses transparency. If `maxGlobalIndex` is not exceeded, the object also contains `colors`, an array of all colors (RGB) found across all palettes, sorted by increasing value, and `indexCount` indicating the number of indexes required to store the colors and the transparency in a GIF. + * @throws {GifError} When any frame requires more than 256 color indexes. + */ + +exports.getColorInfo = function (frames, maxGlobalIndex) { + let usesTransparency = false; + const palettes = []; + for (let i = 0; i < frames.length; ++i) { + let palette = frames[i].getPalette(); + if (palette.usesTransparency) { + usesTransparency = true; + } + if (palette.indexCount > 256) { + throw new GifError(`Frame ${i} uses more than 256 color indexes`); + } + palettes.push(palette); + } + if (maxGlobalIndex === 0) { + return { usesTransparency, palettes }; + } + + const globalColorSet = new Set(); + palettes.forEach(palette => { + + palette.colors.forEach(color => { + + globalColorSet.add(color); + }); + }); + let indexCount = globalColorSet.size; + if (usesTransparency) { + // odd that GIF requires a color table entry at transparent index + ++indexCount; + } + if (maxGlobalIndex && indexCount > maxGlobalIndex) { + return { usesTransparency, palettes }; + } + + const colors = new Array(globalColorSet.size); + const iter = globalColorSet.values(); + for (let i = 0; i < colors.length; ++i) { + colors[i] = iter.next().value; + } + colors.sort((a, b) => (a - b)); + return { colors, indexCount, usesTransparency, palettes }; +}; + +/** + * copyAsJimp() returns a Jimp that contains a copy of the provided bitmap image (which may be either a BitmapImage or a GifFrame). Modifying the Jimp does not affect the provided bitmap image. This method serves as a macro for simplifying working with Jimp. + * + * @function copyAsJimp + * @memberof GifUtil + * @param {object} Reference to the Jimp package, keeping this library from being dependent on Jimp. + * @param {bitmapImageToCopy} Instance of BitmapImage (may be a GifUtil) with which to source the Jimp. + * @return {object} An new instance of Jimp containing a copy of the image in bitmapImageToCopy. + */ + +exports.copyAsJimp = function (jimp, bitmapImageToCopy) { + return exports.shareAsJimp(jimp, new BitmapImage(bitmapImageToCopy)); +}; + +/** + * getMaxDimensions() returns the pixel width and height required to accommodate all of the provided frames, according to the offsets and dimensions of each frame. + * + * @function getMaxDimensions + * @memberof GifUtil + * @param {GifFrame[]} frames Frames to measure for their aggregate maximum dimensions. + * @return {object} An object of the form {maxWidth, maxHeight} indicating the maximum width and height required to accommodate all frames. + */ + +exports.getMaxDimensions = function (frames) { + let maxWidth = 0, maxHeight = 0; + frames.forEach(frame => { + const width = frame.xOffset + frame.bitmap.width; + if (width > maxWidth) { + maxWidth = width; + } + const height = frame.yOffset + frame.bitmap.height; + if (height > maxHeight) { + maxHeight = height; + } + }); + return { maxWidth, maxHeight }; +}; + +/** + * Quantizes colors so that there are at most a given number of color indexes (including transparency) across all provided images. Uses an algorithm by Anthony Dekker. + * + * The method treats different RGBA combinations as different colors, so if the frame has multiple alpha values or multiple RGB values for an alpha value, the caller may first want to normalize them by converting all transparent pixels to the same RGBA values. + * + * The method may increase the number of colors if there are fewer than the provided maximum. + * + * @function quantizeDekker + * @memberof GifUtil + * @param {BitmapImage|BitmapImage[]} imageOrImages Image or array of images (such as GifFrame instances) to be color-quantized. Quantizing across multiple images ensures color consistency from frame to frame. + * @param {number} maxColorIndexes The maximum number of color indexes that will exist in the palette after completing quantization. Defaults to 256. + * @param {object} dither (optional) An object configuring the dithering to apply. The properties are as followings, imported from the [`image-q` package](https://github.com/ibezkrovnyi/image-quantization) without explanation: { `ditherAlgorithm`: One of 'FloydSteinberg', 'FalseFloydSteinberg', 'Stucki', 'Atkinson', 'Jarvis', 'Burkes', 'Sierra', 'TwoSierra', 'SierraLite'; `minimumColorDistanceToDither`: (optional) A number defaulting to 0; `serpentine`: (optional) A boolean defaulting to true; `calculateErrorLikeGIMP`: (optional) A boolean defaulting to false. } + */ + +exports.quantizeDekker = function (imageOrImages, maxColorIndexes, dither) { + maxColorIndexes = maxColorIndexes || 256; + _quantize(imageOrImages, 'NeuQuantFloat', maxColorIndexes, 0, dither); +} + +/** + * Quantizes colors so that there are at most a given number of color indexes (including transparency) across all provided images. Uses an algorithm by Leon Sorokin. This quantization method differs from the other two by likely never increasing the number of colors, should there be fewer than the provided maximum. + * + * The method treats different RGBA combinations as different colors, so if the frame has multiple alpha values or multiple RGB values for an alpha value, the caller may first want to normalize them by converting all transparent pixels to the same RGBA values. + * + * @function quantizeSorokin + * @memberof GifUtil + * @param {BitmapImage|BitmapImage[]} imageOrImages Image or array of images (such as GifFrame instances) to be color-quantized. Quantizing across multiple images ensures color consistency from frame to frame. + * @param {number} maxColorIndexes The maximum number of color indexes that will exist in the palette after completing quantization. Defaults to 256. + * @param {string} histogram (optional) Histogram method: 'top-pop' for global top-population, 'min-pop' for minimum-population threshhold within subregions. Defaults to 'min-pop'. + * @param {object} dither (optional) An object configuring the dithering to apply, as explained for `quantizeDekker()`. + */ + +exports.quantizeSorokin = function (imageOrImages, maxColorIndexes, histogram, dither) { + maxColorIndexes = maxColorIndexes || 256; + histogram = histogram || 'min-pop'; + let histogramID; + switch (histogram) { + case 'min-pop': + histogramID = 2; + break; + + case 'top-pop': + histogramID = 1; + break + + default: + throw new Error(`Invalid quantizeSorokin histogram '${histogram}'`); + } + _quantize(imageOrImages, 'RGBQuant', maxColorIndexes, histogramID, dither); +} + +/** + * Quantizes colors so that there are at most a given number of color indexes (including transparency) across all provided images. Uses an algorithm by Xiaolin Wu. + * + * The method treats different RGBA combinations as different colors, so if the frame has multiple alpha values or multiple RGB values for an alpha value, the caller may first want to normalize them by converting all transparent pixels to the same RGBA values. + * + * The method may increase the number of colors if there are fewer than the provided maximum. + * + * @function quantizeWu + * @memberof GifUtil + * @param {BitmapImage|BitmapImage[]} imageOrImages Image or array of images (such as GifFrame instances) to be color-quantized. Quantizing across multiple images ensures color consistency from frame to frame. + * @param {number} maxColorIndexes The maximum number of color indexes that will exist in the palette after completing quantization. Defaults to 256. + * @param {number} significantBits (optional) This is the number of significant high bits in each RGB color channel. Takes integer values from 1 through 8. Higher values correspond to higher quality. Defaults to 5. + * @param {object} dither (optional) An object configuring the dithering to apply, as explained for `quantizeDekker()`. + */ + +exports.quantizeWu = function (imageOrImages, maxColorIndexes, significantBits, dither) { + maxColorIndexes = maxColorIndexes || 256; + significantBits = significantBits || 5; + if (significantBits < 1 || significantBits > 8) { + throw new Error("Invalid quantization quality"); + } + _quantize(imageOrImages, 'WuQuant', maxColorIndexes, significantBits, dither); +} + +/** + * read() decodes an encoded GIF, whether provided as a filename or as a byte buffer. + * + * @function read + * @memberof GifUtil + * @param {string|Buffer} source Source to decode. When a string, it's the GIF filename to load and parse. When a Buffer, it's an encoded GIF to parse. + * @param {object} decoder An optional GIF decoder object implementing the `decode` method of class GifCodec. When provided, the method decodes the GIF using this decoder. When not provided, the method uses GifCodec. + * @return {Promise} A Promise that resolves to an instance of the Gif class, representing the decoded GIF. + */ + +exports.read = function (source, decoder) { + decoder = decoder || defaultCodec; + if (Buffer.isBuffer(source)) { + return decoder.decodeGif(source); + } + return _readBinary(source) + .then(buffer => { + + return decoder.decodeGif(buffer); + }); +}; + +/** + * shareAsJimp() returns a Jimp that shares a bitmap with the provided bitmap image (which may be either a BitmapImage or a GifFrame). Modifying the image in either the Jimp or the BitmapImage affects the other objects. This method serves as a macro for simplifying working with Jimp. + * + * @function shareAsJimp + * @memberof GifUtil + * @param {object} Reference to the Jimp package, keeping this library from being dependent on Jimp. + * @param {bitmapImageToShare} Instance of BitmapImage (may be a GifUtil) with which to source the Jimp. + * @return {object} An new instance of Jimp that shares the image in bitmapImageToShare. + */ + +exports.shareAsJimp = function (jimp, bitmapImageToShare) { + const jimpImage = new jimp(bitmapImageToShare.bitmap.width, + bitmapImageToShare.bitmap.height, 0); + jimpImage.bitmap.data = bitmapImageToShare.bitmap.data; + return jimpImage; +}; + +/** + * write() encodes a GIF and saves it as a file. + * + * @function write + * @memberof GifUtil + * @param {string} path Filename to write GIF out as. Will overwrite an existing file. + * @param {GifFrame[]} frames Array of frames to be written into GIF. + * @param {object} spec An optional object that may provide values for `loops` and `colorScope`, as defined for the Gif class. However, `colorSpace` may also take the value Gif.GlobalColorsPreferred (== 0) to indicate that the encoder should attempt to create only a global color table. `loop` defaults to 0, looping indefinitely, and `colorScope` defaults to Gif.GlobalColorsPreferred. + * @param {object} encoder An optional GIF encoder object implementing the `encode` method of class GifCodec. When provided, the method encodes the GIF using this encoder. When not provided, the method uses GifCodec. + * @return {Promise} A Promise that resolves to an instance of the Gif class, representing the encoded GIF. + */ + +exports.write = function (path, frames, spec, encoder) { + encoder = encoder || defaultCodec; + const matches = path.match(/\.[a-zA-Z]+$/); // prevent accidents + if (matches !== null && + INVALID_SUFFIXES.includes(matches[0].toLowerCase())) + { + throw new Error(`GIF '${path}' has an unexpected suffix`); + } + + return encoder.encodeGif(frames, spec) + .then(gif => { + + return _writeBinary(path, gif.buffer) + .then(() => { + + return gif; + }); + }); +}; + +function _quantize(imageOrImages, method, maxColorIndexes, modifier, dither) { + const images = Array.isArray(imageOrImages) ? imageOrImages : [imageOrImages]; + const ditherAlgs = [ + 'FloydSteinberg', + 'FalseFloydSteinberg', + 'Stucki', + 'Atkinson', + 'Jarvis', + 'Burkes', + 'Sierra', + 'TwoSierra', + 'SierraLite' + ]; + + if (dither) { + if (ditherAlgs.indexOf(dither.ditherAlgorithm) < 0) { + throw new Error(`Invalid ditherAlgorithm '${dither.ditherAlgorithm}'`); + } + if (dither.serpentine === undefined) { + dither.serpentine = true; + } + if (dither.minimumColorDistanceToDither === undefined) { + dither.minimumColorDistanceToDither = 0; + } + if (dither.calculateErrorLikeGIMP === undefined) { + dither.calculateErrorLikeGIMP = false; + } + } + + const distCalculator = new ImageQ.distance.Euclidean(); + const quantizer = new ImageQ.palette[method](distCalculator, maxColorIndexes, modifier); + let imageMaker; + if (dither) { + imageMaker = new ImageQ.image.ErrorDiffusionArray( + distCalculator, + ImageQ.image.ErrorDiffusionArrayKernel[dither.ditherAlgorithm], + dither.serpentine, + dither.minimumColorDistanceToDither, + dither.calculateErrorLikeGIMP + ); + } + else { + imageMaker = new ImageQ.image.NearestColor(distCalculator); + } + + const inputContainers = []; + images.forEach(image => { + + const imageBuf = image.bitmap.data; + const inputBuf = new ArrayBuffer(imageBuf.length); + const inputArray = new Uint32Array(inputBuf); + for (let bi = 0, ai = 0; bi < imageBuf.length; bi += 4, ++ai) { + inputArray[ai] = imageBuf.readUInt32LE(bi, true); + } + const inputContainer = ImageQ.utils.PointContainer.fromUint32Array( + inputArray, image.bitmap.width, image.bitmap.height); + quantizer.sample(inputContainer); + inputContainers.push(inputContainer); + }); + + const limitedPalette = quantizer.quantizeSync(); + + for (let i = 0; i < images.length; ++i) { + const imageBuf = images[i].bitmap.data; + const outputContainer = imageMaker.quantizeSync(inputContainers[i], limitedPalette); + const outputArray = outputContainer.toUint32Array(); + for (let bi = 0, ai = 0; bi < imageBuf.length; bi += 4, ++ai) { + imageBuf.writeUInt32LE(outputArray[ai], bi); + } + } +} + +function _readBinary(path) { + // TBD: add support for URLs + return new Promise((resolve, reject) => { + + fs.readFile(path, (err, buffer) => { + + if (err) { + return reject(err); + } + return resolve(buffer); + }); + }); +} + +function _writeBinary(path, buffer) { + // TBD: add support for URLs + return new Promise((resolve, reject) => { + + fs.writeFile(path, buffer, err => { + + if (err) { + return reject(err); + } + return resolve(); + }); + }); +} + + +/***/ }), + +/***/ 7304: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const BitmapImage = __nccwpck_require__(2540); +const { Gif, GifError } = __nccwpck_require__(4345); +const { GifCodec } = __nccwpck_require__(1445); +const { GifFrame } = __nccwpck_require__(1756); +const GifUtil = __nccwpck_require__(4511); + +module.exports = { + BitmapImage, + Gif, + GifCodec, + GifFrame, + GifUtil, + GifError +}; + + +/***/ }), + +/***/ 1621: +/***/ ((module) => { + +"use strict"; + + +module.exports = (flag, argv = process.argv) => { + const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); + const position = argv.indexOf(prefix + flag); + const terminatorPosition = argv.indexOf('--'); + return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); +}; + + +/***/ }), + +/***/ 6296: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const fs = __nccwpck_require__(7147) +const path = __nccwpck_require__(1017) +const EE = (__nccwpck_require__(2361).EventEmitter) +const Minimatch = (__nccwpck_require__(276).Minimatch) + +class Walker extends EE { + constructor (opts) { + opts = opts || {} + super(opts) + // set to true if this.path is a symlink, whether follow is true or not + this.isSymbolicLink = opts.isSymbolicLink + this.path = opts.path || process.cwd() + this.basename = path.basename(this.path) + this.ignoreFiles = opts.ignoreFiles || ['.ignore'] + this.ignoreRules = {} + this.parent = opts.parent || null + this.includeEmpty = !!opts.includeEmpty + this.root = this.parent ? this.parent.root : this.path + this.follow = !!opts.follow + this.result = this.parent ? this.parent.result : new Set() + this.entries = null + this.sawError = false + } + + sort (a, b) { + return a.localeCompare(b, 'en') + } + + emit (ev, data) { + let ret = false + if (!(this.sawError && ev === 'error')) { + if (ev === 'error') { + this.sawError = true + } else if (ev === 'done' && !this.parent) { + data = Array.from(data) + .map(e => /^@/.test(e) ? `./${e}` : e).sort(this.sort) + this.result = data + } + + if (ev === 'error' && this.parent) { + ret = this.parent.emit('error', data) + } else { + ret = super.emit(ev, data) + } + } + return ret + } + + start () { + fs.readdir(this.path, (er, entries) => + er ? this.emit('error', er) : this.onReaddir(entries)) + return this + } + + isIgnoreFile (e) { + return e !== '.' && + e !== '..' && + this.ignoreFiles.indexOf(e) !== -1 + } + + onReaddir (entries) { + this.entries = entries + if (entries.length === 0) { + if (this.includeEmpty) { + this.result.add(this.path.slice(this.root.length + 1)) + } + this.emit('done', this.result) + } else { + const hasIg = this.entries.some(e => + this.isIgnoreFile(e)) + + if (hasIg) { + this.addIgnoreFiles() + } else { + this.filterEntries() + } + } + } + + addIgnoreFiles () { + const newIg = this.entries + .filter(e => this.isIgnoreFile(e)) + + let igCount = newIg.length + const then = _ => { + if (--igCount === 0) { + this.filterEntries() + } + } + + newIg.forEach(e => this.addIgnoreFile(e, then)) + } + + addIgnoreFile (file, then) { + const ig = path.resolve(this.path, file) + fs.readFile(ig, 'utf8', (er, data) => + er ? this.emit('error', er) : this.onReadIgnoreFile(file, data, then)) + } + + onReadIgnoreFile (file, data, then) { + const mmopt = { + matchBase: true, + dot: true, + flipNegate: true, + nocase: true, + } + const rules = data.split(/\r?\n/) + .filter(line => !/^#|^$/.test(line.trim())) + .map(rule => { + return new Minimatch(rule.trim(), mmopt) + }) + + this.ignoreRules[file] = rules + + then() + } + + filterEntries () { + // at this point we either have ignore rules, or just inheriting + // this exclusion is at the point where we know the list of + // entries in the dir, but don't know what they are. since + // some of them *might* be directories, we have to run the + // match in dir-mode as well, so that we'll pick up partials + // of files that will be included later. Anything included + // at this point will be checked again later once we know + // what it is. + const filtered = this.entries.map(entry => { + // at this point, we don't know if it's a dir or not. + const passFile = this.filterEntry(entry) + const passDir = this.filterEntry(entry, true) + return (passFile || passDir) ? [entry, passFile, passDir] : false + }).filter(e => e) + + // now we stat them all + // if it's a dir, and passes as a dir, then recurse + // if it's not a dir, but passes as a file, add to set + let entryCount = filtered.length + if (entryCount === 0) { + this.emit('done', this.result) + } else { + const then = _ => { + if (--entryCount === 0) { + this.emit('done', this.result) + } + } + filtered.forEach(filt => { + const entry = filt[0] + const file = filt[1] + const dir = filt[2] + this.stat({ entry, file, dir }, then) + }) + } + } + + onstat ({ st, entry, file, dir, isSymbolicLink }, then) { + const abs = this.path + '/' + entry + if (!st.isDirectory()) { + if (file) { + this.result.add(abs.slice(this.root.length + 1)) + } + then() + } else { + // is a directory + if (dir) { + this.walker(entry, { isSymbolicLink }, then) + } else { + then() + } + } + } + + stat ({ entry, file, dir }, then) { + const abs = this.path + '/' + entry + fs.lstat(abs, (lstatErr, lstatResult) => { + if (lstatErr) { + this.emit('error', lstatErr) + } else { + const isSymbolicLink = lstatResult.isSymbolicLink() + if (this.follow && isSymbolicLink) { + fs.stat(abs, (statErr, statResult) => { + if (statErr) { + this.emit('error', statErr) + } else { + this.onstat({ st: statResult, entry, file, dir, isSymbolicLink }, then) + } + }) + } else { + this.onstat({ st: lstatResult, entry, file, dir, isSymbolicLink }, then) + } + } + }) + } + + walkerOpt (entry, opts) { + return { + path: this.path + '/' + entry, + parent: this, + ignoreFiles: this.ignoreFiles, + follow: this.follow, + includeEmpty: this.includeEmpty, + ...opts, + } + } + + walker (entry, opts, then) { + new Walker(this.walkerOpt(entry, opts)).on('done', then).start() + } + + filterEntry (entry, partial) { + let included = true + + // this = /a/b/c + // entry = d + // parent /a/b sees c/d + if (this.parent && this.parent.filterEntry) { + var pt = this.basename + '/' + entry + included = this.parent.filterEntry(pt, partial) + } + + this.ignoreFiles.forEach(f => { + if (this.ignoreRules[f]) { + this.ignoreRules[f].forEach(rule => { + // negation means inclusion + // so if it's negated, and already included, no need to check + // likewise if it's neither negated nor included + if (rule.negate !== included) { + // first, match against /foo/bar + // then, against foo/bar + // then, in the case of partials, match with a / + const match = rule.match('/' + entry) || + rule.match(entry) || + (!!partial && ( + rule.match('/' + entry + '/') || + rule.match(entry + '/'))) || + (!!partial && rule.negate && ( + rule.match('/' + entry, true) || + rule.match(entry, true))) + + if (match) { + included = rule.negate + } + } + }) + } + }) + + return included + } +} + +class WalkerSync extends Walker { + start () { + this.onReaddir(fs.readdirSync(this.path)) + return this + } + + addIgnoreFile (file, then) { + const ig = path.resolve(this.path, file) + this.onReadIgnoreFile(file, fs.readFileSync(ig, 'utf8'), then) + } + + stat ({ entry, file, dir }, then) { + const abs = this.path + '/' + entry + let st = fs.lstatSync(abs) + const isSymbolicLink = st.isSymbolicLink() + if (this.follow && isSymbolicLink) { + st = fs.statSync(abs) + } + + // console.error('STAT SYNC', {st, entry, file, dir, isSymbolicLink, then}) + this.onstat({ st, entry, file, dir, isSymbolicLink }, then) + } + + walker (entry, opts, then) { + new WalkerSync(this.walkerOpt(entry, opts)).start() + then() + } +} + +const walk = (opts, callback) => { + const p = new Promise((resolve, reject) => { + new Walker(opts).on('done', resolve).on('error', reject).start() + }) + return callback ? p.then(res => callback(null, res), callback) : p +} + +const walkSync = opts => new WalkerSync(opts).start().result + +module.exports = walk +walk.sync = walkSync +walk.Walker = Walker +walk.WalkerSync = WalkerSync + + +/***/ }), + +/***/ 5557: +/***/ ((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 []; + + // 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); + } + + return expand(escapeBraces(str), true).map(unescapeBraces); +} + +function embrace(str) { + return '{' + str + '}'; +} +function isPadded(el) { + return /^-?0\d/.test(el); +} + +function lte(i, y) { + return i <= y; +} +function gte(i, y) { + return i >= y; +} + +function expand(str, isTop) { + var expansions = []; + + var m = balanced('{', '}', str); + if (!m) return [str]; + + // 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) + : ['']; + + 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]; + } + + 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; + }); + } + } + } + + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. + var N; + + 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); + + N = []; + + 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 = []; + + for (var j = 0; j < n.length; j++) { + N.push.apply(N, expand(n[j], false)); + } + } + + 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 expansions; +} + + + +/***/ }), + +/***/ 8374: +/***/ ((module) => { + +const isWindows = typeof process === 'object' && + process && + process.platform === 'win32' +module.exports = isWindows ? { sep: '\\' } : { sep: '/' } + + +/***/ }), + +/***/ 276: +/***/ ((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) +} + +module.exports = minimatch + +const path = __nccwpck_require__(8374) +minimatch.sep = path.sep + +const GLOBSTAR = Symbol('globstar **') +minimatch.GLOBSTAR = GLOBSTAR +const expand = __nccwpck_require__(5557) + +const plTypes = { + '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, + '?': { open: '(?:', close: ')?' }, + '+': { open: '(?:', close: ')+' }, + '*': { open: '(?:', close: ')*' }, + '@': { open: '(?:', close: ')' } +} + +// any single thing other than / +// don't need to escape / when using new RegExp() +const qmark = '[^/]' + +// * => 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})($|\\\/)).)*?' + +// not a ^ or / followed by a dot, +// followed by anything, any number of times. +const twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' + +// "abc" -> { a:true, b:true, c:true } +const charSet = s => s.split('').reduce((set, c) => { + set[c] = true + return set +}, {}) + +// characters that need to be escaped in RegExp. +const reSpecials = charSet('().*{}+?[]^$\\!') + +// characters that indicate we have to add the pattern start +const addPatternStartSet = charSet('[.(') + +// 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 + } + + 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)) + + return m +} + + + + + +// 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] + } + + return expand(pattern) +} + +const MAX_PATTERN_LENGTH = 1024 * 64 +const assertValidPattern = pattern => { + if (typeof pattern !== 'string') { + throw new TypeError('invalid pattern') + } + + if (pattern.length > MAX_PATTERN_LENGTH) { + throw new TypeError('pattern is too long') + } +} + +// 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') + +minimatch.makeRe = (pattern, options) => + new Minimatch(pattern, options || {}).makeRe() + +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 +} + +// replace stuff like \* with * +const globUnescape = s => s.replace(/\\(.)/g, '$1') +const regExpEscape = s => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') + +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() + } + + 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 + } + if (!pattern) { + this.empty = true + return + } + + // step 1: figure out negation, etc. + this.parseNegate() + + // step 2: expand braces + let set = this.globSet = this.braceExpand() + + if (options.debug) this.debug = (...args) => console.error(...args) + + this.debug(this.pattern, set) + + // 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)) + + this.debug(this.pattern, set) + + // glob --> regexps + set = set.map((s, si, set) => s.map(this.parse, this)) + + this.debug(this.pattern, set) + + // filter out everything that didn't compile properly. + set = set.filter(s => s.indexOf(false) === -1) + + this.debug(this.pattern, set) + + this.set = set + } + + parseNegate () { + if (this.options.nonegate) return + + const pattern = this.pattern + let negate = false + let negateOffset = 0 + + for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) { + negate = !negate + negateOffset++ + } + + if (negateOffset) this.pattern = pattern.substr(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 }) + + this.debug('matchOne', file.length, pattern.length) + + 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 + + if (p === GLOBSTAR) { + this.debug('GLOBSTAR', [pattern, p, f]) + + // "**" + // 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 + } + + // ok, let's see if we can swallow whatever we can. + while (fr < fl) { + var swallowee = file[fr] + + this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) + + // 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 + } + + // ** swallows a segment, and continue. + this.debug('globstar swallow a segment, and continue') + fr++ + } + } + + // 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 + } + + // 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) + } + + if (!hit) return false + } + + // 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/* + + // 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] === '') + } + + // should be unreachable. + /* istanbul ignore next */ + throw new Error('wtf?') + } + + braceExpand () { + return braceExpand(this.pattern, this.options) + } + + parse (pattern, isSub) { + assertValidPattern(pattern) + + const options = this.options + + // shortcuts + if (pattern === '**') { + if (!options.noglobstar) + return GLOBSTAR + else + pattern = '*' + } + if (pattern === '') return '' + + 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}(?:$|\\\/))' + : '(?!\\.)' + + 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 + } + } + + for (let i = 0, c; (i < pattern.length) && (c = pattern.charAt(i)); i++) { + this.debug('%s\t%s %s %j', pattern, i, re, c) + + // skip over any that are escaped. + if (escaping) { + /* istanbul ignore next - completely not allowed, even escaped. */ + if (c === '/') { + return false + } + + if (reSpecials[c]) { + re += '\\' + } + re += c + escaping = false + continue + } + + switch (c) { + /* istanbul ignore next */ + case '/': { + // Should already be path-split by now. + return false + } + + case '\\': + clearStateChar() + escaping = true + continue + + // 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) + + // 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 + } + + // 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 + + case '(': + if (inClass) { + re += '(' + continue + } + + if (!stateChar) { + re += '\\(' + continue + } + + 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 + + case ')': + if (inClass || !patternListStack.length) { + re += '\\)' + continue + } + + 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 + + case '|': + if (inClass || !patternListStack.length) { + re += '\\|' + continue + } + + clearStateChar() + re += '|' + continue + + // these are mostly the same in regexp and glob + case '[': + // swallow any state-tracking char before the [ + clearStateChar() + + if (inClass) { + re += '\\' + c + continue + } + + inClass = true + classStart = i + reClassStart = re.length + re += c + continue + + 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 + } + + // 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.substr(0, reClassStart) + '\\[' + sp[0] + '\\]' + hasMagic = hasMagic || sp[1] + inClass = false + continue + } + + // finish up the class. + hasMagic = true + inClass = false + re += c + continue + + default: + // swallow any state char that wasn't consumed + clearStateChar() + + if (reSpecials[c] && !(c === '^' && inClass)) { + re += '\\' + } + + re += c + break + + } // switch + } // for + + // 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.substr(classStart + 1) + sp = this.parse(cs, SUBPARSE) + re = re.substr(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 + '|' + }) + + this.debug('tail=%j\n %s', tail, tail, pl, re) + const t = pl.type === '*' ? star + : pl.type === '?' ? qmark + : '\\' + pl.type + + hasMagic = true + re = re.slice(0, pl.reStart) + t + '\\(' + tail + } + + // handle trailing things that only matter at the very end. + clearStateChar() + if (escaping) { + // trailing \\ + re += '\\\\' + } + + // 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)] + + // 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 + + const dollar = nlAfter === '' && isSub !== SUBPARSE ? '$' : '' + re = nlBefore + nlFirst + nlAfter + dollar + nlLast + } + + // 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 + } + + if (addPatternStart) { + re = patternStart + re + } + + // parsing just a piece of a larger pattern. + if (isSub === SUBPARSE) { + return [re, hasMagic] + } + + // 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) + } + + 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('$.') + } + } + + 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 + + const twoStar = options.noglobstar ? star + : options.dot ? twoStarDot + : twoStarNoDot + const flags = options.nocase ? 'i' : '' + + // 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('|') + + // must match entire pattern + // ending in a * or ** will make it less strict. + re = '^(?:' + re + ')$' + + // can match anything, as long as it's not this. + if (this.negate) re = '^(?!' + re + ').*$' + + try { + this.regexp = new RegExp(re, flags) + } catch (ex) /* istanbul ignore next - should be impossible */ { + this.regexp = false + } + 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 === '' + + if (f === '/' && partial) return true + + const options = this.options + + // windows: need to use /, not \ + if (path.sep !== '/') { + f = f.split(path.sep).join('/') + } + + // 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) + + // 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 + } + + 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 + } + } + + // didn't get any hits. this is success if it's a negative + // pattern, failure otherwise. + if (options.flipNegate) return false + return this.negate + } + + static defaults (def) { + return minimatch.defaults(def).Minimatch + } +} + +minimatch.Minimatch = Minimatch + + +/***/ }), + +/***/ 3794: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +var _interopRequireDefault = __nccwpck_require__(3286); + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _custom = _interopRequireDefault(__nccwpck_require__(9472)); + +var _types = _interopRequireDefault(__nccwpck_require__(770)); + +var _plugins = _interopRequireDefault(__nccwpck_require__(4976)); + +var _default = (0, _custom["default"])({ + types: [_types["default"]], + plugins: [_plugins["default"]] +}); + +exports["default"] = _default; +module.exports = exports.default; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 8541: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var encode = __nccwpck_require__(9179), + decode = __nccwpck_require__(5066); + +module.exports = { + encode: encode, + decode: decode +}; + + +/***/ }), + +/***/ 5066: +/***/ ((module) => { + +/* -*- tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- / +/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */ +/* + Copyright 2011 notmasteryet + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +// - The JPEG specification can be found in the ITU CCITT Recommendation T.81 +// (www.w3.org/Graphics/JPEG/itu-t81.pdf) +// - The JFIF specification can be found in the JPEG File Interchange Format +// (www.w3.org/Graphics/JPEG/jfif3.pdf) +// - The Adobe Application-Specific JPEG markers in the Supporting the DCT Filters +// in PostScript Level 2, Technical Note #5116 +// (partners.adobe.com/public/developer/en/ps/sdk/5116.DCT_Filter.pdf) + +var JpegImage = (function jpegImage() { + "use strict"; + var dctZigZag = new Int32Array([ + 0, + 1, 8, + 16, 9, 2, + 3, 10, 17, 24, + 32, 25, 18, 11, 4, + 5, 12, 19, 26, 33, 40, + 48, 41, 34, 27, 20, 13, 6, + 7, 14, 21, 28, 35, 42, 49, 56, + 57, 50, 43, 36, 29, 22, 15, + 23, 30, 37, 44, 51, 58, + 59, 52, 45, 38, 31, + 39, 46, 53, 60, + 61, 54, 47, + 55, 62, + 63 + ]); + + var dctCos1 = 4017 // cos(pi/16) + var dctSin1 = 799 // sin(pi/16) + var dctCos3 = 3406 // cos(3*pi/16) + var dctSin3 = 2276 // sin(3*pi/16) + var dctCos6 = 1567 // cos(6*pi/16) + var dctSin6 = 3784 // sin(6*pi/16) + var dctSqrt2 = 5793 // sqrt(2) + var dctSqrt1d2 = 2896 // sqrt(2) / 2 + + function constructor() { + } + + function buildHuffmanTable(codeLengths, values) { + var k = 0, code = [], i, j, length = 16; + while (length > 0 && !codeLengths[length - 1]) + length--; + code.push({children: [], index: 0}); + var p = code[0], q; + for (i = 0; i < length; i++) { + for (j = 0; j < codeLengths[i]; j++) { + p = code.pop(); + p.children[p.index] = values[k]; + while (p.index > 0) { + if (code.length === 0) + throw new Error('Could not recreate Huffman Table'); + p = code.pop(); + } + p.index++; + code.push(p); + while (code.length <= i) { + code.push(q = {children: [], index: 0}); + p.children[p.index] = q.children; + p = q; + } + k++; + } + if (i + 1 < length) { + // p here points to last code + code.push(q = {children: [], index: 0}); + p.children[p.index] = q.children; + p = q; + } + } + return code[0].children; + } + + function decodeScan(data, offset, + frame, components, resetInterval, + spectralStart, spectralEnd, + successivePrev, successive, opts) { + var precision = frame.precision; + var samplesPerLine = frame.samplesPerLine; + var scanLines = frame.scanLines; + var mcusPerLine = frame.mcusPerLine; + var progressive = frame.progressive; + var maxH = frame.maxH, maxV = frame.maxV; + + var startOffset = offset, bitsData = 0, bitsCount = 0; + function readBit() { + if (bitsCount > 0) { + bitsCount--; + return (bitsData >> bitsCount) & 1; + } + bitsData = data[offset++]; + if (bitsData == 0xFF) { + var nextByte = data[offset++]; + if (nextByte) { + throw new Error("unexpected marker: " + ((bitsData << 8) | nextByte).toString(16)); + } + // unstuff 0 + } + bitsCount = 7; + return bitsData >>> 7; + } + function decodeHuffman(tree) { + var node = tree, bit; + while ((bit = readBit()) !== null) { + node = node[bit]; + if (typeof node === 'number') + return node; + if (typeof node !== 'object') + throw new Error("invalid huffman sequence"); + } + return null; + } + function receive(length) { + var n = 0; + while (length > 0) { + var bit = readBit(); + if (bit === null) return; + n = (n << 1) | bit; + length--; + } + return n; + } + function receiveAndExtend(length) { + var n = receive(length); + if (n >= 1 << (length - 1)) + return n; + return n + (-1 << length) + 1; + } + function decodeBaseline(component, zz) { + var t = decodeHuffman(component.huffmanTableDC); + var diff = t === 0 ? 0 : receiveAndExtend(t); + zz[0]= (component.pred += diff); + var k = 1; + while (k < 64) { + var rs = decodeHuffman(component.huffmanTableAC); + var s = rs & 15, r = rs >> 4; + if (s === 0) { + if (r < 15) + break; + k += 16; + continue; + } + k += r; + var z = dctZigZag[k]; + zz[z] = receiveAndExtend(s); + k++; + } + } + function decodeDCFirst(component, zz) { + var t = decodeHuffman(component.huffmanTableDC); + var diff = t === 0 ? 0 : (receiveAndExtend(t) << successive); + zz[0] = (component.pred += diff); + } + function decodeDCSuccessive(component, zz) { + zz[0] |= readBit() << successive; + } + var eobrun = 0; + function decodeACFirst(component, zz) { + if (eobrun > 0) { + eobrun--; + return; + } + var k = spectralStart, e = spectralEnd; + while (k <= e) { + var rs = decodeHuffman(component.huffmanTableAC); + var s = rs & 15, r = rs >> 4; + if (s === 0) { + if (r < 15) { + eobrun = receive(r) + (1 << r) - 1; + break; + } + k += 16; + continue; + } + k += r; + var z = dctZigZag[k]; + zz[z] = receiveAndExtend(s) * (1 << successive); + k++; + } + } + var successiveACState = 0, successiveACNextValue; + function decodeACSuccessive(component, zz) { + var k = spectralStart, e = spectralEnd, r = 0; + while (k <= e) { + var z = dctZigZag[k]; + var direction = zz[z] < 0 ? -1 : 1; + switch (successiveACState) { + case 0: // initial state + var rs = decodeHuffman(component.huffmanTableAC); + var s = rs & 15, r = rs >> 4; + if (s === 0) { + if (r < 15) { + eobrun = receive(r) + (1 << r); + successiveACState = 4; + } else { + r = 16; + successiveACState = 1; + } + } else { + if (s !== 1) + throw new Error("invalid ACn encoding"); + successiveACNextValue = receiveAndExtend(s); + successiveACState = r ? 2 : 3; + } + continue; + case 1: // skipping r zero items + case 2: + if (zz[z]) + zz[z] += (readBit() << successive) * direction; + else { + r--; + if (r === 0) + successiveACState = successiveACState == 2 ? 3 : 0; + } + break; + case 3: // set value for a zero item + if (zz[z]) + zz[z] += (readBit() << successive) * direction; + else { + zz[z] = successiveACNextValue << successive; + successiveACState = 0; + } + break; + case 4: // eob + if (zz[z]) + zz[z] += (readBit() << successive) * direction; + break; + } + k++; + } + if (successiveACState === 4) { + eobrun--; + if (eobrun === 0) + successiveACState = 0; + } + } + function decodeMcu(component, decode, mcu, row, col) { + var mcuRow = (mcu / mcusPerLine) | 0; + var mcuCol = mcu % mcusPerLine; + var blockRow = mcuRow * component.v + row; + var blockCol = mcuCol * component.h + col; + // If the block is missing and we're in tolerant mode, just skip it. + if (component.blocks[blockRow] === undefined && opts.tolerantDecoding) + return; + decode(component, component.blocks[blockRow][blockCol]); + } + function decodeBlock(component, decode, mcu) { + var blockRow = (mcu / component.blocksPerLine) | 0; + var blockCol = mcu % component.blocksPerLine; + // If the block is missing and we're in tolerant mode, just skip it. + if (component.blocks[blockRow] === undefined && opts.tolerantDecoding) + return; + decode(component, component.blocks[blockRow][blockCol]); + } + + var componentsLength = components.length; + var component, i, j, k, n; + var decodeFn; + if (progressive) { + if (spectralStart === 0) + decodeFn = successivePrev === 0 ? decodeDCFirst : decodeDCSuccessive; + else + decodeFn = successivePrev === 0 ? decodeACFirst : decodeACSuccessive; + } else { + decodeFn = decodeBaseline; + } + + var mcu = 0, marker; + var mcuExpected; + if (componentsLength == 1) { + mcuExpected = components[0].blocksPerLine * components[0].blocksPerColumn; + } else { + mcuExpected = mcusPerLine * frame.mcusPerColumn; + } + if (!resetInterval) resetInterval = mcuExpected; + + var h, v; + while (mcu < mcuExpected) { + // reset interval stuff + for (i = 0; i < componentsLength; i++) + components[i].pred = 0; + eobrun = 0; + + if (componentsLength == 1) { + component = components[0]; + for (n = 0; n < resetInterval; n++) { + decodeBlock(component, decodeFn, mcu); + mcu++; + } + } else { + for (n = 0; n < resetInterval; n++) { + for (i = 0; i < componentsLength; i++) { + component = components[i]; + h = component.h; + v = component.v; + for (j = 0; j < v; j++) { + for (k = 0; k < h; k++) { + decodeMcu(component, decodeFn, mcu, j, k); + } + } + } + mcu++; + + // If we've reached our expected MCU's, stop decoding + if (mcu === mcuExpected) break; + } + } + + if (mcu === mcuExpected) { + // Skip trailing bytes at the end of the scan - until we reach the next marker + do { + if (data[offset] === 0xFF) { + if (data[offset + 1] !== 0x00) { + break; + } + } + offset += 1; + } while (offset < data.length - 2); + } + + // find marker + bitsCount = 0; + marker = (data[offset] << 8) | data[offset + 1]; + if (marker < 0xFF00) { + throw new Error("marker was not found"); + } + + if (marker >= 0xFFD0 && marker <= 0xFFD7) { // RSTx + offset += 2; + } + else + break; + } + + return offset - startOffset; + } + + function buildComponentData(frame, component) { + var lines = []; + var blocksPerLine = component.blocksPerLine; + var blocksPerColumn = component.blocksPerColumn; + var samplesPerLine = blocksPerLine << 3; + // Only 1 used per invocation of this function and garbage collected after invocation, so no need to account for its memory footprint. + var R = new Int32Array(64), r = new Uint8Array(64); + + // A port of poppler's IDCT method which in turn is taken from: + // Christoph Loeffler, Adriaan Ligtenberg, George S. Moschytz, + // "Practical Fast 1-D DCT Algorithms with 11 Multiplications", + // IEEE Intl. Conf. on Acoustics, Speech & Signal Processing, 1989, + // 988-991. + function quantizeAndInverse(zz, dataOut, dataIn) { + var qt = component.quantizationTable; + var v0, v1, v2, v3, v4, v5, v6, v7, t; + var p = dataIn; + var i; + + // dequant + for (i = 0; i < 64; i++) + p[i] = zz[i] * qt[i]; + + // inverse DCT on rows + for (i = 0; i < 8; ++i) { + var row = 8 * i; + + // check for all-zero AC coefficients + if (p[1 + row] == 0 && p[2 + row] == 0 && p[3 + row] == 0 && + p[4 + row] == 0 && p[5 + row] == 0 && p[6 + row] == 0 && + p[7 + row] == 0) { + t = (dctSqrt2 * p[0 + row] + 512) >> 10; + p[0 + row] = t; + p[1 + row] = t; + p[2 + row] = t; + p[3 + row] = t; + p[4 + row] = t; + p[5 + row] = t; + p[6 + row] = t; + p[7 + row] = t; + continue; + } + + // stage 4 + v0 = (dctSqrt2 * p[0 + row] + 128) >> 8; + v1 = (dctSqrt2 * p[4 + row] + 128) >> 8; + v2 = p[2 + row]; + v3 = p[6 + row]; + v4 = (dctSqrt1d2 * (p[1 + row] - p[7 + row]) + 128) >> 8; + v7 = (dctSqrt1d2 * (p[1 + row] + p[7 + row]) + 128) >> 8; + v5 = p[3 + row] << 4; + v6 = p[5 + row] << 4; + + // stage 3 + t = (v0 - v1+ 1) >> 1; + v0 = (v0 + v1 + 1) >> 1; + v1 = t; + t = (v2 * dctSin6 + v3 * dctCos6 + 128) >> 8; + v2 = (v2 * dctCos6 - v3 * dctSin6 + 128) >> 8; + v3 = t; + t = (v4 - v6 + 1) >> 1; + v4 = (v4 + v6 + 1) >> 1; + v6 = t; + t = (v7 + v5 + 1) >> 1; + v5 = (v7 - v5 + 1) >> 1; + v7 = t; + + // stage 2 + t = (v0 - v3 + 1) >> 1; + v0 = (v0 + v3 + 1) >> 1; + v3 = t; + t = (v1 - v2 + 1) >> 1; + v1 = (v1 + v2 + 1) >> 1; + v2 = t; + t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12; + v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12; + v7 = t; + t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12; + v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12; + v6 = t; + + // stage 1 + p[0 + row] = v0 + v7; + p[7 + row] = v0 - v7; + p[1 + row] = v1 + v6; + p[6 + row] = v1 - v6; + p[2 + row] = v2 + v5; + p[5 + row] = v2 - v5; + p[3 + row] = v3 + v4; + p[4 + row] = v3 - v4; + } + + // inverse DCT on columns + for (i = 0; i < 8; ++i) { + var col = i; + + // check for all-zero AC coefficients + if (p[1*8 + col] == 0 && p[2*8 + col] == 0 && p[3*8 + col] == 0 && + p[4*8 + col] == 0 && p[5*8 + col] == 0 && p[6*8 + col] == 0 && + p[7*8 + col] == 0) { + t = (dctSqrt2 * dataIn[i+0] + 8192) >> 14; + p[0*8 + col] = t; + p[1*8 + col] = t; + p[2*8 + col] = t; + p[3*8 + col] = t; + p[4*8 + col] = t; + p[5*8 + col] = t; + p[6*8 + col] = t; + p[7*8 + col] = t; + continue; + } + + // stage 4 + v0 = (dctSqrt2 * p[0*8 + col] + 2048) >> 12; + v1 = (dctSqrt2 * p[4*8 + col] + 2048) >> 12; + v2 = p[2*8 + col]; + v3 = p[6*8 + col]; + v4 = (dctSqrt1d2 * (p[1*8 + col] - p[7*8 + col]) + 2048) >> 12; + v7 = (dctSqrt1d2 * (p[1*8 + col] + p[7*8 + col]) + 2048) >> 12; + v5 = p[3*8 + col]; + v6 = p[5*8 + col]; + + // stage 3 + t = (v0 - v1 + 1) >> 1; + v0 = (v0 + v1 + 1) >> 1; + v1 = t; + t = (v2 * dctSin6 + v3 * dctCos6 + 2048) >> 12; + v2 = (v2 * dctCos6 - v3 * dctSin6 + 2048) >> 12; + v3 = t; + t = (v4 - v6 + 1) >> 1; + v4 = (v4 + v6 + 1) >> 1; + v6 = t; + t = (v7 + v5 + 1) >> 1; + v5 = (v7 - v5 + 1) >> 1; + v7 = t; + + // stage 2 + t = (v0 - v3 + 1) >> 1; + v0 = (v0 + v3 + 1) >> 1; + v3 = t; + t = (v1 - v2 + 1) >> 1; + v1 = (v1 + v2 + 1) >> 1; + v2 = t; + t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12; + v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12; + v7 = t; + t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12; + v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12; + v6 = t; + + // stage 1 + p[0*8 + col] = v0 + v7; + p[7*8 + col] = v0 - v7; + p[1*8 + col] = v1 + v6; + p[6*8 + col] = v1 - v6; + p[2*8 + col] = v2 + v5; + p[5*8 + col] = v2 - v5; + p[3*8 + col] = v3 + v4; + p[4*8 + col] = v3 - v4; + } + + // convert to 8-bit integers + for (i = 0; i < 64; ++i) { + var sample = 128 + ((p[i] + 8) >> 4); + dataOut[i] = sample < 0 ? 0 : sample > 0xFF ? 0xFF : sample; + } + } + + requestMemoryAllocation(samplesPerLine * blocksPerColumn * 8); + + var i, j; + for (var blockRow = 0; blockRow < blocksPerColumn; blockRow++) { + var scanLine = blockRow << 3; + for (i = 0; i < 8; i++) + lines.push(new Uint8Array(samplesPerLine)); + for (var blockCol = 0; blockCol < blocksPerLine; blockCol++) { + quantizeAndInverse(component.blocks[blockRow][blockCol], r, R); + + var offset = 0, sample = blockCol << 3; + for (j = 0; j < 8; j++) { + var line = lines[scanLine + j]; + for (i = 0; i < 8; i++) + line[sample + i] = r[offset++]; + } + } + } + return lines; + } + + function clampTo8bit(a) { + return a < 0 ? 0 : a > 255 ? 255 : a; + } + + constructor.prototype = { + load: function load(path) { + var xhr = new XMLHttpRequest(); + xhr.open("GET", path, true); + xhr.responseType = "arraybuffer"; + xhr.onload = (function() { + // TODO catch parse error + var data = new Uint8Array(xhr.response || xhr.mozResponseArrayBuffer); + this.parse(data); + if (this.onload) + this.onload(); + }).bind(this); + xhr.send(null); + }, + parse: function parse(data) { + var maxResolutionInPixels = this.opts.maxResolutionInMP * 1000 * 1000; + var offset = 0, length = data.length; + function readUint16() { + var value = (data[offset] << 8) | data[offset + 1]; + offset += 2; + return value; + } + function readDataBlock() { + var length = readUint16(); + var array = data.subarray(offset, offset + length - 2); + offset += array.length; + return array; + } + function prepareComponents(frame) { + var maxH = 0, maxV = 0; + var component, componentId; + for (componentId in frame.components) { + if (frame.components.hasOwnProperty(componentId)) { + component = frame.components[componentId]; + if (maxH < component.h) maxH = component.h; + if (maxV < component.v) maxV = component.v; + } + } + var mcusPerLine = Math.ceil(frame.samplesPerLine / 8 / maxH); + var mcusPerColumn = Math.ceil(frame.scanLines / 8 / maxV); + for (componentId in frame.components) { + if (frame.components.hasOwnProperty(componentId)) { + component = frame.components[componentId]; + var blocksPerLine = Math.ceil(Math.ceil(frame.samplesPerLine / 8) * component.h / maxH); + var blocksPerColumn = Math.ceil(Math.ceil(frame.scanLines / 8) * component.v / maxV); + var blocksPerLineForMcu = mcusPerLine * component.h; + var blocksPerColumnForMcu = mcusPerColumn * component.v; + var blocksToAllocate = blocksPerColumnForMcu * blocksPerLineForMcu; + var blocks = []; + + // Each block is a Int32Array of length 64 (4 x 64 = 256 bytes) + requestMemoryAllocation(blocksToAllocate * 256); + + for (var i = 0; i < blocksPerColumnForMcu; i++) { + var row = []; + for (var j = 0; j < blocksPerLineForMcu; j++) + row.push(new Int32Array(64)); + blocks.push(row); + } + component.blocksPerLine = blocksPerLine; + component.blocksPerColumn = blocksPerColumn; + component.blocks = blocks; + } + } + frame.maxH = maxH; + frame.maxV = maxV; + frame.mcusPerLine = mcusPerLine; + frame.mcusPerColumn = mcusPerColumn; + } + var jfif = null; + var adobe = null; + var pixels = null; + var frame, resetInterval; + var quantizationTables = [], frames = []; + var huffmanTablesAC = [], huffmanTablesDC = []; + var fileMarker = readUint16(); + this.comments = []; + if (fileMarker != 0xFFD8) { // SOI (Start of Image) + throw new Error("SOI not found"); + } + + fileMarker = readUint16(); + while (fileMarker != 0xFFD9) { // EOI (End of image) + var i, j, l; + switch(fileMarker) { + case 0xFF00: break; + case 0xFFE0: // APP0 (Application Specific) + case 0xFFE1: // APP1 + case 0xFFE2: // APP2 + case 0xFFE3: // APP3 + case 0xFFE4: // APP4 + case 0xFFE5: // APP5 + case 0xFFE6: // APP6 + case 0xFFE7: // APP7 + case 0xFFE8: // APP8 + case 0xFFE9: // APP9 + case 0xFFEA: // APP10 + case 0xFFEB: // APP11 + case 0xFFEC: // APP12 + case 0xFFED: // APP13 + case 0xFFEE: // APP14 + case 0xFFEF: // APP15 + case 0xFFFE: // COM (Comment) + var appData = readDataBlock(); + + if (fileMarker === 0xFFFE) { + var comment = String.fromCharCode.apply(null, appData); + this.comments.push(comment); + } + + if (fileMarker === 0xFFE0) { + if (appData[0] === 0x4A && appData[1] === 0x46 && appData[2] === 0x49 && + appData[3] === 0x46 && appData[4] === 0) { // 'JFIF\x00' + jfif = { + version: { major: appData[5], minor: appData[6] }, + densityUnits: appData[7], + xDensity: (appData[8] << 8) | appData[9], + yDensity: (appData[10] << 8) | appData[11], + thumbWidth: appData[12], + thumbHeight: appData[13], + thumbData: appData.subarray(14, 14 + 3 * appData[12] * appData[13]) + }; + } + } + // TODO APP1 - Exif + if (fileMarker === 0xFFE1) { + if (appData[0] === 0x45 && + appData[1] === 0x78 && + appData[2] === 0x69 && + appData[3] === 0x66 && + appData[4] === 0) { // 'EXIF\x00' + this.exifBuffer = appData.subarray(5, appData.length); + } + } + + if (fileMarker === 0xFFEE) { + if (appData[0] === 0x41 && appData[1] === 0x64 && appData[2] === 0x6F && + appData[3] === 0x62 && appData[4] === 0x65 && appData[5] === 0) { // 'Adobe\x00' + adobe = { + version: appData[6], + flags0: (appData[7] << 8) | appData[8], + flags1: (appData[9] << 8) | appData[10], + transformCode: appData[11] + }; + } + } + break; + + case 0xFFDB: // DQT (Define Quantization Tables) + var quantizationTablesLength = readUint16(); + var quantizationTablesEnd = quantizationTablesLength + offset - 2; + while (offset < quantizationTablesEnd) { + var quantizationTableSpec = data[offset++]; + requestMemoryAllocation(64 * 4); + var tableData = new Int32Array(64); + if ((quantizationTableSpec >> 4) === 0) { // 8 bit values + for (j = 0; j < 64; j++) { + var z = dctZigZag[j]; + tableData[z] = data[offset++]; + } + } else if ((quantizationTableSpec >> 4) === 1) { //16 bit + for (j = 0; j < 64; j++) { + var z = dctZigZag[j]; + tableData[z] = readUint16(); + } + } else + throw new Error("DQT: invalid table spec"); + quantizationTables[quantizationTableSpec & 15] = tableData; + } + break; + + case 0xFFC0: // SOF0 (Start of Frame, Baseline DCT) + case 0xFFC1: // SOF1 (Start of Frame, Extended DCT) + case 0xFFC2: // SOF2 (Start of Frame, Progressive DCT) + readUint16(); // skip data length + frame = {}; + frame.extended = (fileMarker === 0xFFC1); + frame.progressive = (fileMarker === 0xFFC2); + frame.precision = data[offset++]; + frame.scanLines = readUint16(); + frame.samplesPerLine = readUint16(); + frame.components = {}; + frame.componentsOrder = []; + + var pixelsInFrame = frame.scanLines * frame.samplesPerLine; + if (pixelsInFrame > maxResolutionInPixels) { + var exceededAmount = Math.ceil((pixelsInFrame - maxResolutionInPixels) / 1e6); + throw new Error(`maxResolutionInMP limit exceeded by ${exceededAmount}MP`); + } + + var componentsCount = data[offset++], componentId; + var maxH = 0, maxV = 0; + for (i = 0; i < componentsCount; i++) { + componentId = data[offset]; + var h = data[offset + 1] >> 4; + var v = data[offset + 1] & 15; + var qId = data[offset + 2]; + frame.componentsOrder.push(componentId); + frame.components[componentId] = { + h: h, + v: v, + quantizationIdx: qId + }; + offset += 3; + } + prepareComponents(frame); + frames.push(frame); + break; + + case 0xFFC4: // DHT (Define Huffman Tables) + var huffmanLength = readUint16(); + for (i = 2; i < huffmanLength;) { + var huffmanTableSpec = data[offset++]; + var codeLengths = new Uint8Array(16); + var codeLengthSum = 0; + for (j = 0; j < 16; j++, offset++) { + codeLengthSum += (codeLengths[j] = data[offset]); + } + requestMemoryAllocation(16 + codeLengthSum); + var huffmanValues = new Uint8Array(codeLengthSum); + for (j = 0; j < codeLengthSum; j++, offset++) + huffmanValues[j] = data[offset]; + i += 17 + codeLengthSum; + + ((huffmanTableSpec >> 4) === 0 ? + huffmanTablesDC : huffmanTablesAC)[huffmanTableSpec & 15] = + buildHuffmanTable(codeLengths, huffmanValues); + } + break; + + case 0xFFDD: // DRI (Define Restart Interval) + readUint16(); // skip data length + resetInterval = readUint16(); + break; + + case 0xFFDC: // Number of Lines marker + readUint16() // skip data length + readUint16() // Ignore this data since it represents the image height + break; + + case 0xFFDA: // SOS (Start of Scan) + var scanLength = readUint16(); + var selectorsCount = data[offset++]; + var components = [], component; + for (i = 0; i < selectorsCount; i++) { + component = frame.components[data[offset++]]; + var tableSpec = data[offset++]; + component.huffmanTableDC = huffmanTablesDC[tableSpec >> 4]; + component.huffmanTableAC = huffmanTablesAC[tableSpec & 15]; + components.push(component); + } + var spectralStart = data[offset++]; + var spectralEnd = data[offset++]; + var successiveApproximation = data[offset++]; + var processed = decodeScan(data, offset, + frame, components, resetInterval, + spectralStart, spectralEnd, + successiveApproximation >> 4, successiveApproximation & 15, this.opts); + offset += processed; + break; + + case 0xFFFF: // Fill bytes + if (data[offset] !== 0xFF) { // Avoid skipping a valid marker. + offset--; + } + break; + + default: + if (data[offset - 3] == 0xFF && + data[offset - 2] >= 0xC0 && data[offset - 2] <= 0xFE) { + // could be incorrect encoding -- last 0xFF byte of the previous + // block was eaten by the encoder + offset -= 3; + break; + } + throw new Error("unknown JPEG marker " + fileMarker.toString(16)); + } + fileMarker = readUint16(); + } + if (frames.length != 1) + throw new Error("only single frame JPEGs supported"); + + // set each frame's components quantization table + for (var i = 0; i < frames.length; i++) { + var cp = frames[i].components; + for (var j in cp) { + cp[j].quantizationTable = quantizationTables[cp[j].quantizationIdx]; + delete cp[j].quantizationIdx; + } + } + + this.width = frame.samplesPerLine; + this.height = frame.scanLines; + this.jfif = jfif; + this.adobe = adobe; + this.components = []; + for (var i = 0; i < frame.componentsOrder.length; i++) { + var component = frame.components[frame.componentsOrder[i]]; + this.components.push({ + lines: buildComponentData(frame, component), + scaleX: component.h / frame.maxH, + scaleY: component.v / frame.maxV + }); + } + }, + getData: function getData(width, height) { + var scaleX = this.width / width, scaleY = this.height / height; + + var component1, component2, component3, component4; + var component1Line, component2Line, component3Line, component4Line; + var x, y; + var offset = 0; + var Y, Cb, Cr, K, C, M, Ye, R, G, B; + var colorTransform; + var dataLength = width * height * this.components.length; + requestMemoryAllocation(dataLength); + var data = new Uint8Array(dataLength); + switch (this.components.length) { + case 1: + component1 = this.components[0]; + for (y = 0; y < height; y++) { + component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)]; + for (x = 0; x < width; x++) { + Y = component1Line[0 | (x * component1.scaleX * scaleX)]; + + data[offset++] = Y; + } + } + break; + case 2: + // PDF might compress two component data in custom colorspace + component1 = this.components[0]; + component2 = this.components[1]; + for (y = 0; y < height; y++) { + component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)]; + component2Line = component2.lines[0 | (y * component2.scaleY * scaleY)]; + for (x = 0; x < width; x++) { + Y = component1Line[0 | (x * component1.scaleX * scaleX)]; + data[offset++] = Y; + Y = component2Line[0 | (x * component2.scaleX * scaleX)]; + data[offset++] = Y; + } + } + break; + case 3: + // The default transform for three components is true + colorTransform = true; + // The adobe transform marker overrides any previous setting + if (this.adobe && this.adobe.transformCode) + colorTransform = true; + else if (typeof this.opts.colorTransform !== 'undefined') + colorTransform = !!this.opts.colorTransform; + + component1 = this.components[0]; + component2 = this.components[1]; + component3 = this.components[2]; + for (y = 0; y < height; y++) { + component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)]; + component2Line = component2.lines[0 | (y * component2.scaleY * scaleY)]; + component3Line = component3.lines[0 | (y * component3.scaleY * scaleY)]; + for (x = 0; x < width; x++) { + if (!colorTransform) { + R = component1Line[0 | (x * component1.scaleX * scaleX)]; + G = component2Line[0 | (x * component2.scaleX * scaleX)]; + B = component3Line[0 | (x * component3.scaleX * scaleX)]; + } else { + Y = component1Line[0 | (x * component1.scaleX * scaleX)]; + Cb = component2Line[0 | (x * component2.scaleX * scaleX)]; + Cr = component3Line[0 | (x * component3.scaleX * scaleX)]; + + R = clampTo8bit(Y + 1.402 * (Cr - 128)); + G = clampTo8bit(Y - 0.3441363 * (Cb - 128) - 0.71413636 * (Cr - 128)); + B = clampTo8bit(Y + 1.772 * (Cb - 128)); + } + + data[offset++] = R; + data[offset++] = G; + data[offset++] = B; + } + } + break; + case 4: + if (!this.adobe) + throw new Error('Unsupported color mode (4 components)'); + // The default transform for four components is false + colorTransform = false; + // The adobe transform marker overrides any previous setting + if (this.adobe && this.adobe.transformCode) + colorTransform = true; + else if (typeof this.opts.colorTransform !== 'undefined') + colorTransform = !!this.opts.colorTransform; + + component1 = this.components[0]; + component2 = this.components[1]; + component3 = this.components[2]; + component4 = this.components[3]; + for (y = 0; y < height; y++) { + component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)]; + component2Line = component2.lines[0 | (y * component2.scaleY * scaleY)]; + component3Line = component3.lines[0 | (y * component3.scaleY * scaleY)]; + component4Line = component4.lines[0 | (y * component4.scaleY * scaleY)]; + for (x = 0; x < width; x++) { + if (!colorTransform) { + C = component1Line[0 | (x * component1.scaleX * scaleX)]; + M = component2Line[0 | (x * component2.scaleX * scaleX)]; + Ye = component3Line[0 | (x * component3.scaleX * scaleX)]; + K = component4Line[0 | (x * component4.scaleX * scaleX)]; + } else { + Y = component1Line[0 | (x * component1.scaleX * scaleX)]; + Cb = component2Line[0 | (x * component2.scaleX * scaleX)]; + Cr = component3Line[0 | (x * component3.scaleX * scaleX)]; + K = component4Line[0 | (x * component4.scaleX * scaleX)]; + + C = 255 - clampTo8bit(Y + 1.402 * (Cr - 128)); + M = 255 - clampTo8bit(Y - 0.3441363 * (Cb - 128) - 0.71413636 * (Cr - 128)); + Ye = 255 - clampTo8bit(Y + 1.772 * (Cb - 128)); + } + data[offset++] = 255-C; + data[offset++] = 255-M; + data[offset++] = 255-Ye; + data[offset++] = 255-K; + } + } + break; + default: + throw new Error('Unsupported color mode'); + } + return data; + }, + copyToImageData: function copyToImageData(imageData, formatAsRGBA) { + var width = imageData.width, height = imageData.height; + var imageDataArray = imageData.data; + var data = this.getData(width, height); + var i = 0, j = 0, x, y; + var Y, K, C, M, R, G, B; + switch (this.components.length) { + case 1: + for (y = 0; y < height; y++) { + for (x = 0; x < width; x++) { + Y = data[i++]; + + imageDataArray[j++] = Y; + imageDataArray[j++] = Y; + imageDataArray[j++] = Y; + if (formatAsRGBA) { + imageDataArray[j++] = 255; + } + } + } + break; + case 3: + for (y = 0; y < height; y++) { + for (x = 0; x < width; x++) { + R = data[i++]; + G = data[i++]; + B = data[i++]; + + imageDataArray[j++] = R; + imageDataArray[j++] = G; + imageDataArray[j++] = B; + if (formatAsRGBA) { + imageDataArray[j++] = 255; + } + } + } + break; + case 4: + for (y = 0; y < height; y++) { + for (x = 0; x < width; x++) { + C = data[i++]; + M = data[i++]; + Y = data[i++]; + K = data[i++]; + + R = 255 - clampTo8bit(C * (1 - K / 255) + K); + G = 255 - clampTo8bit(M * (1 - K / 255) + K); + B = 255 - clampTo8bit(Y * (1 - K / 255) + K); + + imageDataArray[j++] = R; + imageDataArray[j++] = G; + imageDataArray[j++] = B; + if (formatAsRGBA) { + imageDataArray[j++] = 255; + } + } + } + break; + default: + throw new Error('Unsupported color mode'); + } + } + }; + + + // We cap the amount of memory used by jpeg-js to avoid unexpected OOMs from untrusted content. + var totalBytesAllocated = 0; + var maxMemoryUsageBytes = 0; + function requestMemoryAllocation(increaseAmount = 0) { + var totalMemoryImpactBytes = totalBytesAllocated + increaseAmount; + if (totalMemoryImpactBytes > maxMemoryUsageBytes) { + var exceededAmount = Math.ceil((totalMemoryImpactBytes - maxMemoryUsageBytes) / 1024 / 1024); + throw new Error(`maxMemoryUsageInMB limit exceeded by at least ${exceededAmount}MB`); + } + + totalBytesAllocated = totalMemoryImpactBytes; + } + + constructor.resetMaxMemoryUsage = function (maxMemoryUsageBytes_) { + totalBytesAllocated = 0; + maxMemoryUsageBytes = maxMemoryUsageBytes_; + }; + + constructor.getBytesAllocated = function () { + return totalBytesAllocated; + }; + + constructor.requestMemoryAllocation = requestMemoryAllocation; + + return constructor; +})(); + +if (true) { + module.exports = decode; +} else {} + +function decode(jpegData, userOpts = {}) { + var defaultOpts = { + // "undefined" means "Choose whether to transform colors based on the image’s color model." + colorTransform: undefined, + useTArray: false, + formatAsRGBA: true, + tolerantDecoding: true, + maxResolutionInMP: 100, // Don't decode more than 100 megapixels + maxMemoryUsageInMB: 512, // Don't decode if memory footprint is more than 512MB + }; + + var opts = {...defaultOpts, ...userOpts}; + var arr = new Uint8Array(jpegData); + var decoder = new JpegImage(); + decoder.opts = opts; + // If this constructor ever supports async decoding this will need to be done differently. + // Until then, treating as singleton limit is fine. + JpegImage.resetMaxMemoryUsage(opts.maxMemoryUsageInMB * 1024 * 1024); + decoder.parse(arr); + + var channels = (opts.formatAsRGBA) ? 4 : 3; + var bytesNeeded = decoder.width * decoder.height * channels; + try { + JpegImage.requestMemoryAllocation(bytesNeeded); + var image = { + width: decoder.width, + height: decoder.height, + exifBuffer: decoder.exifBuffer, + data: opts.useTArray ? + new Uint8Array(bytesNeeded) : + Buffer.alloc(bytesNeeded) + }; + if(decoder.comments.length > 0) { + image["comments"] = decoder.comments; + } + } catch (err){ + if (err instanceof RangeError){ + throw new Error("Could not allocate enough memory for the image. " + + "Required: " + bytesNeeded); + } else { + throw err; + } + } + + decoder.copyToImageData(image, opts.formatAsRGBA); + + return image; +} + + +/***/ }), + +/***/ 9179: +/***/ ((module) => { + +/* + Copyright (c) 2008, Adobe Systems Incorporated + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + * Neither the name of Adobe Systems Incorporated nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +/* +JPEG encoder ported to JavaScript and optimized by Andreas Ritter, www.bytestrom.eu, 11/2009 + +Basic GUI blocking jpeg encoder +*/ + +var btoa = btoa || function(buf) { + return Buffer.from(buf).toString('base64'); +}; + +function JPEGEncoder(quality) { + var self = this; + var fround = Math.round; + var ffloor = Math.floor; + var YTable = new Array(64); + var UVTable = new Array(64); + var fdtbl_Y = new Array(64); + var fdtbl_UV = new Array(64); + var YDC_HT; + var UVDC_HT; + var YAC_HT; + var UVAC_HT; + + var bitcode = new Array(65535); + var category = new Array(65535); + var outputfDCTQuant = new Array(64); + var DU = new Array(64); + var byteout = []; + var bytenew = 0; + var bytepos = 7; + + var YDU = new Array(64); + var UDU = new Array(64); + var VDU = new Array(64); + var clt = new Array(256); + var RGB_YUV_TABLE = new Array(2048); + var currentQuality; + + var ZigZag = [ + 0, 1, 5, 6,14,15,27,28, + 2, 4, 7,13,16,26,29,42, + 3, 8,12,17,25,30,41,43, + 9,11,18,24,31,40,44,53, + 10,19,23,32,39,45,52,54, + 20,22,33,38,46,51,55,60, + 21,34,37,47,50,56,59,61, + 35,36,48,49,57,58,62,63 + ]; + + var std_dc_luminance_nrcodes = [0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0]; + var std_dc_luminance_values = [0,1,2,3,4,5,6,7,8,9,10,11]; + var std_ac_luminance_nrcodes = [0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,0x7d]; + var std_ac_luminance_values = [ + 0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12, + 0x21,0x31,0x41,0x06,0x13,0x51,0x61,0x07, + 0x22,0x71,0x14,0x32,0x81,0x91,0xa1,0x08, + 0x23,0x42,0xb1,0xc1,0x15,0x52,0xd1,0xf0, + 0x24,0x33,0x62,0x72,0x82,0x09,0x0a,0x16, + 0x17,0x18,0x19,0x1a,0x25,0x26,0x27,0x28, + 0x29,0x2a,0x34,0x35,0x36,0x37,0x38,0x39, + 0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49, + 0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59, + 0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69, + 0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79, + 0x7a,0x83,0x84,0x85,0x86,0x87,0x88,0x89, + 0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98, + 0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7, + 0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6, + 0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5, + 0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4, + 0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xe1,0xe2, + 0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea, + 0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8, + 0xf9,0xfa + ]; + + var std_dc_chrominance_nrcodes = [0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0]; + var std_dc_chrominance_values = [0,1,2,3,4,5,6,7,8,9,10,11]; + var std_ac_chrominance_nrcodes = [0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,0x77]; + var std_ac_chrominance_values = [ + 0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21, + 0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71, + 0x13,0x22,0x32,0x81,0x08,0x14,0x42,0x91, + 0xa1,0xb1,0xc1,0x09,0x23,0x33,0x52,0xf0, + 0x15,0x62,0x72,0xd1,0x0a,0x16,0x24,0x34, + 0xe1,0x25,0xf1,0x17,0x18,0x19,0x1a,0x26, + 0x27,0x28,0x29,0x2a,0x35,0x36,0x37,0x38, + 0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48, + 0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58, + 0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68, + 0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78, + 0x79,0x7a,0x82,0x83,0x84,0x85,0x86,0x87, + 0x88,0x89,0x8a,0x92,0x93,0x94,0x95,0x96, + 0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5, + 0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4, + 0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3, + 0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2, + 0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda, + 0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9, + 0xea,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8, + 0xf9,0xfa + ]; + + function initQuantTables(sf){ + var YQT = [ + 16, 11, 10, 16, 24, 40, 51, 61, + 12, 12, 14, 19, 26, 58, 60, 55, + 14, 13, 16, 24, 40, 57, 69, 56, + 14, 17, 22, 29, 51, 87, 80, 62, + 18, 22, 37, 56, 68,109,103, 77, + 24, 35, 55, 64, 81,104,113, 92, + 49, 64, 78, 87,103,121,120,101, + 72, 92, 95, 98,112,100,103, 99 + ]; + + for (var i = 0; i < 64; i++) { + var t = ffloor((YQT[i]*sf+50)/100); + if (t < 1) { + t = 1; + } else if (t > 255) { + t = 255; + } + YTable[ZigZag[i]] = t; + } + var UVQT = [ + 17, 18, 24, 47, 99, 99, 99, 99, + 18, 21, 26, 66, 99, 99, 99, 99, + 24, 26, 56, 99, 99, 99, 99, 99, + 47, 66, 99, 99, 99, 99, 99, 99, + 99, 99, 99, 99, 99, 99, 99, 99, + 99, 99, 99, 99, 99, 99, 99, 99, + 99, 99, 99, 99, 99, 99, 99, 99, + 99, 99, 99, 99, 99, 99, 99, 99 + ]; + for (var j = 0; j < 64; j++) { + var u = ffloor((UVQT[j]*sf+50)/100); + if (u < 1) { + u = 1; + } else if (u > 255) { + u = 255; + } + UVTable[ZigZag[j]] = u; + } + var aasf = [ + 1.0, 1.387039845, 1.306562965, 1.175875602, + 1.0, 0.785694958, 0.541196100, 0.275899379 + ]; + var k = 0; + for (var row = 0; row < 8; row++) + { + for (var col = 0; col < 8; col++) + { + fdtbl_Y[k] = (1.0 / (YTable [ZigZag[k]] * aasf[row] * aasf[col] * 8.0)); + fdtbl_UV[k] = (1.0 / (UVTable[ZigZag[k]] * aasf[row] * aasf[col] * 8.0)); + k++; + } + } + } + + function computeHuffmanTbl(nrcodes, std_table){ + var codevalue = 0; + var pos_in_table = 0; + var HT = new Array(); + for (var k = 1; k <= 16; k++) { + for (var j = 1; j <= nrcodes[k]; j++) { + HT[std_table[pos_in_table]] = []; + HT[std_table[pos_in_table]][0] = codevalue; + HT[std_table[pos_in_table]][1] = k; + pos_in_table++; + codevalue++; + } + codevalue*=2; + } + return HT; + } + + function initHuffmanTbl() + { + YDC_HT = computeHuffmanTbl(std_dc_luminance_nrcodes,std_dc_luminance_values); + UVDC_HT = computeHuffmanTbl(std_dc_chrominance_nrcodes,std_dc_chrominance_values); + YAC_HT = computeHuffmanTbl(std_ac_luminance_nrcodes,std_ac_luminance_values); + UVAC_HT = computeHuffmanTbl(std_ac_chrominance_nrcodes,std_ac_chrominance_values); + } + + function initCategoryNumber() + { + var nrlower = 1; + var nrupper = 2; + for (var cat = 1; cat <= 15; cat++) { + //Positive numbers + for (var nr = nrlower; nr>0] = 38470 * i; + RGB_YUV_TABLE[(i+ 512)>>0] = 7471 * i + 0x8000; + RGB_YUV_TABLE[(i+ 768)>>0] = -11059 * i; + RGB_YUV_TABLE[(i+1024)>>0] = -21709 * i; + RGB_YUV_TABLE[(i+1280)>>0] = 32768 * i + 0x807FFF; + RGB_YUV_TABLE[(i+1536)>>0] = -27439 * i; + RGB_YUV_TABLE[(i+1792)>>0] = - 5329 * i; + } + } + + // IO functions + function writeBits(bs) + { + var value = bs[0]; + var posval = bs[1]-1; + while ( posval >= 0 ) { + if (value & (1 << posval) ) { + bytenew |= (1 << bytepos); + } + posval--; + bytepos--; + if (bytepos < 0) { + if (bytenew == 0xFF) { + writeByte(0xFF); + writeByte(0); + } + else { + writeByte(bytenew); + } + bytepos=7; + bytenew=0; + } + } + } + + function writeByte(value) + { + //byteout.push(clt[value]); // write char directly instead of converting later + byteout.push(value); + } + + function writeWord(value) + { + writeByte((value>>8)&0xFF); + writeByte((value )&0xFF); + } + + // DCT & quantization core + function fDCTQuant(data, fdtbl) + { + var d0, d1, d2, d3, d4, d5, d6, d7; + /* Pass 1: process rows. */ + var dataOff=0; + var i; + var I8 = 8; + var I64 = 64; + for (i=0; i 0.0) ? ((fDCTQuant + 0.5)|0) : ((fDCTQuant - 0.5)|0); + //outputfDCTQuant[i] = fround(fDCTQuant); + + } + return outputfDCTQuant; + } + + function writeAPP0() + { + writeWord(0xFFE0); // marker + writeWord(16); // length + writeByte(0x4A); // J + writeByte(0x46); // F + writeByte(0x49); // I + writeByte(0x46); // F + writeByte(0); // = "JFIF",'\0' + writeByte(1); // versionhi + writeByte(1); // versionlo + writeByte(0); // xyunits + writeWord(1); // xdensity + writeWord(1); // ydensity + writeByte(0); // thumbnwidth + writeByte(0); // thumbnheight + } + + function writeAPP1(exifBuffer) { + if (!exifBuffer) return; + + writeWord(0xFFE1); // APP1 marker + + if (exifBuffer[0] === 0x45 && + exifBuffer[1] === 0x78 && + exifBuffer[2] === 0x69 && + exifBuffer[3] === 0x66) { + // Buffer already starts with EXIF, just use it directly + writeWord(exifBuffer.length + 2); // length is buffer + length itself! + } else { + // Buffer doesn't start with EXIF, write it for them + writeWord(exifBuffer.length + 5 + 2); // length is buffer + EXIF\0 + length itself! + writeByte(0x45); // E + writeByte(0x78); // X + writeByte(0x69); // I + writeByte(0x66); // F + writeByte(0); // = "EXIF",'\0' + } + + for (var i = 0; i < exifBuffer.length; i++) { + writeByte(exifBuffer[i]); + } + } + + function writeSOF0(width, height) + { + writeWord(0xFFC0); // marker + writeWord(17); // length, truecolor YUV JPG + writeByte(8); // precision + writeWord(height); + writeWord(width); + writeByte(3); // nrofcomponents + writeByte(1); // IdY + writeByte(0x11); // HVY + writeByte(0); // QTY + writeByte(2); // IdU + writeByte(0x11); // HVU + writeByte(1); // QTU + writeByte(3); // IdV + writeByte(0x11); // HVV + writeByte(1); // QTV + } + + function writeDQT() + { + writeWord(0xFFDB); // marker + writeWord(132); // length + writeByte(0); + for (var i=0; i<64; i++) { + writeByte(YTable[i]); + } + writeByte(1); + for (var j=0; j<64; j++) { + writeByte(UVTable[j]); + } + } + + function writeDHT() + { + writeWord(0xFFC4); // marker + writeWord(0x01A2); // length + + writeByte(0); // HTYDCinfo + for (var i=0; i<16; i++) { + writeByte(std_dc_luminance_nrcodes[i+1]); + } + for (var j=0; j<=11; j++) { + writeByte(std_dc_luminance_values[j]); + } + + writeByte(0x10); // HTYACinfo + for (var k=0; k<16; k++) { + writeByte(std_ac_luminance_nrcodes[k+1]); + } + for (var l=0; l<=161; l++) { + writeByte(std_ac_luminance_values[l]); + } + + writeByte(1); // HTUDCinfo + for (var m=0; m<16; m++) { + writeByte(std_dc_chrominance_nrcodes[m+1]); + } + for (var n=0; n<=11; n++) { + writeByte(std_dc_chrominance_values[n]); + } + + writeByte(0x11); // HTUACinfo + for (var o=0; o<16; o++) { + writeByte(std_ac_chrominance_nrcodes[o+1]); + } + for (var p=0; p<=161; p++) { + writeByte(std_ac_chrominance_values[p]); + } + } + + function writeSOS() + { + writeWord(0xFFDA); // marker + writeWord(12); // length + writeByte(3); // nrofcomponents + writeByte(1); // IdY + writeByte(0); // HTY + writeByte(2); // IdU + writeByte(0x11); // HTU + writeByte(3); // IdV + writeByte(0x11); // HTV + writeByte(0); // Ss + writeByte(0x3f); // Se + writeByte(0); // Bf + } + + function processDU(CDU, fdtbl, DC, HTDC, HTAC){ + var EOB = HTAC[0x00]; + var M16zeroes = HTAC[0xF0]; + var pos; + var I16 = 16; + var I63 = 63; + var I64 = 64; + var DU_DCT = fDCTQuant(CDU, fdtbl); + //ZigZag reorder + for (var j=0;j0)&&(DU[end0pos]==0); end0pos--) {}; + //end0pos = first element in reverse order !=0 + if ( end0pos == 0) { + writeBits(EOB); + return DC; + } + var i = 1; + var lng; + while ( i <= end0pos ) { + var startpos = i; + for (; (DU[i]==0) && (i<=end0pos); ++i) {} + var nrzeroes = i-startpos; + if ( nrzeroes >= I16 ) { + lng = nrzeroes>>4; + for (var nrmarker=1; nrmarker <= lng; ++nrmarker) + writeBits(M16zeroes); + nrzeroes = nrzeroes&0xF; + } + pos = 32767+DU[i]; + writeBits(HTAC[(nrzeroes<<4)+category[pos]]); + writeBits(bitcode[pos]); + i++; + } + if ( end0pos != I63 ) { + writeBits(EOB); + } + return DC; + } + + function initCharLookupTable(){ + var sfcc = String.fromCharCode; + for(var i=0; i < 256; i++){ ///// ACHTUNG // 255 + clt[i] = sfcc(i); + } + } + + this.encode = function(image,quality) // image data object + { + var time_start = new Date().getTime(); + + if(quality) setQuality(quality); + + // Initialize bit writer + byteout = new Array(); + bytenew=0; + bytepos=7; + + // Add JPEG headers + writeWord(0xFFD8); // SOI + writeAPP0(); + writeAPP1(image.exifBuffer); + writeDQT(); + writeSOF0(image.width,image.height); + writeDHT(); + writeSOS(); + + + // Encode 8x8 macroblocks + var DCY=0; + var DCU=0; + var DCV=0; + + bytenew=0; + bytepos=7; + + + this.encode.displayName = "_encode_"; + + var imageData = image.data; + var width = image.width; + var height = image.height; + + var quadWidth = width*4; + var tripleWidth = width*3; + + var x, y = 0; + var r, g, b; + var start,p, col,row,pos; + while(y < height){ + x = 0; + while(x < quadWidth){ + start = quadWidth * y + x; + p = start; + col = -1; + row = 0; + + for(pos=0; pos < 64; pos++){ + row = pos >> 3;// /8 + col = ( pos & 7 ) * 4; // %8 + p = start + ( row * quadWidth ) + col; + + if(y+row >= height){ // padding bottom + p-= (quadWidth*(y+1+row-height)); + } + + if(x+col >= quadWidth){ // padding right + p-= ((x+col) - quadWidth +4) + } + + r = imageData[ p++ ]; + g = imageData[ p++ ]; + b = imageData[ p++ ]; + + + /* // calculate YUV values dynamically + YDU[pos]=((( 0.29900)*r+( 0.58700)*g+( 0.11400)*b))-128; //-0x80 + UDU[pos]=(((-0.16874)*r+(-0.33126)*g+( 0.50000)*b)); + VDU[pos]=((( 0.50000)*r+(-0.41869)*g+(-0.08131)*b)); + */ + + // use lookup table (slightly faster) + YDU[pos] = ((RGB_YUV_TABLE[r] + RGB_YUV_TABLE[(g + 256)>>0] + RGB_YUV_TABLE[(b + 512)>>0]) >> 16)-128; + UDU[pos] = ((RGB_YUV_TABLE[(r + 768)>>0] + RGB_YUV_TABLE[(g + 1024)>>0] + RGB_YUV_TABLE[(b + 1280)>>0]) >> 16)-128; + VDU[pos] = ((RGB_YUV_TABLE[(r + 1280)>>0] + RGB_YUV_TABLE[(g + 1536)>>0] + RGB_YUV_TABLE[(b + 1792)>>0]) >> 16)-128; + + } + + DCY = processDU(YDU, fdtbl_Y, DCY, YDC_HT, YAC_HT); + DCU = processDU(UDU, fdtbl_UV, DCU, UVDC_HT, UVAC_HT); + DCV = processDU(VDU, fdtbl_UV, DCV, UVDC_HT, UVAC_HT); + x+=32; + } + y+=8; + } + + + //////////////////////////////////////////////////////////////// + + // Do the bit alignment of the EOI marker + if ( bytepos >= 0 ) { + var fillbits = []; + fillbits[1] = bytepos+1; + fillbits[0] = (1<<(bytepos+1))-1; + writeBits(fillbits); + } + + writeWord(0xFFD9); //EOI + + if (false) {} + return Buffer.from(byteout); + + var jpegDataUri = 'data:image/jpeg;base64,' + btoa(byteout.join('')); + + byteout = []; + + // benchmarking + var duration = new Date().getTime() - time_start; + //console.log('Encoding time: '+ duration + 'ms'); + // + + return jpegDataUri + } + + function setQuality(quality){ + if (quality <= 0) { + quality = 1; + } + if (quality > 100) { + quality = 100; + } + + if(currentQuality == quality) return // don't recalc if unchanged + + var sf = 0; + if (quality < 50) { + sf = Math.floor(5000 / quality); + } else { + sf = Math.floor(200 - quality*2); + } + + initQuantTables(sf); + currentQuality = quality; + //console.log('Quality set to: '+quality +'%'); + } + + function init(){ + var time_start = new Date().getTime(); + if(!quality) quality = 50; + // Create tables + initCharLookupTable() + initHuffmanTbl(); + initCategoryNumber(); + initRGBYUVTable(); + + setQuality(quality); + var duration = new Date().getTime() - time_start; + //console.log('Initialization '+ duration + 'ms'); + } + + init(); + +}; + +if (true) { + module.exports = encode; +} else {} + +function encode(imgData, qu) { + if (typeof qu === 'undefined') qu = 50; + var encoder = new JPEGEncoder(qu); + var data = encoder.encode(imgData, qu); + return { + data: data, + width: imgData.width, + height: imgData.height + }; +} + +// helper function to get the imageData of an existing image on the current page. +function getImageDataFromImage(idOrElement){ + var theImg = (typeof(idOrElement)=='string')? document.getElementById(idOrElement):idOrElement; + var cvs = document.createElement('canvas'); + cvs.width = theImg.width; + cvs.height = theImg.height; + var ctx = cvs.getContext("2d"); + ctx.drawImage(theImg,0,0); + + return (ctx.getImageData(0, 0, cvs.width, cvs.height)); +} + + +/***/ }), + +/***/ 9919: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var fs = __nccwpck_require__(7147) +var url = __nccwpck_require__(7310) +var path = __nccwpck_require__(1017) +var request = __nccwpck_require__(6130) +var parseASCII = __nccwpck_require__(5807) +var parseXML = __nccwpck_require__(1199) +var readBinary = __nccwpck_require__(4563) +var mime = __nccwpck_require__(5018) +var noop = function() {} +var isBinary = __nccwpck_require__(9597) + +function parseFont(file, data, cb) { + var result, binary + + if (isBinary(data)) { + if (typeof data === 'string') data = Buffer.from(data, 'binary') + binary = true + } else data = data.toString().trim() + + try { + if (binary) result = readBinary(data) + else if (/json/.test(mime.lookup(file)) || data.charAt(0) === '{') + result = JSON.parse(data) + else if (/xml/.test(mime.lookup(file)) || data.charAt(0) === '<') + result = parseXML(data) + else result = parseASCII(data) + } catch (e) { + cb(e) + cb = noop + } + + cb(null, result) +} + +module.exports = function loadFont(opt, cb) { + cb = typeof cb === 'function' ? cb : noop + + if (typeof opt === 'string') opt = { uri: opt, url: opt } + else if (!opt) opt = {} + + var file = opt.uri || opt.url + + function handleData(err, data) { + if (err) return cb(err) + parseFont(file, data.body || data, cb) + } + + if (url.parse(file).host) { + request(opt, handleData) + } else { + fs.readFile(file, opt, handleData) + } +} + + +/***/ }), + +/***/ 9597: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var equal = __nccwpck_require__(4664) +var HEADER = Buffer.from([66, 77, 70, 3]) + +module.exports = function(buf) { + if (typeof buf === 'string') + return buf.substring(0, 3) === 'BMF' + return buf.length > 4 && equal(buf.slice(0, 4), HEADER) +} + +/***/ }), + +/***/ 7426: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/*! + * mime-db + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015-2022 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module exports. + */ + +module.exports = __nccwpck_require__(3765) + + +/***/ }), + +/***/ 3583: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; +/*! + * mime-types + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + + + +/** + * Module dependencies. + * @private + */ + +var db = __nccwpck_require__(7426) +var extname = (__nccwpck_require__(1017).extname) + +/** + * Module variables. + * @private + */ + +var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/ +var TEXT_TYPE_REGEXP = /^text\//i + +/** + * Module exports. + * @public + */ + +exports.charset = charset +exports.charsets = { lookup: charset } +exports.contentType = contentType +exports.extension = extension +exports.extensions = Object.create(null) +exports.lookup = lookup +exports.types = Object.create(null) + +// Populate the extensions/types maps +populateMaps(exports.extensions, exports.types) + +/** + * Get the default charset for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + +function charset (type) { + if (!type || typeof type !== 'string') { + return false + } + + // TODO: use media-typer + var match = EXTRACT_TYPE_REGEXP.exec(type) + var mime = match && db[match[1].toLowerCase()] + + if (mime && mime.charset) { + return mime.charset + } + + // default text/* to utf-8 + if (match && TEXT_TYPE_REGEXP.test(match[1])) { + return 'UTF-8' + } + + return false +} + +/** + * Create a full Content-Type header given a MIME type or extension. + * + * @param {string} str + * @return {boolean|string} + */ + +function contentType (str) { + // TODO: should this even be in this module? + if (!str || typeof str !== 'string') { + return false + } + + var mime = str.indexOf('/') === -1 + ? exports.lookup(str) + : str + + if (!mime) { + return false + } + + // TODO: use content-type or other module + if (mime.indexOf('charset') === -1) { + var charset = exports.charset(mime) + if (charset) mime += '; charset=' + charset.toLowerCase() + } + + return mime +} + +/** + * Get the default extension for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + +function extension (type) { + if (!type || typeof type !== 'string') { + return false + } + + // TODO: use media-typer + var match = EXTRACT_TYPE_REGEXP.exec(type) + + // get extensions + var exts = match && exports.extensions[match[1].toLowerCase()] + + if (!exts || !exts.length) { + return false + } + + return exts[0] +} + +/** + * Lookup the MIME type for a file path/extension. + * + * @param {string} path + * @return {boolean|string} + */ + +function lookup (path) { + if (!path || typeof path !== 'string') { + return false + } + + // get the extension ("ext" or ".ext" or full path) + var extension = extname('x.' + path) + .toLowerCase() + .substr(1) + + if (!extension) { + return false + } + + return exports.types[extension] || false +} + +/** + * Populate the extensions and types maps. + * @private + */ + +function populateMaps (extensions, types) { + // source preference (least -> most) + var preference = ['nginx', 'apache', undefined, 'iana'] + + Object.keys(db).forEach(function forEachMimeType (type) { + var mime = db[type] + var exts = mime.extensions + + if (!exts || !exts.length) { + return + } + + // mime -> extensions + extensions[type] = exts + + // extension -> mime + for (var i = 0; i < exts.length; i++) { + var extension = exts[i] + + if (types[extension]) { + var from = preference.indexOf(db[types[extension]].source) + var to = preference.indexOf(mime.source) + + if (types[extension] !== 'application/octet-stream' && + (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) { + // skip the remapping + continue + } + } + + // set the extension -> mime + types[extension] = type + } + }) +} + + +/***/ }), + +/***/ 5018: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var path = __nccwpck_require__(1017); +var fs = __nccwpck_require__(7147); + +function Mime() { + // Map of extension -> mime type + this.types = Object.create(null); + + // Map of mime type -> extension + this.extensions = Object.create(null); +} + +/** + * Define mimetype -> extension mappings. Each key is a mime-type that maps + * to an array of extensions associated with the type. The first extension is + * used as the default extension for the type. + * + * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']}); + * + * @param map (Object) type definitions + */ +Mime.prototype.define = function (map) { + for (var type in map) { + var exts = map[type]; + for (var i = 0; i < exts.length; i++) { + if (process.env.DEBUG_MIME && this.types[exts[i]]) { + console.warn((this._loading || "define()").replace(/.*\//, ''), 'changes "' + exts[i] + '" extension type from ' + + this.types[exts[i]] + ' to ' + type); + } + + this.types[exts[i]] = type; + } + + // Default extension is the first one we encounter + if (!this.extensions[type]) { + this.extensions[type] = exts[0]; + } + } +}; + +/** + * Load an Apache2-style ".types" file + * + * This may be called multiple times (it's expected). Where files declare + * overlapping types/extensions, the last file wins. + * + * @param file (String) path of file to load. + */ +Mime.prototype.load = function(file) { + this._loading = file; + // Read file and split into lines + var map = {}, + content = fs.readFileSync(file, 'ascii'), + lines = content.split(/[\r\n]+/); + + lines.forEach(function(line) { + // Clean up whitespace/comments, and split into fields + var fields = line.replace(/\s*#.*|^\s*|\s*$/g, '').split(/\s+/); + map[fields.shift()] = fields; + }); + + this.define(map); + + this._loading = null; +}; + +/** + * Lookup a mime type based on extension + */ +Mime.prototype.lookup = function(path, fallback) { + var ext = path.replace(/^.*[\.\/\\]/, '').toLowerCase(); + + return this.types[ext] || fallback || this.default_type; +}; + +/** + * Return file extension associated with a mime type + */ +Mime.prototype.extension = function(mimeType) { + var type = mimeType.match(/^\s*([^;\s]*)(?:;|\s|$)/)[1].toLowerCase(); + return this.extensions[type]; +}; + +// Default instance +var mime = new Mime(); + +// Define built-in types +mime.define(__nccwpck_require__(5799)); + +// Default type +mime.default_type = mime.lookup('bin'); + +// +// Additional API specific to the default instance +// + +mime.Mime = Mime; + +/** + * Lookup a charset based on mime type. + */ +mime.charsets = { + lookup: function(mimeType, fallback) { + // Assume text types are utf8 + return (/^text\/|^application\/(javascript|json)/).test(mimeType) ? 'UTF-8' : fallback; + } +}; + +module.exports = mime; + + +/***/ }), + +/***/ 6186: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var path = __nccwpck_require__(1017); +var fs = __nccwpck_require__(7147); +var _0777 = parseInt('0777', 8); + +module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; + +function mkdirP (p, opts, f, made) { + if (typeof opts === 'function') { + f = opts; + opts = {}; + } + else if (!opts || typeof opts !== 'object') { + opts = { mode: opts }; + } + + var mode = opts.mode; + var xfs = opts.fs || fs; + + if (mode === undefined) { + mode = _0777 + } + if (!made) made = null; + + var cb = f || /* istanbul ignore next */ function () {}; + p = path.resolve(p); + + xfs.mkdir(p, mode, function (er) { + if (!er) { + made = made || p; + return cb(null, made); + } + switch (er.code) { + case 'ENOENT': + /* istanbul ignore if */ + if (path.dirname(p) === p) return cb(er); + mkdirP(path.dirname(p), opts, function (er, made) { + /* istanbul ignore if */ + if (er) cb(er, made); + else mkdirP(p, opts, cb, made); + }); + break; + + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + xfs.stat(p, function (er2, stat) { + // if the stat fails, then that's super weird. + // let the original error be the failure reason. + if (er2 || !stat.isDirectory()) cb(er, made) + else cb(null, made); + }); + break; + } + }); +} + +mkdirP.sync = function sync (p, opts, made) { + if (!opts || typeof opts !== 'object') { + opts = { mode: opts }; + } + + var mode = opts.mode; + var xfs = opts.fs || fs; + + if (mode === undefined) { + mode = _0777 + } + if (!made) made = null; + + p = path.resolve(p); + + try { + xfs.mkdirSync(p, mode); + made = made || p; + } + catch (err0) { + switch (err0.code) { + case 'ENOENT' : + made = sync(path.dirname(p), opts, made); + sync(p, opts, made); + break; + + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + var stat; + try { + stat = xfs.statSync(p); + } + catch (err1) /* istanbul ignore next */ { + throw err0; + } + /* istanbul ignore if */ + if (!stat.isDirectory()) throw err0; + break; + } + } + + return made; +}; + + +/***/ }), + +/***/ 900: +/***/ ((module) => { + +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var w = d * 7; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'weeks': + case 'week': + case 'w': + return n * w; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; + } + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; + } + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; + } + if (msAbs >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); + } + return ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); +} + + +/***/ }), + +/***/ 9717: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; +// (c) Dean McNamee , 2013. +// +// https://github.com/deanm/omggif +// +// 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. +// +// omggif is a JavaScript implementation of a GIF 89a encoder and decoder, +// including animation and compression. It does not rely on any specific +// underlying system, so should run in the browser, Node, or Plask. + + + +function GifWriter(buf, width, height, gopts) { + var p = 0; + + var gopts = gopts === undefined ? { } : gopts; + var loop_count = gopts.loop === undefined ? null : gopts.loop; + var global_palette = gopts.palette === undefined ? null : gopts.palette; + + if (width <= 0 || height <= 0 || width > 65535 || height > 65535) + throw new Error("Width/Height invalid."); + + function check_palette_and_num_colors(palette) { + var num_colors = palette.length; + if (num_colors < 2 || num_colors > 256 || num_colors & (num_colors-1)) { + throw new Error( + "Invalid code/color length, must be power of 2 and 2 .. 256."); + } + return num_colors; + } + + // - Header. + buf[p++] = 0x47; buf[p++] = 0x49; buf[p++] = 0x46; // GIF + buf[p++] = 0x38; buf[p++] = 0x39; buf[p++] = 0x61; // 89a + + // Handling of Global Color Table (palette) and background index. + var gp_num_colors_pow2 = 0; + var background = 0; + if (global_palette !== null) { + var gp_num_colors = check_palette_and_num_colors(global_palette); + while (gp_num_colors >>= 1) ++gp_num_colors_pow2; + gp_num_colors = 1 << gp_num_colors_pow2; + --gp_num_colors_pow2; + if (gopts.background !== undefined) { + background = gopts.background; + if (background >= gp_num_colors) + throw new Error("Background index out of range."); + // The GIF spec states that a background index of 0 should be ignored, so + // this is probably a mistake and you really want to set it to another + // slot in the palette. But actually in the end most browsers, etc end + // up ignoring this almost completely (including for dispose background). + if (background === 0) + throw new Error("Background index explicitly passed as 0."); + } + } + + // - Logical Screen Descriptor. + // NOTE(deanm): w/h apparently ignored by implementations, but set anyway. + buf[p++] = width & 0xff; buf[p++] = width >> 8 & 0xff; + buf[p++] = height & 0xff; buf[p++] = height >> 8 & 0xff; + // NOTE: Indicates 0-bpp original color resolution (unused?). + buf[p++] = (global_palette !== null ? 0x80 : 0) | // Global Color Table Flag. + gp_num_colors_pow2; // NOTE: No sort flag (unused?). + buf[p++] = background; // Background Color Index. + buf[p++] = 0; // Pixel aspect ratio (unused?). + + // - Global Color Table + if (global_palette !== null) { + for (var i = 0, il = global_palette.length; i < il; ++i) { + var rgb = global_palette[i]; + buf[p++] = rgb >> 16 & 0xff; + buf[p++] = rgb >> 8 & 0xff; + buf[p++] = rgb & 0xff; + } + } + + if (loop_count !== null) { // Netscape block for looping. + if (loop_count < 0 || loop_count > 65535) + throw new Error("Loop count invalid.") + // Extension code, label, and length. + buf[p++] = 0x21; buf[p++] = 0xff; buf[p++] = 0x0b; + // NETSCAPE2.0 + buf[p++] = 0x4e; buf[p++] = 0x45; buf[p++] = 0x54; buf[p++] = 0x53; + buf[p++] = 0x43; buf[p++] = 0x41; buf[p++] = 0x50; buf[p++] = 0x45; + buf[p++] = 0x32; buf[p++] = 0x2e; buf[p++] = 0x30; + // Sub-block + buf[p++] = 0x03; buf[p++] = 0x01; + buf[p++] = loop_count & 0xff; buf[p++] = loop_count >> 8 & 0xff; + buf[p++] = 0x00; // Terminator. + } + + + var ended = false; + + this.addFrame = function(x, y, w, h, indexed_pixels, opts) { + if (ended === true) { --p; ended = false; } // Un-end. + + opts = opts === undefined ? { } : opts; + + // TODO(deanm): Bounds check x, y. Do they need to be within the virtual + // canvas width/height, I imagine? + if (x < 0 || y < 0 || x > 65535 || y > 65535) + throw new Error("x/y invalid.") + + if (w <= 0 || h <= 0 || w > 65535 || h > 65535) + throw new Error("Width/Height invalid.") + + if (indexed_pixels.length < w * h) + throw new Error("Not enough pixels for the frame size."); + + var using_local_palette = true; + var palette = opts.palette; + if (palette === undefined || palette === null) { + using_local_palette = false; + palette = global_palette; + } + + if (palette === undefined || palette === null) + throw new Error("Must supply either a local or global palette."); + + var num_colors = check_palette_and_num_colors(palette); + + // Compute the min_code_size (power of 2), destroying num_colors. + var min_code_size = 0; + while (num_colors >>= 1) ++min_code_size; + num_colors = 1 << min_code_size; // Now we can easily get it back. + + var delay = opts.delay === undefined ? 0 : opts.delay; + + // From the spec: + // 0 - No disposal specified. The decoder is + // not required to take any action. + // 1 - Do not dispose. The graphic is to be left + // in place. + // 2 - Restore to background color. The area used by the + // graphic must be restored to the background color. + // 3 - Restore to previous. The decoder is required to + // restore the area overwritten by the graphic with + // what was there prior to rendering the graphic. + // 4-7 - To be defined. + // NOTE(deanm): Dispose background doesn't really work, apparently most + // browsers ignore the background palette index and clear to transparency. + var disposal = opts.disposal === undefined ? 0 : opts.disposal; + if (disposal < 0 || disposal > 3) // 4-7 is reserved. + throw new Error("Disposal out of range."); + + var use_transparency = false; + var transparent_index = 0; + if (opts.transparent !== undefined && opts.transparent !== null) { + use_transparency = true; + transparent_index = opts.transparent; + if (transparent_index < 0 || transparent_index >= num_colors) + throw new Error("Transparent color index."); + } + + if (disposal !== 0 || use_transparency || delay !== 0) { + // - Graphics Control Extension + buf[p++] = 0x21; buf[p++] = 0xf9; // Extension / Label. + buf[p++] = 4; // Byte size. + + buf[p++] = disposal << 2 | (use_transparency === true ? 1 : 0); + buf[p++] = delay & 0xff; buf[p++] = delay >> 8 & 0xff; + buf[p++] = transparent_index; // Transparent color index. + buf[p++] = 0; // Block Terminator. + } + + // - Image Descriptor + buf[p++] = 0x2c; // Image Seperator. + buf[p++] = x & 0xff; buf[p++] = x >> 8 & 0xff; // Left. + buf[p++] = y & 0xff; buf[p++] = y >> 8 & 0xff; // Top. + buf[p++] = w & 0xff; buf[p++] = w >> 8 & 0xff; + buf[p++] = h & 0xff; buf[p++] = h >> 8 & 0xff; + // NOTE: No sort flag (unused?). + // TODO(deanm): Support interlace. + buf[p++] = using_local_palette === true ? (0x80 | (min_code_size-1)) : 0; + + // - Local Color Table + if (using_local_palette === true) { + for (var i = 0, il = palette.length; i < il; ++i) { + var rgb = palette[i]; + buf[p++] = rgb >> 16 & 0xff; + buf[p++] = rgb >> 8 & 0xff; + buf[p++] = rgb & 0xff; + } + } + + p = GifWriterOutputLZWCodeStream( + buf, p, min_code_size < 2 ? 2 : min_code_size, indexed_pixels); + + return p; + }; + + this.end = function() { + if (ended === false) { + buf[p++] = 0x3b; // Trailer. + ended = true; + } + return p; + }; + + this.getOutputBuffer = function() { return buf; }; + this.setOutputBuffer = function(v) { buf = v; }; + this.getOutputBufferPosition = function() { return p; }; + this.setOutputBufferPosition = function(v) { p = v; }; +} + +// Main compression routine, palette indexes -> LZW code stream. +// |index_stream| must have at least one entry. +function GifWriterOutputLZWCodeStream(buf, p, min_code_size, index_stream) { + buf[p++] = min_code_size; + var cur_subblock = p++; // Pointing at the length field. + + var clear_code = 1 << min_code_size; + var code_mask = clear_code - 1; + var eoi_code = clear_code + 1; + var next_code = eoi_code + 1; + + var cur_code_size = min_code_size + 1; // Number of bits per code. + var cur_shift = 0; + // We have at most 12-bit codes, so we should have to hold a max of 19 + // bits here (and then we would write out). + var cur = 0; + + function emit_bytes_to_buffer(bit_block_size) { + while (cur_shift >= bit_block_size) { + buf[p++] = cur & 0xff; + cur >>= 8; cur_shift -= 8; + if (p === cur_subblock + 256) { // Finished a subblock. + buf[cur_subblock] = 255; + cur_subblock = p++; + } + } + } + + function emit_code(c) { + cur |= c << cur_shift; + cur_shift += cur_code_size; + emit_bytes_to_buffer(8); + } + + // I am not an expert on the topic, and I don't want to write a thesis. + // However, it is good to outline here the basic algorithm and the few data + // structures and optimizations here that make this implementation fast. + // The basic idea behind LZW is to build a table of previously seen runs + // addressed by a short id (herein called output code). All data is + // referenced by a code, which represents one or more values from the + // original input stream. All input bytes can be referenced as the same + // value as an output code. So if you didn't want any compression, you + // could more or less just output the original bytes as codes (there are + // some details to this, but it is the idea). In order to achieve + // compression, values greater then the input range (codes can be up to + // 12-bit while input only 8-bit) represent a sequence of previously seen + // inputs. The decompressor is able to build the same mapping while + // decoding, so there is always a shared common knowledge between the + // encoding and decoder, which is also important for "timing" aspects like + // how to handle variable bit width code encoding. + // + // One obvious but very important consequence of the table system is there + // is always a unique id (at most 12-bits) to map the runs. 'A' might be + // 4, then 'AA' might be 10, 'AAA' 11, 'AAAA' 12, etc. This relationship + // can be used for an effecient lookup strategy for the code mapping. We + // need to know if a run has been seen before, and be able to map that run + // to the output code. Since we start with known unique ids (input bytes), + // and then from those build more unique ids (table entries), we can + // continue this chain (almost like a linked list) to always have small + // integer values that represent the current byte chains in the encoder. + // This means instead of tracking the input bytes (AAAABCD) to know our + // current state, we can track the table entry for AAAABC (it is guaranteed + // to exist by the nature of the algorithm) and the next character D. + // Therefor the tuple of (table_entry, byte) is guaranteed to also be + // unique. This allows us to create a simple lookup key for mapping input + // sequences to codes (table indices) without having to store or search + // any of the code sequences. So if 'AAAA' has a table entry of 12, the + // tuple of ('AAAA', K) for any input byte K will be unique, and can be our + // key. This leads to a integer value at most 20-bits, which can always + // fit in an SMI value and be used as a fast sparse array / object key. + + // Output code for the current contents of the index buffer. + var ib_code = index_stream[0] & code_mask; // Load first input index. + var code_table = { }; // Key'd on our 20-bit "tuple". + + emit_code(clear_code); // Spec says first code should be a clear code. + + // First index already loaded, process the rest of the stream. + for (var i = 1, il = index_stream.length; i < il; ++i) { + var k = index_stream[i] & code_mask; + var cur_key = ib_code << 8 | k; // (prev, k) unique tuple. + var cur_code = code_table[cur_key]; // buffer + k. + + // Check if we have to create a new code table entry. + if (cur_code === undefined) { // We don't have buffer + k. + // Emit index buffer (without k). + // This is an inline version of emit_code, because this is the core + // writing routine of the compressor (and V8 cannot inline emit_code + // because it is a closure here in a different context). Additionally + // we can call emit_byte_to_buffer less often, because we can have + // 30-bits (from our 31-bit signed SMI), and we know our codes will only + // be 12-bits, so can safely have 18-bits there without overflow. + // emit_code(ib_code); + cur |= ib_code << cur_shift; + cur_shift += cur_code_size; + while (cur_shift >= 8) { + buf[p++] = cur & 0xff; + cur >>= 8; cur_shift -= 8; + if (p === cur_subblock + 256) { // Finished a subblock. + buf[cur_subblock] = 255; + cur_subblock = p++; + } + } + + if (next_code === 4096) { // Table full, need a clear. + emit_code(clear_code); + next_code = eoi_code + 1; + cur_code_size = min_code_size + 1; + code_table = { }; + } else { // Table not full, insert a new entry. + // Increase our variable bit code sizes if necessary. This is a bit + // tricky as it is based on "timing" between the encoding and + // decoder. From the encoders perspective this should happen after + // we've already emitted the index buffer and are about to create the + // first table entry that would overflow our current code bit size. + if (next_code >= (1 << cur_code_size)) ++cur_code_size; + code_table[cur_key] = next_code++; // Insert into code table. + } + + ib_code = k; // Index buffer to single input k. + } else { + ib_code = cur_code; // Index buffer to sequence in code table. + } + } + + emit_code(ib_code); // There will still be something in the index buffer. + emit_code(eoi_code); // End Of Information. + + // Flush / finalize the sub-blocks stream to the buffer. + emit_bytes_to_buffer(1); + + // Finish the sub-blocks, writing out any unfinished lengths and + // terminating with a sub-block of length 0. If we have already started + // but not yet used a sub-block it can just become the terminator. + if (cur_subblock + 1 === p) { // Started but unused. + buf[cur_subblock] = 0; + } else { // Started and used, write length and additional terminator block. + buf[cur_subblock] = p - cur_subblock - 1; + buf[p++] = 0; + } + return p; +} + +function GifReader(buf) { + var p = 0; + + // - Header (GIF87a or GIF89a). + if (buf[p++] !== 0x47 || buf[p++] !== 0x49 || buf[p++] !== 0x46 || + buf[p++] !== 0x38 || (buf[p++]+1 & 0xfd) !== 0x38 || buf[p++] !== 0x61) { + throw new Error("Invalid GIF 87a/89a header."); + } + + // - Logical Screen Descriptor. + var width = buf[p++] | buf[p++] << 8; + var height = buf[p++] | buf[p++] << 8; + var pf0 = buf[p++]; // . + var global_palette_flag = pf0 >> 7; + var num_global_colors_pow2 = pf0 & 0x7; + var num_global_colors = 1 << (num_global_colors_pow2 + 1); + var background = buf[p++]; + buf[p++]; // Pixel aspect ratio (unused?). + + var global_palette_offset = null; + var global_palette_size = null; + + if (global_palette_flag) { + global_palette_offset = p; + global_palette_size = num_global_colors; + p += num_global_colors * 3; // Seek past palette. + } + + var no_eof = true; + + var frames = [ ]; + + var delay = 0; + var transparent_index = null; + var disposal = 0; // 0 - No disposal specified. + var loop_count = null; + + this.width = width; + this.height = height; + + while (no_eof && p < buf.length) { + switch (buf[p++]) { + case 0x21: // Graphics Control Extension Block + switch (buf[p++]) { + case 0xff: // Application specific block + // Try if it's a Netscape block (with animation loop counter). + if (buf[p ] !== 0x0b || // 21 FF already read, check block size. + // NETSCAPE2.0 + buf[p+1 ] == 0x4e && buf[p+2 ] == 0x45 && buf[p+3 ] == 0x54 && + buf[p+4 ] == 0x53 && buf[p+5 ] == 0x43 && buf[p+6 ] == 0x41 && + buf[p+7 ] == 0x50 && buf[p+8 ] == 0x45 && buf[p+9 ] == 0x32 && + buf[p+10] == 0x2e && buf[p+11] == 0x30 && + // Sub-block + buf[p+12] == 0x03 && buf[p+13] == 0x01 && buf[p+16] == 0) { + p += 14; + loop_count = buf[p++] | buf[p++] << 8; + p++; // Skip terminator. + } else { // We don't know what it is, just try to get past it. + p += 12; + while (true) { // Seek through subblocks. + var block_size = buf[p++]; + // Bad block size (ex: undefined from an out of bounds read). + if (!(block_size >= 0)) throw Error("Invalid block size"); + if (block_size === 0) break; // 0 size is terminator + p += block_size; + } + } + break; + + case 0xf9: // Graphics Control Extension + if (buf[p++] !== 0x4 || buf[p+4] !== 0) + throw new Error("Invalid graphics extension block."); + var pf1 = buf[p++]; + delay = buf[p++] | buf[p++] << 8; + transparent_index = buf[p++]; + if ((pf1 & 1) === 0) transparent_index = null; + disposal = pf1 >> 2 & 0x7; + p++; // Skip terminator. + break; + + case 0xfe: // Comment Extension. + while (true) { // Seek through subblocks. + var block_size = buf[p++]; + // Bad block size (ex: undefined from an out of bounds read). + if (!(block_size >= 0)) throw Error("Invalid block size"); + if (block_size === 0) break; // 0 size is terminator + // console.log(buf.slice(p, p+block_size).toString('ascii')); + p += block_size; + } + break; + + default: + throw new Error( + "Unknown graphic control label: 0x" + buf[p-1].toString(16)); + } + break; + + case 0x2c: // Image Descriptor. + var x = buf[p++] | buf[p++] << 8; + var y = buf[p++] | buf[p++] << 8; + var w = buf[p++] | buf[p++] << 8; + var h = buf[p++] | buf[p++] << 8; + var pf2 = buf[p++]; + var local_palette_flag = pf2 >> 7; + var interlace_flag = pf2 >> 6 & 1; + var num_local_colors_pow2 = pf2 & 0x7; + var num_local_colors = 1 << (num_local_colors_pow2 + 1); + var palette_offset = global_palette_offset; + var palette_size = global_palette_size; + var has_local_palette = false; + if (local_palette_flag) { + var has_local_palette = true; + palette_offset = p; // Override with local palette. + palette_size = num_local_colors; + p += num_local_colors * 3; // Seek past palette. + } + + var data_offset = p; + + p++; // codesize + while (true) { + var block_size = buf[p++]; + // Bad block size (ex: undefined from an out of bounds read). + if (!(block_size >= 0)) throw Error("Invalid block size"); + if (block_size === 0) break; // 0 size is terminator + p += block_size; + } + + frames.push({x: x, y: y, width: w, height: h, + has_local_palette: has_local_palette, + palette_offset: palette_offset, + palette_size: palette_size, + data_offset: data_offset, + data_length: p - data_offset, + transparent_index: transparent_index, + interlaced: !!interlace_flag, + delay: delay, + disposal: disposal}); + break; + + case 0x3b: // Trailer Marker (end of file). + no_eof = false; + break; + + default: + throw new Error("Unknown gif block: 0x" + buf[p-1].toString(16)); + break; + } + } + + this.numFrames = function() { + return frames.length; + }; + + this.loopCount = function() { + return loop_count; + }; + + this.frameInfo = function(frame_num) { + if (frame_num < 0 || frame_num >= frames.length) + throw new Error("Frame index out of range."); + return frames[frame_num]; + } + + this.decodeAndBlitFrameBGRA = function(frame_num, pixels) { + var frame = this.frameInfo(frame_num); + var num_pixels = frame.width * frame.height; + var index_stream = new Uint8Array(num_pixels); // At most 8-bit indices. + GifReaderLZWOutputIndexStream( + buf, frame.data_offset, index_stream, num_pixels); + var palette_offset = frame.palette_offset; + + // NOTE(deanm): It seems to be much faster to compare index to 256 than + // to === null. Not sure why, but CompareStub_EQ_STRICT shows up high in + // the profile, not sure if it's related to using a Uint8Array. + var trans = frame.transparent_index; + if (trans === null) trans = 256; + + // We are possibly just blitting to a portion of the entire frame. + // That is a subrect within the framerect, so the additional pixels + // must be skipped over after we finished a scanline. + var framewidth = frame.width; + var framestride = width - framewidth; + var xleft = framewidth; // Number of subrect pixels left in scanline. + + // Output indicies of the top left and bottom right corners of the subrect. + var opbeg = ((frame.y * width) + frame.x) * 4; + var opend = ((frame.y + frame.height) * width + frame.x) * 4; + var op = opbeg; + + var scanstride = framestride * 4; + + // Use scanstride to skip past the rows when interlacing. This is skipping + // 7 rows for the first two passes, then 3 then 1. + if (frame.interlaced === true) { + scanstride += width * 4 * 7; // Pass 1. + } + + var interlaceskip = 8; // Tracking the row interval in the current pass. + + for (var i = 0, il = index_stream.length; i < il; ++i) { + var index = index_stream[i]; + + if (xleft === 0) { // Beginning of new scan line + op += scanstride; + xleft = framewidth; + if (op >= opend) { // Catch the wrap to switch passes when interlacing. + scanstride = framestride * 4 + width * 4 * (interlaceskip-1); + // interlaceskip / 2 * 4 is interlaceskip << 1. + op = opbeg + (framewidth + framestride) * (interlaceskip << 1); + interlaceskip >>= 1; + } + } + + if (index === trans) { + op += 4; + } else { + var r = buf[palette_offset + index * 3]; + var g = buf[palette_offset + index * 3 + 1]; + var b = buf[palette_offset + index * 3 + 2]; + pixels[op++] = b; + pixels[op++] = g; + pixels[op++] = r; + pixels[op++] = 255; + } + --xleft; + } + }; + + // I will go to copy and paste hell one day... + this.decodeAndBlitFrameRGBA = function(frame_num, pixels) { + var frame = this.frameInfo(frame_num); + var num_pixels = frame.width * frame.height; + var index_stream = new Uint8Array(num_pixels); // At most 8-bit indices. + GifReaderLZWOutputIndexStream( + buf, frame.data_offset, index_stream, num_pixels); + var palette_offset = frame.palette_offset; + + // NOTE(deanm): It seems to be much faster to compare index to 256 than + // to === null. Not sure why, but CompareStub_EQ_STRICT shows up high in + // the profile, not sure if it's related to using a Uint8Array. + var trans = frame.transparent_index; + if (trans === null) trans = 256; + + // We are possibly just blitting to a portion of the entire frame. + // That is a subrect within the framerect, so the additional pixels + // must be skipped over after we finished a scanline. + var framewidth = frame.width; + var framestride = width - framewidth; + var xleft = framewidth; // Number of subrect pixels left in scanline. + + // Output indicies of the top left and bottom right corners of the subrect. + var opbeg = ((frame.y * width) + frame.x) * 4; + var opend = ((frame.y + frame.height) * width + frame.x) * 4; + var op = opbeg; + + var scanstride = framestride * 4; + + // Use scanstride to skip past the rows when interlacing. This is skipping + // 7 rows for the first two passes, then 3 then 1. + if (frame.interlaced === true) { + scanstride += width * 4 * 7; // Pass 1. + } + + var interlaceskip = 8; // Tracking the row interval in the current pass. + + for (var i = 0, il = index_stream.length; i < il; ++i) { + var index = index_stream[i]; + + if (xleft === 0) { // Beginning of new scan line + op += scanstride; + xleft = framewidth; + if (op >= opend) { // Catch the wrap to switch passes when interlacing. + scanstride = framestride * 4 + width * 4 * (interlaceskip-1); + // interlaceskip / 2 * 4 is interlaceskip << 1. + op = opbeg + (framewidth + framestride) * (interlaceskip << 1); + interlaceskip >>= 1; + } + } + + if (index === trans) { + op += 4; + } else { + var r = buf[palette_offset + index * 3]; + var g = buf[palette_offset + index * 3 + 1]; + var b = buf[palette_offset + index * 3 + 2]; + pixels[op++] = r; + pixels[op++] = g; + pixels[op++] = b; + pixels[op++] = 255; + } + --xleft; + } + }; +} + +function GifReaderLZWOutputIndexStream(code_stream, p, output, output_length) { + var min_code_size = code_stream[p++]; + + var clear_code = 1 << min_code_size; + var eoi_code = clear_code + 1; + var next_code = eoi_code + 1; + + var cur_code_size = min_code_size + 1; // Number of bits per code. + // NOTE: This shares the same name as the encoder, but has a different + // meaning here. Here this masks each code coming from the code stream. + var code_mask = (1 << cur_code_size) - 1; + var cur_shift = 0; + var cur = 0; + + var op = 0; // Output pointer. + + var subblock_size = code_stream[p++]; + + // TODO(deanm): Would using a TypedArray be any faster? At least it would + // solve the fast mode / backing store uncertainty. + // var code_table = Array(4096); + var code_table = new Int32Array(4096); // Can be signed, we only use 20 bits. + + var prev_code = null; // Track code-1. + + while (true) { + // Read up to two bytes, making sure we always 12-bits for max sized code. + while (cur_shift < 16) { + if (subblock_size === 0) break; // No more data to be read. + + cur |= code_stream[p++] << cur_shift; + cur_shift += 8; + + if (subblock_size === 1) { // Never let it get to 0 to hold logic above. + subblock_size = code_stream[p++]; // Next subblock. + } else { + --subblock_size; + } + } + + // TODO(deanm): We should never really get here, we should have received + // and EOI. + if (cur_shift < cur_code_size) + break; + + var code = cur & code_mask; + cur >>= cur_code_size; + cur_shift -= cur_code_size; + + // TODO(deanm): Maybe should check that the first code was a clear code, + // at least this is what you're supposed to do. But actually our encoder + // now doesn't emit a clear code first anyway. + if (code === clear_code) { + // We don't actually have to clear the table. This could be a good idea + // for greater error checking, but we don't really do any anyway. We + // will just track it with next_code and overwrite old entries. + + next_code = eoi_code + 1; + cur_code_size = min_code_size + 1; + code_mask = (1 << cur_code_size) - 1; + + // Don't update prev_code ? + prev_code = null; + continue; + } else if (code === eoi_code) { + break; + } + + // We have a similar situation as the decoder, where we want to store + // variable length entries (code table entries), but we want to do in a + // faster manner than an array of arrays. The code below stores sort of a + // linked list within the code table, and then "chases" through it to + // construct the dictionary entries. When a new entry is created, just the + // last byte is stored, and the rest (prefix) of the entry is only + // referenced by its table entry. Then the code chases through the + // prefixes until it reaches a single byte code. We have to chase twice, + // first to compute the length, and then to actually copy the data to the + // output (backwards, since we know the length). The alternative would be + // storing something in an intermediate stack, but that doesn't make any + // more sense. I implemented an approach where it also stored the length + // in the code table, although it's a bit tricky because you run out of + // bits (12 + 12 + 8), but I didn't measure much improvements (the table + // entries are generally not the long). Even when I created benchmarks for + // very long table entries the complexity did not seem worth it. + // The code table stores the prefix entry in 12 bits and then the suffix + // byte in 8 bits, so each entry is 20 bits. + + var chase_code = code < next_code ? code : prev_code; + + // Chase what we will output, either {CODE} or {CODE-1}. + var chase_length = 0; + var chase = chase_code; + while (chase > clear_code) { + chase = code_table[chase] >> 8; + ++chase_length; + } + + var k = chase; + + var op_end = op + chase_length + (chase_code !== code ? 1 : 0); + if (op_end > output_length) { + console.log("Warning, gif stream longer than expected."); + return; + } + + // Already have the first byte from the chase, might as well write it fast. + output[op++] = k; + + op += chase_length; + var b = op; // Track pointer, writing backwards. + + if (chase_code !== code) // The case of emitting {CODE-1} + k. + output[op++] = k; + + chase = chase_code; + while (chase_length--) { + chase = code_table[chase]; + output[--b] = chase & 0xff; // Write backwards. + chase >>= 8; // Pull down to the prefix code. + } + + if (prev_code !== null && next_code < 4096) { + code_table[next_code++] = prev_code << 8 | k; + // TODO(deanm): Figure out this clearing vs code growth logic better. I + // have an feeling that it should just happen somewhere else, for now it + // is awkward between when we grow past the max and then hit a clear code. + // For now just check if we hit the max 12-bits (then a clear code should + // follow, also of course encoded in 12-bits). + if (next_code >= code_mask+1 && cur_code_size < 12) { + ++cur_code_size; + code_mask = code_mask << 1 | 1; + } + } + + prev_code = code; + } + + if (op !== output_length) { + console.log("Warning, gif stream shorter than expected."); + } + + return output; +} + +// CommonJS. +try { exports.GifWriter = GifWriter; exports.GifReader = GifReader } catch(e) {} + + +/***/ }), + +/***/ 1726: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +// Top level file is just a mixin of submodules & constants + + +var assign = (__nccwpck_require__(5483).assign); + +var deflate = __nccwpck_require__(7265); +var inflate = __nccwpck_require__(6522); +var constants = __nccwpck_require__(8282); + +var pako = {}; + +assign(pako, deflate, inflate, constants); + +module.exports = pako; + + +/***/ }), + +/***/ 7265: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + + +var zlib_deflate = __nccwpck_require__(978); +var utils = __nccwpck_require__(5483); +var strings = __nccwpck_require__(2380); +var msg = __nccwpck_require__(1890); +var ZStream = __nccwpck_require__(6442); + +var toString = Object.prototype.toString; + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + +var Z_NO_FLUSH = 0; +var Z_FINISH = 4; + +var Z_OK = 0; +var Z_STREAM_END = 1; +var Z_SYNC_FLUSH = 2; + +var Z_DEFAULT_COMPRESSION = -1; + +var Z_DEFAULT_STRATEGY = 0; + +var Z_DEFLATED = 8; + +/* ===========================================================================*/ + + +/** + * class Deflate + * + * Generic JS-style wrapper for zlib calls. If you don't need + * streaming behaviour - use more simple functions: [[deflate]], + * [[deflateRaw]] and [[gzip]]. + **/ + +/* internal + * Deflate.chunks -> Array + * + * Chunks of output data, if [[Deflate#onData]] not overridden. + **/ + +/** + * Deflate.result -> Uint8Array|Array + * + * Compressed result, generated by default [[Deflate#onData]] + * and [[Deflate#onEnd]] handlers. Filled after you push last chunk + * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you + * push a chunk with explicit flush (call [[Deflate#push]] with + * `Z_SYNC_FLUSH` param). + **/ + +/** + * Deflate.err -> Number + * + * Error code after deflate finished. 0 (Z_OK) on success. + * You will not need it in real life, because deflate errors + * are possible only on wrong options or bad `onData` / `onEnd` + * custom handlers. + **/ + +/** + * Deflate.msg -> String + * + * Error message, if [[Deflate.err]] != 0 + **/ + + +/** + * new Deflate(options) + * - options (Object): zlib deflate options. + * + * Creates new deflator instance with specified params. Throws exception + * on bad params. Supported options: + * + * - `level` + * - `windowBits` + * - `memLevel` + * - `strategy` + * - `dictionary` + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Additional options, for internal needs: + * + * - `chunkSize` - size of generated data chunks (16K by default) + * - `raw` (Boolean) - do raw deflate + * - `gzip` (Boolean) - create gzip wrapper + * - `to` (String) - if equal to 'string', then result will be "binary string" + * (each char code [0..255]) + * - `header` (Object) - custom header for gzip + * - `text` (Boolean) - true if compressed data believed to be text + * - `time` (Number) - modification time, unix timestamp + * - `os` (Number) - operation system code + * - `extra` (Array) - array of bytes with extra data (max 65536) + * - `name` (String) - file name (binary string) + * - `comment` (String) - comment (binary string) + * - `hcrc` (Boolean) - true if header crc should be added + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) + * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); + * + * var deflate = new pako.Deflate({ level: 3}); + * + * deflate.push(chunk1, false); + * deflate.push(chunk2, true); // true -> last chunk + * + * if (deflate.err) { throw new Error(deflate.err); } + * + * console.log(deflate.result); + * ``` + **/ +function Deflate(options) { + if (!(this instanceof Deflate)) return new Deflate(options); + + this.options = utils.assign({ + level: Z_DEFAULT_COMPRESSION, + method: Z_DEFLATED, + chunkSize: 16384, + windowBits: 15, + memLevel: 8, + strategy: Z_DEFAULT_STRATEGY, + to: '' + }, options || {}); + + var opt = this.options; + + if (opt.raw && (opt.windowBits > 0)) { + opt.windowBits = -opt.windowBits; + } + + else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) { + opt.windowBits += 16; + } + + this.err = 0; // error code, if happens (0 = Z_OK) + this.msg = ''; // error message + this.ended = false; // used to avoid multiple onEnd() calls + this.chunks = []; // chunks of compressed data + + this.strm = new ZStream(); + this.strm.avail_out = 0; + + var status = zlib_deflate.deflateInit2( + this.strm, + opt.level, + opt.method, + opt.windowBits, + opt.memLevel, + opt.strategy + ); + + if (status !== Z_OK) { + throw new Error(msg[status]); + } + + if (opt.header) { + zlib_deflate.deflateSetHeader(this.strm, opt.header); + } + + if (opt.dictionary) { + var dict; + // Convert data if needed + if (typeof opt.dictionary === 'string') { + // If we need to compress text, change encoding to utf8. + dict = strings.string2buf(opt.dictionary); + } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') { + dict = new Uint8Array(opt.dictionary); + } else { + dict = opt.dictionary; + } + + status = zlib_deflate.deflateSetDictionary(this.strm, dict); + + if (status !== Z_OK) { + throw new Error(msg[status]); + } + + this._dict_set = true; + } +} + +/** + * Deflate#push(data[, mode]) -> Boolean + * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be + * converted to utf8 byte sequence. + * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. + * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH. + * + * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with + * new compressed chunks. Returns `true` on success. The last data block must have + * mode Z_FINISH (or `true`). That will flush internal pending buffers and call + * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you + * can use mode Z_SYNC_FLUSH, keeping the compression context. + * + * On fail call [[Deflate#onEnd]] with error code and return false. + * + * We strongly recommend to use `Uint8Array` on input for best speed (output + * array format is detected automatically). Also, don't skip last param and always + * use the same type in your code (boolean or number). That will improve JS speed. + * + * For regular `Array`-s make sure all elements are [0..255]. + * + * ##### Example + * + * ```javascript + * push(chunk, false); // push one of data chunks + * ... + * push(chunk, true); // push last chunk + * ``` + **/ +Deflate.prototype.push = function (data, mode) { + var strm = this.strm; + var chunkSize = this.options.chunkSize; + var status, _mode; + + if (this.ended) { return false; } + + _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH); + + // Convert data if needed + if (typeof data === 'string') { + // If we need to compress text, change encoding to utf8. + strm.input = strings.string2buf(data); + } else if (toString.call(data) === '[object ArrayBuffer]') { + strm.input = new Uint8Array(data); + } else { + strm.input = data; + } + + strm.next_in = 0; + strm.avail_in = strm.input.length; + + do { + if (strm.avail_out === 0) { + strm.output = new utils.Buf8(chunkSize); + strm.next_out = 0; + strm.avail_out = chunkSize; + } + status = zlib_deflate.deflate(strm, _mode); /* no bad return value */ + + if (status !== Z_STREAM_END && status !== Z_OK) { + this.onEnd(status); + this.ended = true; + return false; + } + if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) { + if (this.options.to === 'string') { + this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out))); + } else { + this.onData(utils.shrinkBuf(strm.output, strm.next_out)); + } + } + } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END); + + // Finalize on the last chunk. + if (_mode === Z_FINISH) { + status = zlib_deflate.deflateEnd(this.strm); + this.onEnd(status); + this.ended = true; + return status === Z_OK; + } + + // callback interim results if Z_SYNC_FLUSH. + if (_mode === Z_SYNC_FLUSH) { + this.onEnd(Z_OK); + strm.avail_out = 0; + return true; + } + + return true; +}; + + +/** + * Deflate#onData(chunk) -> Void + * - chunk (Uint8Array|Array|String): output data. Type of array depends + * on js engine support. When string output requested, each chunk + * will be string. + * + * By default, stores data blocks in `chunks[]` property and glue + * those in `onEnd`. Override this handler, if you need another behaviour. + **/ +Deflate.prototype.onData = function (chunk) { + this.chunks.push(chunk); +}; + + +/** + * Deflate#onEnd(status) -> Void + * - status (Number): deflate status. 0 (Z_OK) on success, + * other if not. + * + * Called once after you tell deflate that the input stream is + * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) + * or if an error happened. By default - join collected chunks, + * free memory and fill `results` / `err` properties. + **/ +Deflate.prototype.onEnd = function (status) { + // On success - join + if (status === Z_OK) { + if (this.options.to === 'string') { + this.result = this.chunks.join(''); + } else { + this.result = utils.flattenChunks(this.chunks); + } + } + this.chunks = []; + this.err = status; + this.msg = this.strm.msg; +}; + + +/** + * deflate(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to compress. + * - options (Object): zlib deflate options. + * + * Compress `data` with deflate algorithm and `options`. + * + * Supported options are: + * + * - level + * - windowBits + * - memLevel + * - strategy + * - dictionary + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Sugar (options): + * + * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify + * negative windowBits implicitly. + * - `to` (String) - if equal to 'string', then result will be "binary string" + * (each char code [0..255]) + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , data = Uint8Array([1,2,3,4,5,6,7,8,9]); + * + * console.log(pako.deflate(data)); + * ``` + **/ +function deflate(input, options) { + var deflator = new Deflate(options); + + deflator.push(input, true); + + // That will never happens, if you don't cheat with options :) + if (deflator.err) { throw deflator.msg || msg[deflator.err]; } + + return deflator.result; +} + + +/** + * deflateRaw(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to compress. + * - options (Object): zlib deflate options. + * + * The same as [[deflate]], but creates raw data, without wrapper + * (header and adler32 crc). + **/ +function deflateRaw(input, options) { + options = options || {}; + options.raw = true; + return deflate(input, options); +} + + +/** + * gzip(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to compress. + * - options (Object): zlib deflate options. + * + * The same as [[deflate]], but create gzip wrapper instead of + * deflate one. + **/ +function gzip(input, options) { + options = options || {}; + options.gzip = true; + return deflate(input, options); +} + + +exports.Deflate = Deflate; +exports.deflate = deflate; +exports.deflateRaw = deflateRaw; +exports.gzip = gzip; + + +/***/ }), + +/***/ 6522: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + + +var zlib_inflate = __nccwpck_require__(409); +var utils = __nccwpck_require__(5483); +var strings = __nccwpck_require__(2380); +var c = __nccwpck_require__(8282); +var msg = __nccwpck_require__(1890); +var ZStream = __nccwpck_require__(6442); +var GZheader = __nccwpck_require__(5105); + +var toString = Object.prototype.toString; + +/** + * class Inflate + * + * Generic JS-style wrapper for zlib calls. If you don't need + * streaming behaviour - use more simple functions: [[inflate]] + * and [[inflateRaw]]. + **/ + +/* internal + * inflate.chunks -> Array + * + * Chunks of output data, if [[Inflate#onData]] not overridden. + **/ + +/** + * Inflate.result -> Uint8Array|Array|String + * + * Uncompressed result, generated by default [[Inflate#onData]] + * and [[Inflate#onEnd]] handlers. Filled after you push last chunk + * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you + * push a chunk with explicit flush (call [[Inflate#push]] with + * `Z_SYNC_FLUSH` param). + **/ + +/** + * Inflate.err -> Number + * + * Error code after inflate finished. 0 (Z_OK) on success. + * Should be checked if broken data possible. + **/ + +/** + * Inflate.msg -> String + * + * Error message, if [[Inflate.err]] != 0 + **/ + + +/** + * new Inflate(options) + * - options (Object): zlib inflate options. + * + * Creates new inflator instance with specified params. Throws exception + * on bad params. Supported options: + * + * - `windowBits` + * - `dictionary` + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Additional options, for internal needs: + * + * - `chunkSize` - size of generated data chunks (16K by default) + * - `raw` (Boolean) - do raw inflate + * - `to` (String) - if equal to 'string', then result will be converted + * from utf8 to utf16 (javascript) string. When string output requested, + * chunk length can differ from `chunkSize`, depending on content. + * + * By default, when no options set, autodetect deflate/gzip data format via + * wrapper header. + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) + * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); + * + * var inflate = new pako.Inflate({ level: 3}); + * + * inflate.push(chunk1, false); + * inflate.push(chunk2, true); // true -> last chunk + * + * if (inflate.err) { throw new Error(inflate.err); } + * + * console.log(inflate.result); + * ``` + **/ +function Inflate(options) { + if (!(this instanceof Inflate)) return new Inflate(options); + + this.options = utils.assign({ + chunkSize: 16384, + windowBits: 0, + to: '' + }, options || {}); + + var opt = this.options; + + // Force window size for `raw` data, if not set directly, + // because we have no header for autodetect. + if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) { + opt.windowBits = -opt.windowBits; + if (opt.windowBits === 0) { opt.windowBits = -15; } + } + + // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate + if ((opt.windowBits >= 0) && (opt.windowBits < 16) && + !(options && options.windowBits)) { + opt.windowBits += 32; + } + + // Gzip header has no info about windows size, we can do autodetect only + // for deflate. So, if window size not set, force it to max when gzip possible + if ((opt.windowBits > 15) && (opt.windowBits < 48)) { + // bit 3 (16) -> gzipped data + // bit 4 (32) -> autodetect gzip/deflate + if ((opt.windowBits & 15) === 0) { + opt.windowBits |= 15; + } + } + + this.err = 0; // error code, if happens (0 = Z_OK) + this.msg = ''; // error message + this.ended = false; // used to avoid multiple onEnd() calls + this.chunks = []; // chunks of compressed data + + this.strm = new ZStream(); + this.strm.avail_out = 0; + + var status = zlib_inflate.inflateInit2( + this.strm, + opt.windowBits + ); + + if (status !== c.Z_OK) { + throw new Error(msg[status]); + } + + this.header = new GZheader(); + + zlib_inflate.inflateGetHeader(this.strm, this.header); + + // Setup dictionary + if (opt.dictionary) { + // Convert data if needed + if (typeof opt.dictionary === 'string') { + opt.dictionary = strings.string2buf(opt.dictionary); + } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') { + opt.dictionary = new Uint8Array(opt.dictionary); + } + if (opt.raw) { //In raw mode we need to set the dictionary early + status = zlib_inflate.inflateSetDictionary(this.strm, opt.dictionary); + if (status !== c.Z_OK) { + throw new Error(msg[status]); + } + } + } +} + +/** + * Inflate#push(data[, mode]) -> Boolean + * - data (Uint8Array|Array|ArrayBuffer|String): input data + * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. + * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH. + * + * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with + * new output chunks. Returns `true` on success. The last data block must have + * mode Z_FINISH (or `true`). That will flush internal pending buffers and call + * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you + * can use mode Z_SYNC_FLUSH, keeping the decompression context. + * + * On fail call [[Inflate#onEnd]] with error code and return false. + * + * We strongly recommend to use `Uint8Array` on input for best speed (output + * format is detected automatically). Also, don't skip last param and always + * use the same type in your code (boolean or number). That will improve JS speed. + * + * For regular `Array`-s make sure all elements are [0..255]. + * + * ##### Example + * + * ```javascript + * push(chunk, false); // push one of data chunks + * ... + * push(chunk, true); // push last chunk + * ``` + **/ +Inflate.prototype.push = function (data, mode) { + var strm = this.strm; + var chunkSize = this.options.chunkSize; + var dictionary = this.options.dictionary; + var status, _mode; + var next_out_utf8, tail, utf8str; + + // Flag to properly process Z_BUF_ERROR on testing inflate call + // when we check that all output data was flushed. + var allowBufError = false; + + if (this.ended) { return false; } + _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH); + + // Convert data if needed + if (typeof data === 'string') { + // Only binary strings can be decompressed on practice + strm.input = strings.binstring2buf(data); + } else if (toString.call(data) === '[object ArrayBuffer]') { + strm.input = new Uint8Array(data); + } else { + strm.input = data; + } + + strm.next_in = 0; + strm.avail_in = strm.input.length; + + do { + if (strm.avail_out === 0) { + strm.output = new utils.Buf8(chunkSize); + strm.next_out = 0; + strm.avail_out = chunkSize; + } + + status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */ + + if (status === c.Z_NEED_DICT && dictionary) { + status = zlib_inflate.inflateSetDictionary(this.strm, dictionary); + } + + if (status === c.Z_BUF_ERROR && allowBufError === true) { + status = c.Z_OK; + allowBufError = false; + } + + if (status !== c.Z_STREAM_END && status !== c.Z_OK) { + this.onEnd(status); + this.ended = true; + return false; + } + + if (strm.next_out) { + if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) { + + if (this.options.to === 'string') { + + next_out_utf8 = strings.utf8border(strm.output, strm.next_out); + + tail = strm.next_out - next_out_utf8; + utf8str = strings.buf2string(strm.output, next_out_utf8); + + // move tail + strm.next_out = tail; + strm.avail_out = chunkSize - tail; + if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); } + + this.onData(utf8str); + + } else { + this.onData(utils.shrinkBuf(strm.output, strm.next_out)); + } + } + } + + // When no more input data, we should check that internal inflate buffers + // are flushed. The only way to do it when avail_out = 0 - run one more + // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR. + // Here we set flag to process this error properly. + // + // NOTE. Deflate does not return error in this case and does not needs such + // logic. + if (strm.avail_in === 0 && strm.avail_out === 0) { + allowBufError = true; + } + + } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END); + + if (status === c.Z_STREAM_END) { + _mode = c.Z_FINISH; + } + + // Finalize on the last chunk. + if (_mode === c.Z_FINISH) { + status = zlib_inflate.inflateEnd(this.strm); + this.onEnd(status); + this.ended = true; + return status === c.Z_OK; + } + + // callback interim results if Z_SYNC_FLUSH. + if (_mode === c.Z_SYNC_FLUSH) { + this.onEnd(c.Z_OK); + strm.avail_out = 0; + return true; + } + + return true; +}; + + +/** + * Inflate#onData(chunk) -> Void + * - chunk (Uint8Array|Array|String): output data. Type of array depends + * on js engine support. When string output requested, each chunk + * will be string. + * + * By default, stores data blocks in `chunks[]` property and glue + * those in `onEnd`. Override this handler, if you need another behaviour. + **/ +Inflate.prototype.onData = function (chunk) { + this.chunks.push(chunk); +}; + + +/** + * Inflate#onEnd(status) -> Void + * - status (Number): inflate status. 0 (Z_OK) on success, + * other if not. + * + * Called either after you tell inflate that the input stream is + * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) + * or if an error happened. By default - join collected chunks, + * free memory and fill `results` / `err` properties. + **/ +Inflate.prototype.onEnd = function (status) { + // On success - join + if (status === c.Z_OK) { + if (this.options.to === 'string') { + // Glue & convert here, until we teach pako to send + // utf8 aligned strings to onData + this.result = this.chunks.join(''); + } else { + this.result = utils.flattenChunks(this.chunks); + } + } + this.chunks = []; + this.err = status; + this.msg = this.strm.msg; +}; + + +/** + * inflate(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to decompress. + * - options (Object): zlib inflate options. + * + * Decompress `data` with inflate/ungzip and `options`. Autodetect + * format via wrapper header by default. That's why we don't provide + * separate `ungzip` method. + * + * Supported options are: + * + * - windowBits + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information. + * + * Sugar (options): + * + * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify + * negative windowBits implicitly. + * - `to` (String) - if equal to 'string', then result will be converted + * from utf8 to utf16 (javascript) string. When string output requested, + * chunk length can differ from `chunkSize`, depending on content. + * + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , input = pako.deflate([1,2,3,4,5,6,7,8,9]) + * , output; + * + * try { + * output = pako.inflate(input); + * } catch (err) + * console.log(err); + * } + * ``` + **/ +function inflate(input, options) { + var inflator = new Inflate(options); + + inflator.push(input, true); + + // That will never happens, if you don't cheat with options :) + if (inflator.err) { throw inflator.msg || msg[inflator.err]; } + + return inflator.result; +} + + +/** + * inflateRaw(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to decompress. + * - options (Object): zlib inflate options. + * + * The same as [[inflate]], but creates raw data, without wrapper + * (header and adler32 crc). + **/ +function inflateRaw(input, options) { + options = options || {}; + options.raw = true; + return inflate(input, options); +} + + +/** + * ungzip(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to decompress. + * - options (Object): zlib inflate options. + * + * Just shortcut to [[inflate]], because it autodetects format + * by header.content. Done for convenience. + **/ + + +exports.Inflate = Inflate; +exports.inflate = inflate; +exports.inflateRaw = inflateRaw; +exports.ungzip = inflate; + + +/***/ }), + +/***/ 5483: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + + +var TYPED_OK = (typeof Uint8Array !== 'undefined') && + (typeof Uint16Array !== 'undefined') && + (typeof Int32Array !== 'undefined'); + +function _has(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} + +exports.assign = function (obj /*from1, from2, from3, ...*/) { + var sources = Array.prototype.slice.call(arguments, 1); + while (sources.length) { + var source = sources.shift(); + if (!source) { continue; } + + if (typeof source !== 'object') { + throw new TypeError(source + 'must be non-object'); + } + + for (var p in source) { + if (_has(source, p)) { + obj[p] = source[p]; + } + } + } + + return obj; +}; + + +// reduce buffer size, avoiding mem copy +exports.shrinkBuf = function (buf, size) { + if (buf.length === size) { return buf; } + if (buf.subarray) { return buf.subarray(0, size); } + buf.length = size; + return buf; +}; + + +var fnTyped = { + arraySet: function (dest, src, src_offs, len, dest_offs) { + if (src.subarray && dest.subarray) { + dest.set(src.subarray(src_offs, src_offs + len), dest_offs); + return; + } + // Fallback to ordinary array + for (var i = 0; i < len; i++) { + dest[dest_offs + i] = src[src_offs + i]; + } + }, + // Join array of chunks to single array. + flattenChunks: function (chunks) { + var i, l, len, pos, chunk, result; + + // calculate data length + len = 0; + for (i = 0, l = chunks.length; i < l; i++) { + len += chunks[i].length; + } + + // join chunks + result = new Uint8Array(len); + pos = 0; + for (i = 0, l = chunks.length; i < l; i++) { + chunk = chunks[i]; + result.set(chunk, pos); + pos += chunk.length; + } + + return result; + } +}; + +var fnUntyped = { + arraySet: function (dest, src, src_offs, len, dest_offs) { + for (var i = 0; i < len; i++) { + dest[dest_offs + i] = src[src_offs + i]; + } + }, + // Join array of chunks to single array. + flattenChunks: function (chunks) { + return [].concat.apply([], chunks); + } +}; + + +// Enable/Disable typed arrays use, for testing +// +exports.setTyped = function (on) { + if (on) { + exports.Buf8 = Uint8Array; + exports.Buf16 = Uint16Array; + exports.Buf32 = Int32Array; + exports.assign(exports, fnTyped); + } else { + exports.Buf8 = Array; + exports.Buf16 = Array; + exports.Buf32 = Array; + exports.assign(exports, fnUntyped); + } +}; + +exports.setTyped(TYPED_OK); + + +/***/ }), + +/***/ 2380: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; +// String encode/decode helpers + + + +var utils = __nccwpck_require__(5483); + + +// Quick check if we can use fast array to bin string conversion +// +// - apply(Array) can fail on Android 2.2 +// - apply(Uint8Array) can fail on iOS 5.1 Safari +// +var STR_APPLY_OK = true; +var STR_APPLY_UIA_OK = true; + +try { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK = false; } +try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; } + + +// Table with utf8 lengths (calculated by first byte of sequence) +// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS, +// because max possible codepoint is 0x10ffff +var _utf8len = new utils.Buf8(256); +for (var q = 0; q < 256; q++) { + _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1); +} +_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start + + +// convert string to array (typed, when possible) +exports.string2buf = function (str) { + var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; + + // count binary size + for (m_pos = 0; m_pos < str_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) { + c2 = str.charCodeAt(m_pos + 1); + if ((c2 & 0xfc00) === 0xdc00) { + c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); + m_pos++; + } + } + buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; + } + + // allocate buffer + buf = new utils.Buf8(buf_len); + + // convert + for (i = 0, m_pos = 0; i < buf_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) { + c2 = str.charCodeAt(m_pos + 1); + if ((c2 & 0xfc00) === 0xdc00) { + c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); + m_pos++; + } + } + if (c < 0x80) { + /* one byte */ + buf[i++] = c; + } else if (c < 0x800) { + /* two bytes */ + buf[i++] = 0xC0 | (c >>> 6); + buf[i++] = 0x80 | (c & 0x3f); + } else if (c < 0x10000) { + /* three bytes */ + buf[i++] = 0xE0 | (c >>> 12); + buf[i++] = 0x80 | (c >>> 6 & 0x3f); + buf[i++] = 0x80 | (c & 0x3f); + } else { + /* four bytes */ + buf[i++] = 0xf0 | (c >>> 18); + buf[i++] = 0x80 | (c >>> 12 & 0x3f); + buf[i++] = 0x80 | (c >>> 6 & 0x3f); + buf[i++] = 0x80 | (c & 0x3f); + } + } + + return buf; +}; + +// Helper (used in 2 places) +function buf2binstring(buf, len) { + // On Chrome, the arguments in a function call that are allowed is `65534`. + // If the length of the buffer is smaller than that, we can use this optimization, + // otherwise we will take a slower path. + if (len < 65534) { + if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) { + return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len)); + } + } + + var result = ''; + for (var i = 0; i < len; i++) { + result += String.fromCharCode(buf[i]); + } + return result; +} + + +// Convert byte array to binary string +exports.buf2binstring = function (buf) { + return buf2binstring(buf, buf.length); +}; + + +// Convert binary string (typed, when possible) +exports.binstring2buf = function (str) { + var buf = new utils.Buf8(str.length); + for (var i = 0, len = buf.length; i < len; i++) { + buf[i] = str.charCodeAt(i); + } + return buf; +}; + + +// convert array to string +exports.buf2string = function (buf, max) { + var i, out, c, c_len; + var len = max || buf.length; + + // Reserve max possible length (2 words per char) + // NB: by unknown reasons, Array is significantly faster for + // String.fromCharCode.apply than Uint16Array. + var utf16buf = new Array(len * 2); + + for (out = 0, i = 0; i < len;) { + c = buf[i++]; + // quick process ascii + if (c < 0x80) { utf16buf[out++] = c; continue; } + + c_len = _utf8len[c]; + // skip 5 & 6 byte codes + if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; } + + // apply mask on first byte + c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07; + // join the rest + while (c_len > 1 && i < len) { + c = (c << 6) | (buf[i++] & 0x3f); + c_len--; + } + + // terminated by end of string? + if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; } + + if (c < 0x10000) { + utf16buf[out++] = c; + } else { + c -= 0x10000; + utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff); + utf16buf[out++] = 0xdc00 | (c & 0x3ff); + } + } + + return buf2binstring(utf16buf, out); +}; + + +// Calculate max possible position in utf8 buffer, +// that will not break sequence. If that's not possible +// - (very small limits) return max size as is. +// +// buf[] - utf8 bytes array +// max - length limit (mandatory); +exports.utf8border = function (buf, max) { + var pos; + + max = max || buf.length; + if (max > buf.length) { max = buf.length; } + + // go back from last position, until start of sequence found + pos = max - 1; + while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; } + + // Very small and broken sequence, + // return max, because we should return something anyway. + if (pos < 0) { return max; } + + // If we came to start of buffer - that means buffer is too small, + // return max too. + if (pos === 0) { return max; } + + return (pos + _utf8len[buf[pos]] > max) ? pos : max; +}; + + +/***/ }), + +/***/ 6924: +/***/ ((module) => { + +"use strict"; + + +// Note: adler32 takes 12% for level 0 and 2% for level 6. +// It isn't worth it to make additional optimizations as in original. +// Small size is preferable. + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +function adler32(adler, buf, len, pos) { + var s1 = (adler & 0xffff) |0, + s2 = ((adler >>> 16) & 0xffff) |0, + n = 0; + + while (len !== 0) { + // Set limit ~ twice less than 5552, to keep + // s2 in 31-bits, because we force signed ints. + // in other case %= will fail. + n = len > 2000 ? 2000 : len; + len -= n; + + do { + s1 = (s1 + buf[pos++]) |0; + s2 = (s2 + s1) |0; + } while (--n); + + s1 %= 65521; + s2 %= 65521; + } + + return (s1 | (s2 << 16)) |0; +} + + +module.exports = adler32; + + +/***/ }), + +/***/ 8282: +/***/ ((module) => { + +"use strict"; + + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +module.exports = { + + /* Allowed flush values; see deflate() and inflate() below for details */ + Z_NO_FLUSH: 0, + Z_PARTIAL_FLUSH: 1, + Z_SYNC_FLUSH: 2, + Z_FULL_FLUSH: 3, + Z_FINISH: 4, + Z_BLOCK: 5, + Z_TREES: 6, + + /* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ + Z_OK: 0, + Z_STREAM_END: 1, + Z_NEED_DICT: 2, + Z_ERRNO: -1, + Z_STREAM_ERROR: -2, + Z_DATA_ERROR: -3, + //Z_MEM_ERROR: -4, + Z_BUF_ERROR: -5, + //Z_VERSION_ERROR: -6, + + /* compression levels */ + Z_NO_COMPRESSION: 0, + Z_BEST_SPEED: 1, + Z_BEST_COMPRESSION: 9, + Z_DEFAULT_COMPRESSION: -1, + + + Z_FILTERED: 1, + Z_HUFFMAN_ONLY: 2, + Z_RLE: 3, + Z_FIXED: 4, + Z_DEFAULT_STRATEGY: 0, + + /* Possible values of the data_type field (though see inflate()) */ + Z_BINARY: 0, + Z_TEXT: 1, + //Z_ASCII: 1, // = Z_TEXT (deprecated) + Z_UNKNOWN: 2, + + /* The deflate compression method */ + Z_DEFLATED: 8 + //Z_NULL: null // Use -1 or null inline, depending on var type +}; + + +/***/ }), + +/***/ 7242: +/***/ ((module) => { + +"use strict"; + + +// Note: we can't get significant speed boost here. +// So write code to minimize size - no pregenerated tables +// and array tools dependencies. + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +// Use ordinary array, since untyped makes no boost here +function makeTable() { + var c, table = []; + + for (var n = 0; n < 256; n++) { + c = n; + for (var k = 0; k < 8; k++) { + c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); + } + table[n] = c; + } + + return table; +} + +// Create table on load. Just 255 signed longs. Not a problem. +var crcTable = makeTable(); + + +function crc32(crc, buf, len, pos) { + var t = crcTable, + end = pos + len; + + crc ^= -1; + + for (var i = pos; i < end; i++) { + crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; + } + + return (crc ^ (-1)); // >>> 0; +} + + +module.exports = crc32; + + +/***/ }), + +/***/ 978: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +var utils = __nccwpck_require__(5483); +var trees = __nccwpck_require__(8754); +var adler32 = __nccwpck_require__(6924); +var crc32 = __nccwpck_require__(7242); +var msg = __nccwpck_require__(1890); + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +/* Allowed flush values; see deflate() and inflate() below for details */ +var Z_NO_FLUSH = 0; +var Z_PARTIAL_FLUSH = 1; +//var Z_SYNC_FLUSH = 2; +var Z_FULL_FLUSH = 3; +var Z_FINISH = 4; +var Z_BLOCK = 5; +//var Z_TREES = 6; + + +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ +var Z_OK = 0; +var Z_STREAM_END = 1; +//var Z_NEED_DICT = 2; +//var Z_ERRNO = -1; +var Z_STREAM_ERROR = -2; +var Z_DATA_ERROR = -3; +//var Z_MEM_ERROR = -4; +var Z_BUF_ERROR = -5; +//var Z_VERSION_ERROR = -6; + + +/* compression levels */ +//var Z_NO_COMPRESSION = 0; +//var Z_BEST_SPEED = 1; +//var Z_BEST_COMPRESSION = 9; +var Z_DEFAULT_COMPRESSION = -1; + + +var Z_FILTERED = 1; +var Z_HUFFMAN_ONLY = 2; +var Z_RLE = 3; +var Z_FIXED = 4; +var Z_DEFAULT_STRATEGY = 0; + +/* Possible values of the data_type field (though see inflate()) */ +//var Z_BINARY = 0; +//var Z_TEXT = 1; +//var Z_ASCII = 1; // = Z_TEXT +var Z_UNKNOWN = 2; + + +/* The deflate compression method */ +var Z_DEFLATED = 8; + +/*============================================================================*/ + + +var MAX_MEM_LEVEL = 9; +/* Maximum value for memLevel in deflateInit2 */ +var MAX_WBITS = 15; +/* 32K LZ77 window */ +var DEF_MEM_LEVEL = 8; + + +var LENGTH_CODES = 29; +/* number of length codes, not counting the special END_BLOCK code */ +var LITERALS = 256; +/* number of literal bytes 0..255 */ +var L_CODES = LITERALS + 1 + LENGTH_CODES; +/* number of Literal or Length codes, including the END_BLOCK code */ +var D_CODES = 30; +/* number of distance codes */ +var BL_CODES = 19; +/* number of codes used to transfer the bit lengths */ +var HEAP_SIZE = 2 * L_CODES + 1; +/* maximum heap size */ +var MAX_BITS = 15; +/* All codes must not exceed MAX_BITS bits */ + +var MIN_MATCH = 3; +var MAX_MATCH = 258; +var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1); + +var PRESET_DICT = 0x20; + +var INIT_STATE = 42; +var EXTRA_STATE = 69; +var NAME_STATE = 73; +var COMMENT_STATE = 91; +var HCRC_STATE = 103; +var BUSY_STATE = 113; +var FINISH_STATE = 666; + +var BS_NEED_MORE = 1; /* block not completed, need more input or more output */ +var BS_BLOCK_DONE = 2; /* block flush performed */ +var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ +var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ + +var OS_CODE = 0x03; // Unix :) . Don't detect, use this default. + +function err(strm, errorCode) { + strm.msg = msg[errorCode]; + return errorCode; +} + +function rank(f) { + return ((f) << 1) - ((f) > 4 ? 9 : 0); +} + +function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } + + +/* ========================================================================= + * Flush as much pending output as possible. All deflate() output goes + * through this function so some applications may wish to modify it + * to avoid allocating a large strm->output buffer and copying into it. + * (See also read_buf()). + */ +function flush_pending(strm) { + var s = strm.state; + + //_tr_flush_bits(s); + var len = s.pending; + if (len > strm.avail_out) { + len = strm.avail_out; + } + if (len === 0) { return; } + + utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); + strm.next_out += len; + s.pending_out += len; + strm.total_out += len; + strm.avail_out -= len; + s.pending -= len; + if (s.pending === 0) { + s.pending_out = 0; + } +} + + +function flush_block_only(s, last) { + trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); + s.block_start = s.strstart; + flush_pending(s.strm); +} + + +function put_byte(s, b) { + s.pending_buf[s.pending++] = b; +} + + +/* ========================================================================= + * Put a short in the pending buffer. The 16-bit value is put in MSB order. + * IN assertion: the stream state is correct and there is enough room in + * pending_buf. + */ +function putShortMSB(s, b) { +// put_byte(s, (Byte)(b >> 8)); +// put_byte(s, (Byte)(b & 0xff)); + s.pending_buf[s.pending++] = (b >>> 8) & 0xff; + s.pending_buf[s.pending++] = b & 0xff; +} + + +/* =========================================================================== + * Read a new buffer from the current input stream, update the adler32 + * and total number of bytes read. All deflate() input goes through + * this function so some applications may wish to modify it to avoid + * allocating a large strm->input buffer and copying from it. + * (See also flush_pending()). + */ +function read_buf(strm, buf, start, size) { + var len = strm.avail_in; + + if (len > size) { len = size; } + if (len === 0) { return 0; } + + strm.avail_in -= len; + + // zmemcpy(buf, strm->next_in, len); + utils.arraySet(buf, strm.input, strm.next_in, len, start); + if (strm.state.wrap === 1) { + strm.adler = adler32(strm.adler, buf, len, start); + } + + else if (strm.state.wrap === 2) { + strm.adler = crc32(strm.adler, buf, len, start); + } + + strm.next_in += len; + strm.total_in += len; + + return len; +} + + +/* =========================================================================== + * Set match_start to the longest match starting at the given string and + * return its length. Matches shorter or equal to prev_length are discarded, + * in which case the result is equal to prev_length and match_start is + * garbage. + * IN assertions: cur_match is the head of the hash chain for the current + * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 + * OUT assertion: the match length is not greater than s->lookahead. + */ +function longest_match(s, cur_match) { + var chain_length = s.max_chain_length; /* max hash chain length */ + var scan = s.strstart; /* current string */ + var match; /* matched string */ + var len; /* length of current match */ + var best_len = s.prev_length; /* best match length so far */ + var nice_match = s.nice_match; /* stop if match long enough */ + var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? + s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/; + + var _win = s.window; // shortcut + + var wmask = s.w_mask; + var prev = s.prev; + + /* Stop when cur_match becomes <= limit. To simplify the code, + * we prevent matches with the string of window index 0. + */ + + var strend = s.strstart + MAX_MATCH; + var scan_end1 = _win[scan + best_len - 1]; + var scan_end = _win[scan + best_len]; + + /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + + /* Do not waste too much time if we already have a good match: */ + if (s.prev_length >= s.good_match) { + chain_length >>= 2; + } + /* Do not look for matches beyond the end of the input. This is necessary + * to make deflate deterministic. + */ + if (nice_match > s.lookahead) { nice_match = s.lookahead; } + + // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); + + do { + // Assert(cur_match < s->strstart, "no future"); + match = cur_match; + + /* Skip to next match if the match length cannot increase + * or if the match length is less than 2. Note that the checks below + * for insufficient lookahead only occur occasionally for performance + * reasons. Therefore uninitialized memory will be accessed, and + * conditional jumps will be made that depend on those values. + * However the length of the match is limited to the lookahead, so + * the output of deflate is not affected by the uninitialized values. + */ + + if (_win[match + best_len] !== scan_end || + _win[match + best_len - 1] !== scan_end1 || + _win[match] !== _win[scan] || + _win[++match] !== _win[scan + 1]) { + continue; + } + + /* The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2; + match++; + // Assert(*scan == *match, "match[2]?"); + + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + /*jshint noempty:false*/ + } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + scan < strend); + + // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + + len = MAX_MATCH - (strend - scan); + scan = strend - MAX_MATCH; + + if (len > best_len) { + s.match_start = cur_match; + best_len = len; + if (len >= nice_match) { + break; + } + scan_end1 = _win[scan + best_len - 1]; + scan_end = _win[scan + best_len]; + } + } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); + + if (best_len <= s.lookahead) { + return best_len; + } + return s.lookahead; +} + + +/* =========================================================================== + * Fill the window when the lookahead becomes insufficient. + * Updates strstart and lookahead. + * + * IN assertion: lookahead < MIN_LOOKAHEAD + * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD + * At least one byte has been read, or avail_in == 0; reads are + * performed for at least two bytes (required for the zip translate_eol + * option -- not supported here). + */ +function fill_window(s) { + var _w_size = s.w_size; + var p, n, m, more, str; + + //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); + + do { + more = s.window_size - s.lookahead - s.strstart; + + // JS ints have 32 bit, block below not needed + /* Deal with !@#$% 64K limit: */ + //if (sizeof(int) <= 2) { + // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { + // more = wsize; + // + // } else if (more == (unsigned)(-1)) { + // /* Very unlikely, but possible on 16 bit machine if + // * strstart == 0 && lookahead == 1 (input done a byte at time) + // */ + // more--; + // } + //} + + + /* If the window is almost full and there is insufficient lookahead, + * move the upper half to the lower one to make room in the upper half. + */ + if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { + + utils.arraySet(s.window, s.window, _w_size, _w_size, 0); + s.match_start -= _w_size; + s.strstart -= _w_size; + /* we now have strstart >= MAX_DIST */ + s.block_start -= _w_size; + + /* Slide the hash table (could be avoided with 32 bit values + at the expense of memory usage). We slide even when level == 0 + to keep the hash table consistent if we switch back to level > 0 + later. (Using level 0 permanently is not an optimal usage of + zlib, so we don't care about this pathological case.) + */ + + n = s.hash_size; + p = n; + do { + m = s.head[--p]; + s.head[p] = (m >= _w_size ? m - _w_size : 0); + } while (--n); + + n = _w_size; + p = n; + do { + m = s.prev[--p]; + s.prev[p] = (m >= _w_size ? m - _w_size : 0); + /* If n is not on any hash chain, prev[n] is garbage but + * its value will never be used. + */ + } while (--n); + + more += _w_size; + } + if (s.strm.avail_in === 0) { + break; + } + + /* If there was no sliding: + * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && + * more == window_size - lookahead - strstart + * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) + * => more >= window_size - 2*WSIZE + 2 + * In the BIG_MEM or MMAP case (not yet supported), + * window_size == input_size + MIN_LOOKAHEAD && + * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. + * Otherwise, window_size == 2*WSIZE so more >= 2. + * If there was sliding, more >= WSIZE. So in all cases, more >= 2. + */ + //Assert(more >= 2, "more < 2"); + n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); + s.lookahead += n; + + /* Initialize the hash value now that we have some input: */ + if (s.lookahead + s.insert >= MIN_MATCH) { + str = s.strstart - s.insert; + s.ins_h = s.window[str]; + + /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask; +//#if MIN_MATCH != 3 +// Call update_hash() MIN_MATCH-3 more times +//#endif + while (s.insert) { + /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; + + s.prev[str & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = str; + str++; + s.insert--; + if (s.lookahead + s.insert < MIN_MATCH) { + break; + } + } + } + /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, + * but this is not important since only literal bytes will be emitted. + */ + + } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); + + /* If the WIN_INIT bytes after the end of the current data have never been + * written, then zero those bytes in order to avoid memory check reports of + * the use of uninitialized (or uninitialised as Julian writes) bytes by + * the longest match routines. Update the high water mark for the next + * time through here. WIN_INIT is set to MAX_MATCH since the longest match + * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. + */ +// if (s.high_water < s.window_size) { +// var curr = s.strstart + s.lookahead; +// var init = 0; +// +// if (s.high_water < curr) { +// /* Previous high water mark below current data -- zero WIN_INIT +// * bytes or up to end of window, whichever is less. +// */ +// init = s.window_size - curr; +// if (init > WIN_INIT) +// init = WIN_INIT; +// zmemzero(s->window + curr, (unsigned)init); +// s->high_water = curr + init; +// } +// else if (s->high_water < (ulg)curr + WIN_INIT) { +// /* High water mark at or above current data, but below current data +// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up +// * to end of window, whichever is less. +// */ +// init = (ulg)curr + WIN_INIT - s->high_water; +// if (init > s->window_size - s->high_water) +// init = s->window_size - s->high_water; +// zmemzero(s->window + s->high_water, (unsigned)init); +// s->high_water += init; +// } +// } +// +// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, +// "not enough room for search"); +} + +/* =========================================================================== + * Copy without compression as much as possible from the input stream, return + * the current block state. + * This function does not insert new strings in the dictionary since + * uncompressible data is probably not useful. This function is used + * only for the level=0 compression option. + * NOTE: this function should be optimized to avoid extra copying from + * window to pending_buf. + */ +function deflate_stored(s, flush) { + /* Stored blocks are limited to 0xffff bytes, pending_buf is limited + * to pending_buf_size, and each stored block has a 5 byte header: + */ + var max_block_size = 0xffff; + + if (max_block_size > s.pending_buf_size - 5) { + max_block_size = s.pending_buf_size - 5; + } + + /* Copy as much as possible from input to output: */ + for (;;) { + /* Fill the window as much as possible: */ + if (s.lookahead <= 1) { + + //Assert(s->strstart < s->w_size+MAX_DIST(s) || + // s->block_start >= (long)s->w_size, "slide too late"); +// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || +// s.block_start >= s.w_size)) { +// throw new Error("slide too late"); +// } + + fill_window(s); + if (s.lookahead === 0 && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + + if (s.lookahead === 0) { + break; + } + /* flush the current block */ + } + //Assert(s->block_start >= 0L, "block gone"); +// if (s.block_start < 0) throw new Error("block gone"); + + s.strstart += s.lookahead; + s.lookahead = 0; + + /* Emit a stored block if pending_buf will be full: */ + var max_start = s.block_start + max_block_size; + + if (s.strstart === 0 || s.strstart >= max_start) { + /* strstart == 0 is possible when wraparound on 16-bit machine */ + s.lookahead = s.strstart - max_start; + s.strstart = max_start; + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + + + } + /* Flush if we may have to slide, otherwise block_start may become + * negative and the data will be gone: + */ + if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + + s.insert = 0; + + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + + if (s.strstart > s.block_start) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + return BS_NEED_MORE; +} + +/* =========================================================================== + * Compress as much as possible from the input stream, return the current + * block state. + * This function does not perform lazy evaluation of matches and inserts + * new strings in the dictionary only for unmatched strings or for short + * matches. It is used only for the fast compression options. + */ +function deflate_fast(s, flush) { + var hash_head; /* head of the hash chain */ + var bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; /* flush the current block */ + } + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = 0/*NIL*/; + if (s.lookahead >= MIN_MATCH) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + + /* Find the longest match, discarding those <= prev_length. + * At this point we have always match_length < MIN_MATCH + */ + if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s.match_length = longest_match(s, hash_head); + /* longest_match() sets match_start */ + } + if (s.match_length >= MIN_MATCH) { + // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only + + /*** _tr_tally_dist(s, s.strstart - s.match_start, + s.match_length - MIN_MATCH, bflush); ***/ + bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH); + + s.lookahead -= s.match_length; + + /* Insert new strings in the hash table only if the match length + * is not too large. This saves time but degrades compression. + */ + if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) { + s.match_length--; /* string at strstart already in table */ + do { + s.strstart++; + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + /* strstart never exceeds WSIZE-MAX_MATCH, so there are + * always MIN_MATCH bytes ahead. + */ + } while (--s.match_length !== 0); + s.strstart++; + } else + { + s.strstart += s.match_length; + s.match_length = 0; + s.ins_h = s.window[s.strstart]; + /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask; + +//#if MIN_MATCH != 3 +// Call UPDATE_HASH() MIN_MATCH-3 more times +//#endif + /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not + * matter since it will be recomputed at next deflate call. + */ + } + } else { + /* No match, output a literal byte */ + //Tracevv((stderr,"%c", s.window[s.strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1); + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* =========================================================================== + * Same as above, but achieves better compression. We use a lazy + * evaluation for matches: a match is finally adopted only if there is + * no better match at the next window position. + */ +function deflate_slow(s, flush) { + var hash_head; /* head of hash chain */ + var bflush; /* set if current block must be flushed */ + + var max_insert; + + /* Process the input block. */ + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { break; } /* flush the current block */ + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = 0/*NIL*/; + if (s.lookahead >= MIN_MATCH) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + + /* Find the longest match, discarding those <= prev_length. + */ + s.prev_length = s.match_length; + s.prev_match = s.match_start; + s.match_length = MIN_MATCH - 1; + + if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match && + s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s.match_length = longest_match(s, hash_head); + /* longest_match() sets match_start */ + + if (s.match_length <= 5 && + (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) { + + /* If prev_match is also MIN_MATCH, match_start is garbage + * but we will ignore the current match anyway. + */ + s.match_length = MIN_MATCH - 1; + } + } + /* If there was a match at the previous step and the current + * match is not better, output the previous match: + */ + if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) { + max_insert = s.strstart + s.lookahead - MIN_MATCH; + /* Do not insert strings in hash table beyond this. */ + + //check_match(s, s.strstart-1, s.prev_match, s.prev_length); + + /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, + s.prev_length - MIN_MATCH, bflush);***/ + bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH); + /* Insert in hash table all strings up to the end of the match. + * strstart-1 and strstart are already inserted. If there is not + * enough lookahead, the last two strings are not inserted in + * the hash table. + */ + s.lookahead -= s.prev_length - 1; + s.prev_length -= 2; + do { + if (++s.strstart <= max_insert) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + } while (--s.prev_length !== 0); + s.match_available = 0; + s.match_length = MIN_MATCH - 1; + s.strstart++; + + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + } else if (s.match_available) { + /* If there was no match at the previous position, output a + * single literal. If there was a match but the current match + * is longer, truncate the previous match to a single literal. + */ + //Tracevv((stderr,"%c", s->window[s->strstart-1])); + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); + + if (bflush) { + /*** FLUSH_BLOCK_ONLY(s, 0) ***/ + flush_block_only(s, false); + /***/ + } + s.strstart++; + s.lookahead--; + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } else { + /* There is no previous match to compare with, wait for + * the next step to decide. + */ + s.match_available = 1; + s.strstart++; + s.lookahead--; + } + } + //Assert (flush != Z_NO_FLUSH, "no flush?"); + if (s.match_available) { + //Tracevv((stderr,"%c", s->window[s->strstart-1])); + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); + + s.match_available = 0; + } + s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + return BS_BLOCK_DONE; +} + + +/* =========================================================================== + * For Z_RLE, simply look for runs of bytes, generate matches only of distance + * one. Do not maintain a hash table. (It will be regenerated if this run of + * deflate switches away from Z_RLE.) + */ +function deflate_rle(s, flush) { + var bflush; /* set if current block must be flushed */ + var prev; /* byte at distance one to match */ + var scan, strend; /* scan goes up to strend for length of run */ + + var _win = s.window; + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the longest run, plus one for the unrolled loop. + */ + if (s.lookahead <= MAX_MATCH) { + fill_window(s); + if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { break; } /* flush the current block */ + } + + /* See how many times the previous byte repeats */ + s.match_length = 0; + if (s.lookahead >= MIN_MATCH && s.strstart > 0) { + scan = s.strstart - 1; + prev = _win[scan]; + if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { + strend = s.strstart + MAX_MATCH; + do { + /*jshint noempty:false*/ + } while (prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + scan < strend); + s.match_length = MAX_MATCH - (strend - scan); + if (s.match_length > s.lookahead) { + s.match_length = s.lookahead; + } + } + //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); + } + + /* Emit match if have run of MIN_MATCH or longer, else emit literal */ + if (s.match_length >= MIN_MATCH) { + //check_match(s, s.strstart, s.strstart - 1, s.match_length); + + /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ + bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH); + + s.lookahead -= s.match_length; + s.strstart += s.match_length; + s.match_length = 0; + } else { + /* No match, output a literal byte */ + //Tracevv((stderr,"%c", s->window[s->strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = 0; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* =========================================================================== + * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. + * (It will be regenerated if this run of deflate switches away from Huffman.) + */ +function deflate_huff(s, flush) { + var bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we have a literal to write. */ + if (s.lookahead === 0) { + fill_window(s); + if (s.lookahead === 0) { + if (flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + break; /* flush the current block */ + } + } + + /* Output a literal byte */ + s.match_length = 0; + //Tracevv((stderr,"%c", s->window[s->strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + s.lookahead--; + s.strstart++; + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = 0; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* Values for max_lazy_match, good_match and max_chain_length, depending on + * the desired pack level (0..9). The values given below have been tuned to + * exclude worst case performance for pathological files. Better values may be + * found for specific files. + */ +function Config(good_length, max_lazy, nice_length, max_chain, func) { + this.good_length = good_length; + this.max_lazy = max_lazy; + this.nice_length = nice_length; + this.max_chain = max_chain; + this.func = func; +} + +var configuration_table; + +configuration_table = [ + /* good lazy nice chain */ + new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */ + new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */ + new Config(4, 5, 16, 8, deflate_fast), /* 2 */ + new Config(4, 6, 32, 32, deflate_fast), /* 3 */ + + new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */ + new Config(8, 16, 32, 32, deflate_slow), /* 5 */ + new Config(8, 16, 128, 128, deflate_slow), /* 6 */ + new Config(8, 32, 128, 256, deflate_slow), /* 7 */ + new Config(32, 128, 258, 1024, deflate_slow), /* 8 */ + new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */ +]; + + +/* =========================================================================== + * Initialize the "longest match" routines for a new zlib stream + */ +function lm_init(s) { + s.window_size = 2 * s.w_size; + + /*** CLEAR_HASH(s); ***/ + zero(s.head); // Fill with NIL (= 0); + + /* Set the default configuration parameters: + */ + s.max_lazy_match = configuration_table[s.level].max_lazy; + s.good_match = configuration_table[s.level].good_length; + s.nice_match = configuration_table[s.level].nice_length; + s.max_chain_length = configuration_table[s.level].max_chain; + + s.strstart = 0; + s.block_start = 0; + s.lookahead = 0; + s.insert = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + s.ins_h = 0; +} + + +function DeflateState() { + this.strm = null; /* pointer back to this zlib stream */ + this.status = 0; /* as the name implies */ + this.pending_buf = null; /* output still pending */ + this.pending_buf_size = 0; /* size of pending_buf */ + this.pending_out = 0; /* next pending byte to output to the stream */ + this.pending = 0; /* nb of bytes in the pending buffer */ + this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ + this.gzhead = null; /* gzip header information to write */ + this.gzindex = 0; /* where in extra, name, or comment */ + this.method = Z_DEFLATED; /* can only be DEFLATED */ + this.last_flush = -1; /* value of flush param for previous deflate call */ + + this.w_size = 0; /* LZ77 window size (32K by default) */ + this.w_bits = 0; /* log2(w_size) (8..16) */ + this.w_mask = 0; /* w_size - 1 */ + + this.window = null; + /* Sliding window. Input bytes are read into the second half of the window, + * and move to the first half later to keep a dictionary of at least wSize + * bytes. With this organization, matches are limited to a distance of + * wSize-MAX_MATCH bytes, but this ensures that IO is always + * performed with a length multiple of the block size. + */ + + this.window_size = 0; + /* Actual size of window: 2*wSize, except when the user input buffer + * is directly used as sliding window. + */ + + this.prev = null; + /* Link to older string with same hash index. To limit the size of this + * array to 64K, this link is maintained only for the last 32K strings. + * An index in this array is thus a window index modulo 32K. + */ + + this.head = null; /* Heads of the hash chains or NIL. */ + + this.ins_h = 0; /* hash index of string to be inserted */ + this.hash_size = 0; /* number of elements in hash table */ + this.hash_bits = 0; /* log2(hash_size) */ + this.hash_mask = 0; /* hash_size-1 */ + + this.hash_shift = 0; + /* Number of bits by which ins_h must be shifted at each input + * step. It must be such that after MIN_MATCH steps, the oldest + * byte no longer takes part in the hash key, that is: + * hash_shift * MIN_MATCH >= hash_bits + */ + + this.block_start = 0; + /* Window position at the beginning of the current output block. Gets + * negative when the window is moved backwards. + */ + + this.match_length = 0; /* length of best match */ + this.prev_match = 0; /* previous match */ + this.match_available = 0; /* set if previous match exists */ + this.strstart = 0; /* start of string to insert */ + this.match_start = 0; /* start of matching string */ + this.lookahead = 0; /* number of valid bytes ahead in window */ + + this.prev_length = 0; + /* Length of the best match at previous step. Matches not greater than this + * are discarded. This is used in the lazy match evaluation. + */ + + this.max_chain_length = 0; + /* To speed up deflation, hash chains are never searched beyond this + * length. A higher limit improves compression ratio but degrades the + * speed. + */ + + this.max_lazy_match = 0; + /* Attempt to find a better match only when the current match is strictly + * smaller than this value. This mechanism is used only for compression + * levels >= 4. + */ + // That's alias to max_lazy_match, don't use directly + //this.max_insert_length = 0; + /* Insert new strings in the hash table only if the match length is not + * greater than this length. This saves time but degrades compression. + * max_insert_length is used only for compression levels <= 3. + */ + + this.level = 0; /* compression level (1..9) */ + this.strategy = 0; /* favor or force Huffman coding*/ + + this.good_match = 0; + /* Use a faster search when the previous match is longer than this */ + + this.nice_match = 0; /* Stop searching when current match exceeds this */ + + /* used by trees.c: */ + + /* Didn't use ct_data typedef below to suppress compiler warning */ + + // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ + // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ + // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ + + // Use flat array of DOUBLE size, with interleaved fata, + // because JS does not support effective + this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2); + this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2); + this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2); + zero(this.dyn_ltree); + zero(this.dyn_dtree); + zero(this.bl_tree); + + this.l_desc = null; /* desc. for literal tree */ + this.d_desc = null; /* desc. for distance tree */ + this.bl_desc = null; /* desc. for bit length tree */ + + //ush bl_count[MAX_BITS+1]; + this.bl_count = new utils.Buf16(MAX_BITS + 1); + /* number of codes at each bit length for an optimal tree */ + + //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ + this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */ + zero(this.heap); + + this.heap_len = 0; /* number of elements in the heap */ + this.heap_max = 0; /* element of largest frequency */ + /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. + * The same heap array is used to build all trees. + */ + + this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1]; + zero(this.depth); + /* Depth of each subtree used as tie breaker for trees of equal frequency + */ + + this.l_buf = 0; /* buffer index for literals or lengths */ + + this.lit_bufsize = 0; + /* Size of match buffer for literals/lengths. There are 4 reasons for + * limiting lit_bufsize to 64K: + * - frequencies can be kept in 16 bit counters + * - if compression is not successful for the first block, all input + * data is still in the window so we can still emit a stored block even + * when input comes from standard input. (This can also be done for + * all blocks if lit_bufsize is not greater than 32K.) + * - if compression is not successful for a file smaller than 64K, we can + * even emit a stored file instead of a stored block (saving 5 bytes). + * This is applicable only for zip (not gzip or zlib). + * - creating new Huffman trees less frequently may not provide fast + * adaptation to changes in the input data statistics. (Take for + * example a binary file with poorly compressible code followed by + * a highly compressible string table.) Smaller buffer sizes give + * fast adaptation but have of course the overhead of transmitting + * trees more frequently. + * - I can't count above 4 + */ + + this.last_lit = 0; /* running index in l_buf */ + + this.d_buf = 0; + /* Buffer index for distances. To simplify the code, d_buf and l_buf have + * the same number of elements. To use different lengths, an extra flag + * array would be necessary. + */ + + this.opt_len = 0; /* bit length of current block with optimal trees */ + this.static_len = 0; /* bit length of current block with static trees */ + this.matches = 0; /* number of string matches in current block */ + this.insert = 0; /* bytes at end of window left to insert */ + + + this.bi_buf = 0; + /* Output buffer. bits are inserted starting at the bottom (least + * significant bits). + */ + this.bi_valid = 0; + /* Number of valid bits in bi_buf. All bits above the last valid bit + * are always zero. + */ + + // Used for window memory init. We safely ignore it for JS. That makes + // sense only for pointers and memory check tools. + //this.high_water = 0; + /* High water mark offset in window for initialized bytes -- bytes above + * this are set to zero in order to avoid memory check warnings when + * longest match routines access bytes past the input. This is then + * updated to the new high water mark. + */ +} + + +function deflateResetKeep(strm) { + var s; + + if (!strm || !strm.state) { + return err(strm, Z_STREAM_ERROR); + } + + strm.total_in = strm.total_out = 0; + strm.data_type = Z_UNKNOWN; + + s = strm.state; + s.pending = 0; + s.pending_out = 0; + + if (s.wrap < 0) { + s.wrap = -s.wrap; + /* was made negative by deflate(..., Z_FINISH); */ + } + s.status = (s.wrap ? INIT_STATE : BUSY_STATE); + strm.adler = (s.wrap === 2) ? + 0 // crc32(0, Z_NULL, 0) + : + 1; // adler32(0, Z_NULL, 0) + s.last_flush = Z_NO_FLUSH; + trees._tr_init(s); + return Z_OK; +} + + +function deflateReset(strm) { + var ret = deflateResetKeep(strm); + if (ret === Z_OK) { + lm_init(strm.state); + } + return ret; +} + + +function deflateSetHeader(strm, head) { + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; } + strm.state.gzhead = head; + return Z_OK; +} + + +function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { + if (!strm) { // === Z_NULL + return Z_STREAM_ERROR; + } + var wrap = 1; + + if (level === Z_DEFAULT_COMPRESSION) { + level = 6; + } + + if (windowBits < 0) { /* suppress zlib wrapper */ + wrap = 0; + windowBits = -windowBits; + } + + else if (windowBits > 15) { + wrap = 2; /* write gzip wrapper instead */ + windowBits -= 16; + } + + + if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || + windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || + strategy < 0 || strategy > Z_FIXED) { + return err(strm, Z_STREAM_ERROR); + } + + + if (windowBits === 8) { + windowBits = 9; + } + /* until 256-byte window bug fixed */ + + var s = new DeflateState(); + + strm.state = s; + s.strm = strm; + + s.wrap = wrap; + s.gzhead = null; + s.w_bits = windowBits; + s.w_size = 1 << s.w_bits; + s.w_mask = s.w_size - 1; + + s.hash_bits = memLevel + 7; + s.hash_size = 1 << s.hash_bits; + s.hash_mask = s.hash_size - 1; + s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH); + + s.window = new utils.Buf8(s.w_size * 2); + s.head = new utils.Buf16(s.hash_size); + s.prev = new utils.Buf16(s.w_size); + + // Don't need mem init magic for JS. + //s.high_water = 0; /* nothing written to s->window yet */ + + s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ + + s.pending_buf_size = s.lit_bufsize * 4; + + //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); + //s->pending_buf = (uchf *) overlay; + s.pending_buf = new utils.Buf8(s.pending_buf_size); + + // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`) + //s->d_buf = overlay + s->lit_bufsize/sizeof(ush); + s.d_buf = 1 * s.lit_bufsize; + + //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; + s.l_buf = (1 + 2) * s.lit_bufsize; + + s.level = level; + s.strategy = strategy; + s.method = method; + + return deflateReset(strm); +} + +function deflateInit(strm, level) { + return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); +} + + +function deflate(strm, flush) { + var old_flush, s; + var beg, val; // for gzip header write only + + if (!strm || !strm.state || + flush > Z_BLOCK || flush < 0) { + return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; + } + + s = strm.state; + + if (!strm.output || + (!strm.input && strm.avail_in !== 0) || + (s.status === FINISH_STATE && flush !== Z_FINISH)) { + return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR); + } + + s.strm = strm; /* just in case */ + old_flush = s.last_flush; + s.last_flush = flush; + + /* Write the header */ + if (s.status === INIT_STATE) { + + if (s.wrap === 2) { // GZIP header + strm.adler = 0; //crc32(0L, Z_NULL, 0); + put_byte(s, 31); + put_byte(s, 139); + put_byte(s, 8); + if (!s.gzhead) { // s->gzhead == Z_NULL + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, s.level === 9 ? 2 : + (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? + 4 : 0)); + put_byte(s, OS_CODE); + s.status = BUSY_STATE; + } + else { + put_byte(s, (s.gzhead.text ? 1 : 0) + + (s.gzhead.hcrc ? 2 : 0) + + (!s.gzhead.extra ? 0 : 4) + + (!s.gzhead.name ? 0 : 8) + + (!s.gzhead.comment ? 0 : 16) + ); + put_byte(s, s.gzhead.time & 0xff); + put_byte(s, (s.gzhead.time >> 8) & 0xff); + put_byte(s, (s.gzhead.time >> 16) & 0xff); + put_byte(s, (s.gzhead.time >> 24) & 0xff); + put_byte(s, s.level === 9 ? 2 : + (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? + 4 : 0)); + put_byte(s, s.gzhead.os & 0xff); + if (s.gzhead.extra && s.gzhead.extra.length) { + put_byte(s, s.gzhead.extra.length & 0xff); + put_byte(s, (s.gzhead.extra.length >> 8) & 0xff); + } + if (s.gzhead.hcrc) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); + } + s.gzindex = 0; + s.status = EXTRA_STATE; + } + } + else // DEFLATE header + { + var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8; + var level_flags = -1; + + if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { + level_flags = 0; + } else if (s.level < 6) { + level_flags = 1; + } else if (s.level === 6) { + level_flags = 2; + } else { + level_flags = 3; + } + header |= (level_flags << 6); + if (s.strstart !== 0) { header |= PRESET_DICT; } + header += 31 - (header % 31); + + s.status = BUSY_STATE; + putShortMSB(s, header); + + /* Save the adler32 of the preset dictionary: */ + if (s.strstart !== 0) { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 0xffff); + } + strm.adler = 1; // adler32(0L, Z_NULL, 0); + } + } + +//#ifdef GZIP + if (s.status === EXTRA_STATE) { + if (s.gzhead.extra/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + + while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + break; + } + } + put_byte(s, s.gzhead.extra[s.gzindex] & 0xff); + s.gzindex++; + } + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (s.gzindex === s.gzhead.extra.length) { + s.gzindex = 0; + s.status = NAME_STATE; + } + } + else { + s.status = NAME_STATE; + } + } + if (s.status === NAME_STATE) { + if (s.gzhead.name/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + //int val; + + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + // JS specific: little magic to add zero terminator to end of string + if (s.gzindex < s.gzhead.name.length) { + val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); + + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.gzindex = 0; + s.status = COMMENT_STATE; + } + } + else { + s.status = COMMENT_STATE; + } + } + if (s.status === COMMENT_STATE) { + if (s.gzhead.comment/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + //int val; + + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + // JS specific: little magic to add zero terminator to end of string + if (s.gzindex < s.gzhead.comment.length) { + val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); + + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.status = HCRC_STATE; + } + } + else { + s.status = HCRC_STATE; + } + } + if (s.status === HCRC_STATE) { + if (s.gzhead.hcrc) { + if (s.pending + 2 > s.pending_buf_size) { + flush_pending(strm); + } + if (s.pending + 2 <= s.pending_buf_size) { + put_byte(s, strm.adler & 0xff); + put_byte(s, (strm.adler >> 8) & 0xff); + strm.adler = 0; //crc32(0L, Z_NULL, 0); + s.status = BUSY_STATE; + } + } + else { + s.status = BUSY_STATE; + } + } +//#endif + + /* Flush as much pending output as possible */ + if (s.pending !== 0) { + flush_pending(strm); + if (strm.avail_out === 0) { + /* Since avail_out is 0, deflate will be called again with + * more output space, but possibly with both pending and + * avail_in equal to zero. There won't be anything to do, + * but this is not an error situation so make sure we + * return OK instead of BUF_ERROR at next call of deflate: + */ + s.last_flush = -1; + return Z_OK; + } + + /* Make sure there is something to do and avoid duplicate consecutive + * flushes. For repeated and useless calls with Z_FINISH, we keep + * returning Z_STREAM_END instead of Z_BUF_ERROR. + */ + } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && + flush !== Z_FINISH) { + return err(strm, Z_BUF_ERROR); + } + + /* User must not provide more input after the first FINISH: */ + if (s.status === FINISH_STATE && strm.avail_in !== 0) { + return err(strm, Z_BUF_ERROR); + } + + /* Start a new block or continue the current one. + */ + if (strm.avail_in !== 0 || s.lookahead !== 0 || + (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) { + var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) : + (s.strategy === Z_RLE ? deflate_rle(s, flush) : + configuration_table[s.level].func(s, flush)); + + if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { + s.status = FINISH_STATE; + } + if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { + if (strm.avail_out === 0) { + s.last_flush = -1; + /* avoid BUF_ERROR next call, see above */ + } + return Z_OK; + /* If flush != Z_NO_FLUSH && avail_out == 0, the next call + * of deflate should use the same flush parameter to make sure + * that the flush is complete. So we don't have to output an + * empty block here, this will be done at next call. This also + * ensures that for a very small output buffer, we emit at most + * one empty block. + */ + } + if (bstate === BS_BLOCK_DONE) { + if (flush === Z_PARTIAL_FLUSH) { + trees._tr_align(s); + } + else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ + + trees._tr_stored_block(s, 0, 0, false); + /* For a full flush, this empty block will be recognized + * as a special marker by inflate_sync(). + */ + if (flush === Z_FULL_FLUSH) { + /*** CLEAR_HASH(s); ***/ /* forget history */ + zero(s.head); // Fill with NIL (= 0); + + if (s.lookahead === 0) { + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + } + } + flush_pending(strm); + if (strm.avail_out === 0) { + s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ + return Z_OK; + } + } + } + //Assert(strm->avail_out > 0, "bug2"); + //if (strm.avail_out <= 0) { throw new Error("bug2");} + + if (flush !== Z_FINISH) { return Z_OK; } + if (s.wrap <= 0) { return Z_STREAM_END; } + + /* Write the trailer */ + if (s.wrap === 2) { + put_byte(s, strm.adler & 0xff); + put_byte(s, (strm.adler >> 8) & 0xff); + put_byte(s, (strm.adler >> 16) & 0xff); + put_byte(s, (strm.adler >> 24) & 0xff); + put_byte(s, strm.total_in & 0xff); + put_byte(s, (strm.total_in >> 8) & 0xff); + put_byte(s, (strm.total_in >> 16) & 0xff); + put_byte(s, (strm.total_in >> 24) & 0xff); + } + else + { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 0xffff); + } + + flush_pending(strm); + /* If avail_out is zero, the application will call deflate again + * to flush the rest. + */ + if (s.wrap > 0) { s.wrap = -s.wrap; } + /* write the trailer only once! */ + return s.pending !== 0 ? Z_OK : Z_STREAM_END; +} + +function deflateEnd(strm) { + var status; + + if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { + return Z_STREAM_ERROR; + } + + status = strm.state.status; + if (status !== INIT_STATE && + status !== EXTRA_STATE && + status !== NAME_STATE && + status !== COMMENT_STATE && + status !== HCRC_STATE && + status !== BUSY_STATE && + status !== FINISH_STATE + ) { + return err(strm, Z_STREAM_ERROR); + } + + strm.state = null; + + return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; +} + + +/* ========================================================================= + * Initializes the compression dictionary from the given byte + * sequence without producing any compressed output. + */ +function deflateSetDictionary(strm, dictionary) { + var dictLength = dictionary.length; + + var s; + var str, n; + var wrap; + var avail; + var next; + var input; + var tmpDict; + + if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { + return Z_STREAM_ERROR; + } + + s = strm.state; + wrap = s.wrap; + + if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) { + return Z_STREAM_ERROR; + } + + /* when using zlib wrappers, compute Adler-32 for provided dictionary */ + if (wrap === 1) { + /* adler32(strm->adler, dictionary, dictLength); */ + strm.adler = adler32(strm.adler, dictionary, dictLength, 0); + } + + s.wrap = 0; /* avoid computing Adler-32 in read_buf */ + + /* if dictionary would fill window, just replace the history */ + if (dictLength >= s.w_size) { + if (wrap === 0) { /* already empty otherwise */ + /*** CLEAR_HASH(s); ***/ + zero(s.head); // Fill with NIL (= 0); + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + /* use the tail */ + // dictionary = dictionary.slice(dictLength - s.w_size); + tmpDict = new utils.Buf8(s.w_size); + utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0); + dictionary = tmpDict; + dictLength = s.w_size; + } + /* insert dictionary into window and hash */ + avail = strm.avail_in; + next = strm.next_in; + input = strm.input; + strm.avail_in = dictLength; + strm.next_in = 0; + strm.input = dictionary; + fill_window(s); + while (s.lookahead >= MIN_MATCH) { + str = s.strstart; + n = s.lookahead - (MIN_MATCH - 1); + do { + /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; + + s.prev[str & s.w_mask] = s.head[s.ins_h]; + + s.head[s.ins_h] = str; + str++; + } while (--n); + s.strstart = str; + s.lookahead = MIN_MATCH - 1; + fill_window(s); + } + s.strstart += s.lookahead; + s.block_start = s.strstart; + s.insert = s.lookahead; + s.lookahead = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + strm.next_in = next; + strm.input = input; + strm.avail_in = avail; + s.wrap = wrap; + return Z_OK; +} + + +exports.deflateInit = deflateInit; +exports.deflateInit2 = deflateInit2; +exports.deflateReset = deflateReset; +exports.deflateResetKeep = deflateResetKeep; +exports.deflateSetHeader = deflateSetHeader; +exports.deflate = deflate; +exports.deflateEnd = deflateEnd; +exports.deflateSetDictionary = deflateSetDictionary; +exports.deflateInfo = 'pako deflate (from Nodeca project)'; + +/* Not implemented +exports.deflateBound = deflateBound; +exports.deflateCopy = deflateCopy; +exports.deflateParams = deflateParams; +exports.deflatePending = deflatePending; +exports.deflatePrime = deflatePrime; +exports.deflateTune = deflateTune; +*/ + + +/***/ }), + +/***/ 5105: +/***/ ((module) => { + +"use strict"; + + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +function GZheader() { + /* true if compressed data believed to be text */ + this.text = 0; + /* modification time */ + this.time = 0; + /* extra flags (not used when writing a gzip file) */ + this.xflags = 0; + /* operating system */ + this.os = 0; + /* pointer to extra field or Z_NULL if none */ + this.extra = null; + /* extra field length (valid if extra != Z_NULL) */ + this.extra_len = 0; // Actually, we don't need it in JS, + // but leave for few code modifications + + // + // Setup limits is not necessary because in js we should not preallocate memory + // for inflate use constant limit in 65536 bytes + // + + /* space at extra (only when reading header) */ + // this.extra_max = 0; + /* pointer to zero-terminated file name or Z_NULL */ + this.name = ''; + /* space at name (only when reading header) */ + // this.name_max = 0; + /* pointer to zero-terminated comment or Z_NULL */ + this.comment = ''; + /* space at comment (only when reading header) */ + // this.comm_max = 0; + /* true if there was or will be a header crc */ + this.hcrc = 0; + /* true when done reading gzip header (not used when writing a gzip file) */ + this.done = false; +} + +module.exports = GZheader; + + +/***/ }), + +/***/ 5349: +/***/ ((module) => { + +"use strict"; + + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +// See state defs from inflate.js +var BAD = 30; /* got a data error -- remain here until reset */ +var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ + +/* + Decode literal, length, and distance codes and write out the resulting + literal and match bytes until either not enough input or output is + available, an end-of-block is encountered, or a data error is encountered. + When large enough input and output buffers are supplied to inflate(), for + example, a 16K input buffer and a 64K output buffer, more than 95% of the + inflate execution time is spent in this routine. + + Entry assumptions: + + state.mode === LEN + strm.avail_in >= 6 + strm.avail_out >= 258 + start >= strm.avail_out + state.bits < 8 + + On return, state.mode is one of: + + LEN -- ran out of enough output space or enough available input + TYPE -- reached end of block code, inflate() to interpret next block + BAD -- error in block data + + Notes: + + - The maximum input bits used by a length/distance pair is 15 bits for the + length code, 5 bits for the length extra, 15 bits for the distance code, + and 13 bits for the distance extra. This totals 48 bits, or six bytes. + Therefore if strm.avail_in >= 6, then there is enough input to avoid + checking for available input while decoding. + + - The maximum bytes that a single length/distance pair can output is 258 + bytes, which is the maximum length that can be coded. inflate_fast() + requires strm.avail_out >= 258 for each loop to avoid checking for + output space. + */ +module.exports = function inflate_fast(strm, start) { + var state; + var _in; /* local strm.input */ + var last; /* have enough input while in < last */ + var _out; /* local strm.output */ + var beg; /* inflate()'s initial strm.output */ + var end; /* while out < end, enough space available */ +//#ifdef INFLATE_STRICT + var dmax; /* maximum distance from zlib header */ +//#endif + var wsize; /* window size or zero if not using window */ + var whave; /* valid bytes in the window */ + var wnext; /* window write index */ + // Use `s_window` instead `window`, avoid conflict with instrumentation tools + var s_window; /* allocated sliding window, if wsize != 0 */ + var hold; /* local strm.hold */ + var bits; /* local strm.bits */ + var lcode; /* local strm.lencode */ + var dcode; /* local strm.distcode */ + var lmask; /* mask for first level of length codes */ + var dmask; /* mask for first level of distance codes */ + var here; /* retrieved table entry */ + var op; /* code bits, operation, extra bits, or */ + /* window position, window bytes to copy */ + var len; /* match length, unused bytes */ + var dist; /* match distance */ + var from; /* where to copy match from */ + var from_source; + + + var input, output; // JS specific, because we have no pointers + + /* copy state to local variables */ + state = strm.state; + //here = state.here; + _in = strm.next_in; + input = strm.input; + last = _in + (strm.avail_in - 5); + _out = strm.next_out; + output = strm.output; + beg = _out - (start - strm.avail_out); + end = _out + (strm.avail_out - 257); +//#ifdef INFLATE_STRICT + dmax = state.dmax; +//#endif + wsize = state.wsize; + whave = state.whave; + wnext = state.wnext; + s_window = state.window; + hold = state.hold; + bits = state.bits; + lcode = state.lencode; + dcode = state.distcode; + lmask = (1 << state.lenbits) - 1; + dmask = (1 << state.distbits) - 1; + + + /* decode literals and length/distances until end-of-block or not enough + input data or output space */ + + top: + do { + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + + here = lcode[hold & lmask]; + + dolen: + for (;;) { // Goto emulation + op = here >>> 24/*here.bits*/; + hold >>>= op; + bits -= op; + op = (here >>> 16) & 0xff/*here.op*/; + if (op === 0) { /* literal */ + //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + // "inflate: literal '%c'\n" : + // "inflate: literal 0x%02x\n", here.val)); + output[_out++] = here & 0xffff/*here.val*/; + } + else if (op & 16) { /* length base */ + len = here & 0xffff/*here.val*/; + op &= 15; /* number of extra bits */ + if (op) { + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + len += hold & ((1 << op) - 1); + hold >>>= op; + bits -= op; + } + //Tracevv((stderr, "inflate: length %u\n", len)); + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + here = dcode[hold & dmask]; + + dodist: + for (;;) { // goto emulation + op = here >>> 24/*here.bits*/; + hold >>>= op; + bits -= op; + op = (here >>> 16) & 0xff/*here.op*/; + + if (op & 16) { /* distance base */ + dist = here & 0xffff/*here.val*/; + op &= 15; /* number of extra bits */ + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + } + dist += hold & ((1 << op) - 1); +//#ifdef INFLATE_STRICT + if (dist > dmax) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break top; + } +//#endif + hold >>>= op; + bits -= op; + //Tracevv((stderr, "inflate: distance %u\n", dist)); + op = _out - beg; /* max distance in output */ + if (dist > op) { /* see if copy from window */ + op = dist - op; /* distance back in window */ + if (op > whave) { + if (state.sane) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break top; + } + +// (!) This block is disabled in zlib defaults, +// don't enable it for binary compatibility +//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR +// if (len <= op - whave) { +// do { +// output[_out++] = 0; +// } while (--len); +// continue top; +// } +// len -= op - whave; +// do { +// output[_out++] = 0; +// } while (--op > whave); +// if (op === 0) { +// from = _out - dist; +// do { +// output[_out++] = output[from++]; +// } while (--len); +// continue top; +// } +//#endif + } + from = 0; // window index + from_source = s_window; + if (wnext === 0) { /* very common case */ + from += wsize - op; + if (op < len) { /* some from window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + else if (wnext < op) { /* wrap around window */ + from += wsize + wnext - op; + op -= wnext; + if (op < len) { /* some from end of window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = 0; + if (wnext < len) { /* some from start of window */ + op = wnext; + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + } + else { /* contiguous in window */ + from += wnext - op; + if (op < len) { /* some from window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + while (len > 2) { + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + len -= 3; + } + if (len) { + output[_out++] = from_source[from++]; + if (len > 1) { + output[_out++] = from_source[from++]; + } + } + } + else { + from = _out - dist; /* copy direct from output */ + do { /* minimum length is three */ + output[_out++] = output[from++]; + output[_out++] = output[from++]; + output[_out++] = output[from++]; + len -= 3; + } while (len > 2); + if (len) { + output[_out++] = output[from++]; + if (len > 1) { + output[_out++] = output[from++]; + } + } + } + } + else if ((op & 64) === 0) { /* 2nd level distance code */ + here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; + continue dodist; + } + else { + strm.msg = 'invalid distance code'; + state.mode = BAD; + break top; + } + + break; // need to emulate goto via "continue" + } + } + else if ((op & 64) === 0) { /* 2nd level length code */ + here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; + continue dolen; + } + else if (op & 32) { /* end-of-block */ + //Tracevv((stderr, "inflate: end of block\n")); + state.mode = TYPE; + break top; + } + else { + strm.msg = 'invalid literal/length code'; + state.mode = BAD; + break top; + } + + break; // need to emulate goto via "continue" + } + } while (_in < last && _out < end); + + /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ + len = bits >> 3; + _in -= len; + bits -= len << 3; + hold &= (1 << bits) - 1; + + /* update state and return */ + strm.next_in = _in; + strm.next_out = _out; + strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last)); + strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end)); + state.hold = hold; + state.bits = bits; + return; +}; + + +/***/ }), + +/***/ 409: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +var utils = __nccwpck_require__(5483); +var adler32 = __nccwpck_require__(6924); +var crc32 = __nccwpck_require__(7242); +var inflate_fast = __nccwpck_require__(5349); +var inflate_table = __nccwpck_require__(6895); + +var CODES = 0; +var LENS = 1; +var DISTS = 2; + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +/* Allowed flush values; see deflate() and inflate() below for details */ +//var Z_NO_FLUSH = 0; +//var Z_PARTIAL_FLUSH = 1; +//var Z_SYNC_FLUSH = 2; +//var Z_FULL_FLUSH = 3; +var Z_FINISH = 4; +var Z_BLOCK = 5; +var Z_TREES = 6; + + +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ +var Z_OK = 0; +var Z_STREAM_END = 1; +var Z_NEED_DICT = 2; +//var Z_ERRNO = -1; +var Z_STREAM_ERROR = -2; +var Z_DATA_ERROR = -3; +var Z_MEM_ERROR = -4; +var Z_BUF_ERROR = -5; +//var Z_VERSION_ERROR = -6; + +/* The deflate compression method */ +var Z_DEFLATED = 8; + + +/* STATES ====================================================================*/ +/* ===========================================================================*/ + + +var HEAD = 1; /* i: waiting for magic header */ +var FLAGS = 2; /* i: waiting for method and flags (gzip) */ +var TIME = 3; /* i: waiting for modification time (gzip) */ +var OS = 4; /* i: waiting for extra flags and operating system (gzip) */ +var EXLEN = 5; /* i: waiting for extra length (gzip) */ +var EXTRA = 6; /* i: waiting for extra bytes (gzip) */ +var NAME = 7; /* i: waiting for end of file name (gzip) */ +var COMMENT = 8; /* i: waiting for end of comment (gzip) */ +var HCRC = 9; /* i: waiting for header crc (gzip) */ +var DICTID = 10; /* i: waiting for dictionary check value */ +var DICT = 11; /* waiting for inflateSetDictionary() call */ +var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ +var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ +var STORED = 14; /* i: waiting for stored size (length and complement) */ +var COPY_ = 15; /* i/o: same as COPY below, but only first time in */ +var COPY = 16; /* i/o: waiting for input or output to copy stored block */ +var TABLE = 17; /* i: waiting for dynamic block table lengths */ +var LENLENS = 18; /* i: waiting for code length code lengths */ +var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ +var LEN_ = 20; /* i: same as LEN below, but only first time in */ +var LEN = 21; /* i: waiting for length/lit/eob code */ +var LENEXT = 22; /* i: waiting for length extra bits */ +var DIST = 23; /* i: waiting for distance code */ +var DISTEXT = 24; /* i: waiting for distance extra bits */ +var MATCH = 25; /* o: waiting for output space to copy string */ +var LIT = 26; /* o: waiting for output space to write literal */ +var CHECK = 27; /* i: waiting for 32-bit check value */ +var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ +var DONE = 29; /* finished check, done -- remain here until reset */ +var BAD = 30; /* got a data error -- remain here until reset */ +var MEM = 31; /* got an inflate() memory error -- remain here until reset */ +var SYNC = 32; /* looking for synchronization bytes to restart inflate() */ + +/* ===========================================================================*/ + + + +var ENOUGH_LENS = 852; +var ENOUGH_DISTS = 592; +//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); + +var MAX_WBITS = 15; +/* 32K LZ77 window */ +var DEF_WBITS = MAX_WBITS; + + +function zswap32(q) { + return (((q >>> 24) & 0xff) + + ((q >>> 8) & 0xff00) + + ((q & 0xff00) << 8) + + ((q & 0xff) << 24)); +} + + +function InflateState() { + this.mode = 0; /* current inflate mode */ + this.last = false; /* true if processing last block */ + this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ + this.havedict = false; /* true if dictionary provided */ + this.flags = 0; /* gzip header method and flags (0 if zlib) */ + this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ + this.check = 0; /* protected copy of check value */ + this.total = 0; /* protected copy of output count */ + // TODO: may be {} + this.head = null; /* where to save gzip header information */ + + /* sliding window */ + this.wbits = 0; /* log base 2 of requested window size */ + this.wsize = 0; /* window size or zero if not using window */ + this.whave = 0; /* valid bytes in the window */ + this.wnext = 0; /* window write index */ + this.window = null; /* allocated sliding window, if needed */ + + /* bit accumulator */ + this.hold = 0; /* input bit accumulator */ + this.bits = 0; /* number of bits in "in" */ + + /* for string and stored block copying */ + this.length = 0; /* literal or length of data to copy */ + this.offset = 0; /* distance back to copy string from */ + + /* for table and code decoding */ + this.extra = 0; /* extra bits needed */ + + /* fixed and dynamic code tables */ + this.lencode = null; /* starting table for length/literal codes */ + this.distcode = null; /* starting table for distance codes */ + this.lenbits = 0; /* index bits for lencode */ + this.distbits = 0; /* index bits for distcode */ + + /* dynamic table building */ + this.ncode = 0; /* number of code length code lengths */ + this.nlen = 0; /* number of length code lengths */ + this.ndist = 0; /* number of distance code lengths */ + this.have = 0; /* number of code lengths in lens[] */ + this.next = null; /* next available space in codes[] */ + + this.lens = new utils.Buf16(320); /* temporary storage for code lengths */ + this.work = new utils.Buf16(288); /* work area for code table building */ + + /* + because we don't have pointers in js, we use lencode and distcode directly + as buffers so we don't need codes + */ + //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */ + this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ + this.distdyn = null; /* dynamic table for distance codes (JS specific) */ + this.sane = 0; /* if false, allow invalid distance too far */ + this.back = 0; /* bits back of last unprocessed length/lit */ + this.was = 0; /* initial length of match */ +} + +function inflateResetKeep(strm) { + var state; + + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + strm.total_in = strm.total_out = state.total = 0; + strm.msg = ''; /*Z_NULL*/ + if (state.wrap) { /* to support ill-conceived Java test suite */ + strm.adler = state.wrap & 1; + } + state.mode = HEAD; + state.last = 0; + state.havedict = 0; + state.dmax = 32768; + state.head = null/*Z_NULL*/; + state.hold = 0; + state.bits = 0; + //state.lencode = state.distcode = state.next = state.codes; + state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS); + state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS); + + state.sane = 1; + state.back = -1; + //Tracev((stderr, "inflate: reset\n")); + return Z_OK; +} + +function inflateReset(strm) { + var state; + + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + state.wsize = 0; + state.whave = 0; + state.wnext = 0; + return inflateResetKeep(strm); + +} + +function inflateReset2(strm, windowBits) { + var wrap; + var state; + + /* get the state */ + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + + /* extract wrap request from windowBits parameter */ + if (windowBits < 0) { + wrap = 0; + windowBits = -windowBits; + } + else { + wrap = (windowBits >> 4) + 1; + if (windowBits < 48) { + windowBits &= 15; + } + } + + /* set number of window bits, free window if different */ + if (windowBits && (windowBits < 8 || windowBits > 15)) { + return Z_STREAM_ERROR; + } + if (state.window !== null && state.wbits !== windowBits) { + state.window = null; + } + + /* update state and reset the rest of it */ + state.wrap = wrap; + state.wbits = windowBits; + return inflateReset(strm); +} + +function inflateInit2(strm, windowBits) { + var ret; + var state; + + if (!strm) { return Z_STREAM_ERROR; } + //strm.msg = Z_NULL; /* in case we return an error */ + + state = new InflateState(); + + //if (state === Z_NULL) return Z_MEM_ERROR; + //Tracev((stderr, "inflate: allocated\n")); + strm.state = state; + state.window = null/*Z_NULL*/; + ret = inflateReset2(strm, windowBits); + if (ret !== Z_OK) { + strm.state = null/*Z_NULL*/; + } + return ret; +} + +function inflateInit(strm) { + return inflateInit2(strm, DEF_WBITS); +} + + +/* + Return state with length and distance decoding tables and index sizes set to + fixed code decoding. Normally this returns fixed tables from inffixed.h. + If BUILDFIXED is defined, then instead this routine builds the tables the + first time it's called, and returns those tables the first time and + thereafter. This reduces the size of the code by about 2K bytes, in + exchange for a little execution time. However, BUILDFIXED should not be + used for threaded applications, since the rewriting of the tables and virgin + may not be thread-safe. + */ +var virgin = true; + +var lenfix, distfix; // We have no pointers in JS, so keep tables separate + +function fixedtables(state) { + /* build fixed huffman tables if first call (may not be thread safe) */ + if (virgin) { + var sym; + + lenfix = new utils.Buf32(512); + distfix = new utils.Buf32(32); + + /* literal/length table */ + sym = 0; + while (sym < 144) { state.lens[sym++] = 8; } + while (sym < 256) { state.lens[sym++] = 9; } + while (sym < 280) { state.lens[sym++] = 7; } + while (sym < 288) { state.lens[sym++] = 8; } + + inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 }); + + /* distance table */ + sym = 0; + while (sym < 32) { state.lens[sym++] = 5; } + + inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 }); + + /* do this just once */ + virgin = false; + } + + state.lencode = lenfix; + state.lenbits = 9; + state.distcode = distfix; + state.distbits = 5; +} + + +/* + Update the window with the last wsize (normally 32K) bytes written before + returning. If window does not exist yet, create it. This is only called + when a window is already in use, or when output has been written during this + inflate call, but the end of the deflate stream has not been reached yet. + It is also called to create a window for dictionary data when a dictionary + is loaded. + + Providing output buffers larger than 32K to inflate() should provide a speed + advantage, since only the last 32K of output is copied to the sliding window + upon return from inflate(), and since all distances after the first 32K of + output will fall in the output data, making match copies simpler and faster. + The advantage may be dependent on the size of the processor's data caches. + */ +function updatewindow(strm, src, end, copy) { + var dist; + var state = strm.state; + + /* if it hasn't been done already, allocate space for the window */ + if (state.window === null) { + state.wsize = 1 << state.wbits; + state.wnext = 0; + state.whave = 0; + + state.window = new utils.Buf8(state.wsize); + } + + /* copy state->wsize or less output bytes into the circular window */ + if (copy >= state.wsize) { + utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0); + state.wnext = 0; + state.whave = state.wsize; + } + else { + dist = state.wsize - state.wnext; + if (dist > copy) { + dist = copy; + } + //zmemcpy(state->window + state->wnext, end - copy, dist); + utils.arraySet(state.window, src, end - copy, dist, state.wnext); + copy -= dist; + if (copy) { + //zmemcpy(state->window, end - copy, copy); + utils.arraySet(state.window, src, end - copy, copy, 0); + state.wnext = copy; + state.whave = state.wsize; + } + else { + state.wnext += dist; + if (state.wnext === state.wsize) { state.wnext = 0; } + if (state.whave < state.wsize) { state.whave += dist; } + } + } + return 0; +} + +function inflate(strm, flush) { + var state; + var input, output; // input/output buffers + var next; /* next input INDEX */ + var put; /* next output INDEX */ + var have, left; /* available input and output */ + var hold; /* bit buffer */ + var bits; /* bits in bit buffer */ + var _in, _out; /* save starting available input and output */ + var copy; /* number of stored or match bytes to copy */ + var from; /* where to copy match bytes from */ + var from_source; + var here = 0; /* current decoding table entry */ + var here_bits, here_op, here_val; // paked "here" denormalized (JS specific) + //var last; /* parent table entry */ + var last_bits, last_op, last_val; // paked "last" denormalized (JS specific) + var len; /* length to copy for repeats, bits to drop */ + var ret; /* return code */ + var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */ + var opts; + + var n; // temporary var for NEED_BITS + + var order = /* permutation of code lengths */ + [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]; + + + if (!strm || !strm.state || !strm.output || + (!strm.input && strm.avail_in !== 0)) { + return Z_STREAM_ERROR; + } + + state = strm.state; + if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */ + + + //--- LOAD() --- + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + //--- + + _in = have; + _out = left; + ret = Z_OK; + + inf_leave: // goto emulation + for (;;) { + switch (state.mode) { + case HEAD: + if (state.wrap === 0) { + state.mode = TYPEDO; + break; + } + //=== NEEDBITS(16); + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ + state.check = 0/*crc32(0L, Z_NULL, 0)*/; + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = FLAGS; + break; + } + state.flags = 0; /* expect zlib header */ + if (state.head) { + state.head.done = false; + } + if (!(state.wrap & 1) || /* check if zlib header allowed */ + (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) { + strm.msg = 'incorrect header check'; + state.mode = BAD; + break; + } + if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) { + strm.msg = 'unknown compression method'; + state.mode = BAD; + break; + } + //--- DROPBITS(4) ---// + hold >>>= 4; + bits -= 4; + //---// + len = (hold & 0x0f)/*BITS(4)*/ + 8; + if (state.wbits === 0) { + state.wbits = len; + } + else if (len > state.wbits) { + strm.msg = 'invalid window size'; + state.mode = BAD; + break; + } + state.dmax = 1 << len; + //Tracev((stderr, "inflate: zlib header ok\n")); + strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; + state.mode = hold & 0x200 ? DICTID : TYPE; + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + break; + case FLAGS: + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.flags = hold; + if ((state.flags & 0xff) !== Z_DEFLATED) { + strm.msg = 'unknown compression method'; + state.mode = BAD; + break; + } + if (state.flags & 0xe000) { + strm.msg = 'unknown header flags set'; + state.mode = BAD; + break; + } + if (state.head) { + state.head.text = ((hold >> 8) & 1); + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = TIME; + /* falls through */ + case TIME: + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (state.head) { + state.head.time = hold; + } + if (state.flags & 0x0200) { + //=== CRC4(state.check, hold) + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + hbuf[2] = (hold >>> 16) & 0xff; + hbuf[3] = (hold >>> 24) & 0xff; + state.check = crc32(state.check, hbuf, 4, 0); + //=== + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = OS; + /* falls through */ + case OS: + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (state.head) { + state.head.xflags = (hold & 0xff); + state.head.os = (hold >> 8); + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = EXLEN; + /* falls through */ + case EXLEN: + if (state.flags & 0x0400) { + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.length = hold; + if (state.head) { + state.head.extra_len = hold; + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + } + else if (state.head) { + state.head.extra = null/*Z_NULL*/; + } + state.mode = EXTRA; + /* falls through */ + case EXTRA: + if (state.flags & 0x0400) { + copy = state.length; + if (copy > have) { copy = have; } + if (copy) { + if (state.head) { + len = state.head.extra_len - state.length; + if (!state.head.extra) { + // Use untyped array for more convenient processing later + state.head.extra = new Array(state.head.extra_len); + } + utils.arraySet( + state.head.extra, + input, + next, + // extra field is limited to 65536 bytes + // - no need for additional size check + copy, + /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ + len + ); + //zmemcpy(state.head.extra + len, next, + // len + copy > state.head.extra_max ? + // state.head.extra_max - len : copy); + } + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + state.length -= copy; + } + if (state.length) { break inf_leave; } + } + state.length = 0; + state.mode = NAME; + /* falls through */ + case NAME: + if (state.flags & 0x0800) { + if (have === 0) { break inf_leave; } + copy = 0; + do { + // TODO: 2 or 1 bytes? + len = input[next + copy++]; + /* use constant limit because in js we should not preallocate memory */ + if (state.head && len && + (state.length < 65536 /*state.head.name_max*/)) { + state.head.name += String.fromCharCode(len); + } + } while (len && copy < have); + + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { break inf_leave; } + } + else if (state.head) { + state.head.name = null; + } + state.length = 0; + state.mode = COMMENT; + /* falls through */ + case COMMENT: + if (state.flags & 0x1000) { + if (have === 0) { break inf_leave; } + copy = 0; + do { + len = input[next + copy++]; + /* use constant limit because in js we should not preallocate memory */ + if (state.head && len && + (state.length < 65536 /*state.head.comm_max*/)) { + state.head.comment += String.fromCharCode(len); + } + } while (len && copy < have); + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { break inf_leave; } + } + else if (state.head) { + state.head.comment = null; + } + state.mode = HCRC; + /* falls through */ + case HCRC: + if (state.flags & 0x0200) { + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (hold !== (state.check & 0xffff)) { + strm.msg = 'header crc mismatch'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + } + if (state.head) { + state.head.hcrc = ((state.flags >> 9) & 1); + state.head.done = true; + } + strm.adler = state.check = 0; + state.mode = TYPE; + break; + case DICTID: + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + strm.adler = state.check = zswap32(hold); + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = DICT; + /* falls through */ + case DICT: + if (state.havedict === 0) { + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + return Z_NEED_DICT; + } + strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; + state.mode = TYPE; + /* falls through */ + case TYPE: + if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; } + /* falls through */ + case TYPEDO: + if (state.last) { + //--- BYTEBITS() ---// + hold >>>= bits & 7; + bits -= bits & 7; + //---// + state.mode = CHECK; + break; + } + //=== NEEDBITS(3); */ + while (bits < 3) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.last = (hold & 0x01)/*BITS(1)*/; + //--- DROPBITS(1) ---// + hold >>>= 1; + bits -= 1; + //---// + + switch ((hold & 0x03)/*BITS(2)*/) { + case 0: /* stored block */ + //Tracev((stderr, "inflate: stored block%s\n", + // state.last ? " (last)" : "")); + state.mode = STORED; + break; + case 1: /* fixed block */ + fixedtables(state); + //Tracev((stderr, "inflate: fixed codes block%s\n", + // state.last ? " (last)" : "")); + state.mode = LEN_; /* decode codes */ + if (flush === Z_TREES) { + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + break inf_leave; + } + break; + case 2: /* dynamic block */ + //Tracev((stderr, "inflate: dynamic codes block%s\n", + // state.last ? " (last)" : "")); + state.mode = TABLE; + break; + case 3: + strm.msg = 'invalid block type'; + state.mode = BAD; + } + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + break; + case STORED: + //--- BYTEBITS() ---// /* go to byte boundary */ + hold >>>= bits & 7; + bits -= bits & 7; + //---// + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { + strm.msg = 'invalid stored block lengths'; + state.mode = BAD; + break; + } + state.length = hold & 0xffff; + //Tracev((stderr, "inflate: stored length %u\n", + // state.length)); + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = COPY_; + if (flush === Z_TREES) { break inf_leave; } + /* falls through */ + case COPY_: + state.mode = COPY; + /* falls through */ + case COPY: + copy = state.length; + if (copy) { + if (copy > have) { copy = have; } + if (copy > left) { copy = left; } + if (copy === 0) { break inf_leave; } + //--- zmemcpy(put, next, copy); --- + utils.arraySet(output, input, next, copy, put); + //---// + have -= copy; + next += copy; + left -= copy; + put += copy; + state.length -= copy; + break; + } + //Tracev((stderr, "inflate: stored end\n")); + state.mode = TYPE; + break; + case TABLE: + //=== NEEDBITS(14); */ + while (bits < 14) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257; + //--- DROPBITS(5) ---// + hold >>>= 5; + bits -= 5; + //---// + state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1; + //--- DROPBITS(5) ---// + hold >>>= 5; + bits -= 5; + //---// + state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4; + //--- DROPBITS(4) ---// + hold >>>= 4; + bits -= 4; + //---// +//#ifndef PKZIP_BUG_WORKAROUND + if (state.nlen > 286 || state.ndist > 30) { + strm.msg = 'too many length or distance symbols'; + state.mode = BAD; + break; + } +//#endif + //Tracev((stderr, "inflate: table sizes ok\n")); + state.have = 0; + state.mode = LENLENS; + /* falls through */ + case LENLENS: + while (state.have < state.ncode) { + //=== NEEDBITS(3); + while (bits < 3) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.lens[order[state.have++]] = (hold & 0x07);//BITS(3); + //--- DROPBITS(3) ---// + hold >>>= 3; + bits -= 3; + //---// + } + while (state.have < 19) { + state.lens[order[state.have++]] = 0; + } + // We have separate tables & no pointers. 2 commented lines below not needed. + //state.next = state.codes; + //state.lencode = state.next; + // Switch to use dynamic table + state.lencode = state.lendyn; + state.lenbits = 7; + + opts = { bits: state.lenbits }; + ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts); + state.lenbits = opts.bits; + + if (ret) { + strm.msg = 'invalid code lengths set'; + state.mode = BAD; + break; + } + //Tracev((stderr, "inflate: code lengths ok\n")); + state.have = 0; + state.mode = CODELENS; + /* falls through */ + case CODELENS: + while (state.have < state.nlen + state.ndist) { + for (;;) { + here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if (here_val < 16) { + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.lens[state.have++] = here_val; + } + else { + if (here_val === 16) { + //=== NEEDBITS(here.bits + 2); + n = here_bits + 2; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + if (state.have === 0) { + strm.msg = 'invalid bit length repeat'; + state.mode = BAD; + break; + } + len = state.lens[state.have - 1]; + copy = 3 + (hold & 0x03);//BITS(2); + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + } + else if (here_val === 17) { + //=== NEEDBITS(here.bits + 3); + n = here_bits + 3; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + len = 0; + copy = 3 + (hold & 0x07);//BITS(3); + //--- DROPBITS(3) ---// + hold >>>= 3; + bits -= 3; + //---// + } + else { + //=== NEEDBITS(here.bits + 7); + n = here_bits + 7; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + len = 0; + copy = 11 + (hold & 0x7f);//BITS(7); + //--- DROPBITS(7) ---// + hold >>>= 7; + bits -= 7; + //---// + } + if (state.have + copy > state.nlen + state.ndist) { + strm.msg = 'invalid bit length repeat'; + state.mode = BAD; + break; + } + while (copy--) { + state.lens[state.have++] = len; + } + } + } + + /* handle error breaks in while */ + if (state.mode === BAD) { break; } + + /* check for end-of-block code (better have one) */ + if (state.lens[256] === 0) { + strm.msg = 'invalid code -- missing end-of-block'; + state.mode = BAD; + break; + } + + /* build code tables -- note: do not change the lenbits or distbits + values here (9 and 6) without reading the comments in inftrees.h + concerning the ENOUGH constants, which depend on those values */ + state.lenbits = 9; + + opts = { bits: state.lenbits }; + ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); + // We have separate tables & no pointers. 2 commented lines below not needed. + // state.next_index = opts.table_index; + state.lenbits = opts.bits; + // state.lencode = state.next; + + if (ret) { + strm.msg = 'invalid literal/lengths set'; + state.mode = BAD; + break; + } + + state.distbits = 6; + //state.distcode.copy(state.codes); + // Switch to use dynamic table + state.distcode = state.distdyn; + opts = { bits: state.distbits }; + ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); + // We have separate tables & no pointers. 2 commented lines below not needed. + // state.next_index = opts.table_index; + state.distbits = opts.bits; + // state.distcode = state.next; + + if (ret) { + strm.msg = 'invalid distances set'; + state.mode = BAD; + break; + } + //Tracev((stderr, 'inflate: codes ok\n')); + state.mode = LEN_; + if (flush === Z_TREES) { break inf_leave; } + /* falls through */ + case LEN_: + state.mode = LEN; + /* falls through */ + case LEN: + if (have >= 6 && left >= 258) { + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + inflate_fast(strm, _out); + //--- LOAD() --- + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + //--- + + if (state.mode === TYPE) { + state.back = -1; + } + break; + } + state.back = 0; + for (;;) { + here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if (here_bits <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if (here_op && (here_op & 0xf0) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;;) { + here = state.lencode[last_val + + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((last_bits + here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + //--- DROPBITS(last.bits) ---// + hold >>>= last_bits; + bits -= last_bits; + //---// + state.back += last_bits; + } + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.back += here_bits; + state.length = here_val; + if (here_op === 0) { + //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + // "inflate: literal '%c'\n" : + // "inflate: literal 0x%02x\n", here.val)); + state.mode = LIT; + break; + } + if (here_op & 32) { + //Tracevv((stderr, "inflate: end of block\n")); + state.back = -1; + state.mode = TYPE; + break; + } + if (here_op & 64) { + strm.msg = 'invalid literal/length code'; + state.mode = BAD; + break; + } + state.extra = here_op & 15; + state.mode = LENEXT; + /* falls through */ + case LENEXT: + if (state.extra) { + //=== NEEDBITS(state.extra); + n = state.extra; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; + //--- DROPBITS(state.extra) ---// + hold >>>= state.extra; + bits -= state.extra; + //---// + state.back += state.extra; + } + //Tracevv((stderr, "inflate: length %u\n", state.length)); + state.was = state.length; + state.mode = DIST; + /* falls through */ + case DIST: + for (;;) { + here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if ((here_op & 0xf0) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;;) { + here = state.distcode[last_val + + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((last_bits + here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + //--- DROPBITS(last.bits) ---// + hold >>>= last_bits; + bits -= last_bits; + //---// + state.back += last_bits; + } + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.back += here_bits; + if (here_op & 64) { + strm.msg = 'invalid distance code'; + state.mode = BAD; + break; + } + state.offset = here_val; + state.extra = (here_op) & 15; + state.mode = DISTEXT; + /* falls through */ + case DISTEXT: + if (state.extra) { + //=== NEEDBITS(state.extra); + n = state.extra; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; + //--- DROPBITS(state.extra) ---// + hold >>>= state.extra; + bits -= state.extra; + //---// + state.back += state.extra; + } +//#ifdef INFLATE_STRICT + if (state.offset > state.dmax) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break; + } +//#endif + //Tracevv((stderr, "inflate: distance %u\n", state.offset)); + state.mode = MATCH; + /* falls through */ + case MATCH: + if (left === 0) { break inf_leave; } + copy = _out - left; + if (state.offset > copy) { /* copy from window */ + copy = state.offset - copy; + if (copy > state.whave) { + if (state.sane) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break; + } +// (!) This block is disabled in zlib defaults, +// don't enable it for binary compatibility +//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR +// Trace((stderr, "inflate.c too far\n")); +// copy -= state.whave; +// if (copy > state.length) { copy = state.length; } +// if (copy > left) { copy = left; } +// left -= copy; +// state.length -= copy; +// do { +// output[put++] = 0; +// } while (--copy); +// if (state.length === 0) { state.mode = LEN; } +// break; +//#endif + } + if (copy > state.wnext) { + copy -= state.wnext; + from = state.wsize - copy; + } + else { + from = state.wnext - copy; + } + if (copy > state.length) { copy = state.length; } + from_source = state.window; + } + else { /* copy from output */ + from_source = output; + from = put - state.offset; + copy = state.length; + } + if (copy > left) { copy = left; } + left -= copy; + state.length -= copy; + do { + output[put++] = from_source[from++]; + } while (--copy); + if (state.length === 0) { state.mode = LEN; } + break; + case LIT: + if (left === 0) { break inf_leave; } + output[put++] = state.length; + left--; + state.mode = LEN; + break; + case CHECK: + if (state.wrap) { + //=== NEEDBITS(32); + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + // Use '|' instead of '+' to make sure that result is signed + hold |= input[next++] << bits; + bits += 8; + } + //===// + _out -= left; + strm.total_out += _out; + state.total += _out; + if (_out) { + strm.adler = state.check = + /*UPDATE(state.check, put - _out, _out);*/ + (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out)); + + } + _out = left; + // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too + if ((state.flags ? hold : zswap32(hold)) !== state.check) { + strm.msg = 'incorrect data check'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + //Tracev((stderr, "inflate: check matches trailer\n")); + } + state.mode = LENGTH; + /* falls through */ + case LENGTH: + if (state.wrap && state.flags) { + //=== NEEDBITS(32); + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (hold !== (state.total & 0xffffffff)) { + strm.msg = 'incorrect length check'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + //Tracev((stderr, "inflate: length matches trailer\n")); + } + state.mode = DONE; + /* falls through */ + case DONE: + ret = Z_STREAM_END; + break inf_leave; + case BAD: + ret = Z_DATA_ERROR; + break inf_leave; + case MEM: + return Z_MEM_ERROR; + case SYNC: + /* falls through */ + default: + return Z_STREAM_ERROR; + } + } + + // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" + + /* + Return from inflate(), updating the total counts and the check value. + If there was no progress during the inflate() call, return a buffer + error. Call updatewindow() to create and/or update the window state. + Note: a memory error from inflate() is non-recoverable. + */ + + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + + if (state.wsize || (_out !== strm.avail_out && state.mode < BAD && + (state.mode < CHECK || flush !== Z_FINISH))) { + if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) { + state.mode = MEM; + return Z_MEM_ERROR; + } + } + _in -= strm.avail_in; + _out -= strm.avail_out; + strm.total_in += _in; + strm.total_out += _out; + state.total += _out; + if (state.wrap && _out) { + strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ + (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out)); + } + strm.data_type = state.bits + (state.last ? 64 : 0) + + (state.mode === TYPE ? 128 : 0) + + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); + if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) { + ret = Z_BUF_ERROR; + } + return ret; +} + +function inflateEnd(strm) { + + if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) { + return Z_STREAM_ERROR; + } + + var state = strm.state; + if (state.window) { + state.window = null; + } + strm.state = null; + return Z_OK; +} + +function inflateGetHeader(strm, head) { + var state; + + /* check state */ + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; } + + /* save header structure */ + state.head = head; + head.done = false; + return Z_OK; +} + +function inflateSetDictionary(strm, dictionary) { + var dictLength = dictionary.length; + + var state; + var dictid; + var ret; + + /* check state */ + if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; } + state = strm.state; + + if (state.wrap !== 0 && state.mode !== DICT) { + return Z_STREAM_ERROR; + } + + /* check for correct dictionary identifier */ + if (state.mode === DICT) { + dictid = 1; /* adler32(0, null, 0)*/ + /* dictid = adler32(dictid, dictionary, dictLength); */ + dictid = adler32(dictid, dictionary, dictLength, 0); + if (dictid !== state.check) { + return Z_DATA_ERROR; + } + } + /* copy dictionary to window using updatewindow(), which will amend the + existing dictionary if appropriate */ + ret = updatewindow(strm, dictionary, dictLength, dictLength); + if (ret) { + state.mode = MEM; + return Z_MEM_ERROR; + } + state.havedict = 1; + // Tracev((stderr, "inflate: dictionary set\n")); + return Z_OK; +} + +exports.inflateReset = inflateReset; +exports.inflateReset2 = inflateReset2; +exports.inflateResetKeep = inflateResetKeep; +exports.inflateInit = inflateInit; +exports.inflateInit2 = inflateInit2; +exports.inflate = inflate; +exports.inflateEnd = inflateEnd; +exports.inflateGetHeader = inflateGetHeader; +exports.inflateSetDictionary = inflateSetDictionary; +exports.inflateInfo = 'pako inflate (from Nodeca project)'; + +/* Not implemented +exports.inflateCopy = inflateCopy; +exports.inflateGetDictionary = inflateGetDictionary; +exports.inflateMark = inflateMark; +exports.inflatePrime = inflatePrime; +exports.inflateSync = inflateSync; +exports.inflateSyncPoint = inflateSyncPoint; +exports.inflateUndermine = inflateUndermine; +*/ + + +/***/ }), + +/***/ 6895: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +var utils = __nccwpck_require__(5483); + +var MAXBITS = 15; +var ENOUGH_LENS = 852; +var ENOUGH_DISTS = 592; +//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); + +var CODES = 0; +var LENS = 1; +var DISTS = 2; + +var lbase = [ /* Length codes 257..285 base */ + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, + 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 +]; + +var lext = [ /* Length codes 257..285 extra */ + 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, + 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78 +]; + +var dbase = [ /* Distance codes 0..29 base */ + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, + 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, + 8193, 12289, 16385, 24577, 0, 0 +]; + +var dext = [ /* Distance codes 0..29 extra */ + 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, + 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, + 28, 28, 29, 29, 64, 64 +]; + +module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) +{ + var bits = opts.bits; + //here = opts.here; /* table entry for duplication */ + + var len = 0; /* a code's length in bits */ + var sym = 0; /* index of code symbols */ + var min = 0, max = 0; /* minimum and maximum code lengths */ + var root = 0; /* number of index bits for root table */ + var curr = 0; /* number of index bits for current table */ + var drop = 0; /* code bits to drop for sub-table */ + var left = 0; /* number of prefix codes available */ + var used = 0; /* code entries in table used */ + var huff = 0; /* Huffman code */ + var incr; /* for incrementing code, index */ + var fill; /* index for replicating entries */ + var low; /* low bits for current root entry */ + var mask; /* mask for low root bits */ + var next; /* next available space in table */ + var base = null; /* base value table to use */ + var base_index = 0; +// var shoextra; /* extra bits table to use */ + var end; /* use base and extra for symbol > end */ + var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */ + var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */ + var extra = null; + var extra_index = 0; + + var here_bits, here_op, here_val; + + /* + Process a set of code lengths to create a canonical Huffman code. The + code lengths are lens[0..codes-1]. Each length corresponds to the + symbols 0..codes-1. The Huffman code is generated by first sorting the + symbols by length from short to long, and retaining the symbol order + for codes with equal lengths. Then the code starts with all zero bits + for the first code of the shortest length, and the codes are integer + increments for the same length, and zeros are appended as the length + increases. For the deflate format, these bits are stored backwards + from their more natural integer increment ordering, and so when the + decoding tables are built in the large loop below, the integer codes + are incremented backwards. + + This routine assumes, but does not check, that all of the entries in + lens[] are in the range 0..MAXBITS. The caller must assure this. + 1..MAXBITS is interpreted as that code length. zero means that that + symbol does not occur in this code. + + The codes are sorted by computing a count of codes for each length, + creating from that a table of starting indices for each length in the + sorted table, and then entering the symbols in order in the sorted + table. The sorted table is work[], with that space being provided by + the caller. + + The length counts are used for other purposes as well, i.e. finding + the minimum and maximum length codes, determining if there are any + codes at all, checking for a valid set of lengths, and looking ahead + at length counts to determine sub-table sizes when building the + decoding tables. + */ + + /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ + for (len = 0; len <= MAXBITS; len++) { + count[len] = 0; + } + for (sym = 0; sym < codes; sym++) { + count[lens[lens_index + sym]]++; + } + + /* bound code lengths, force root to be within code lengths */ + root = bits; + for (max = MAXBITS; max >= 1; max--) { + if (count[max] !== 0) { break; } + } + if (root > max) { + root = max; + } + if (max === 0) { /* no symbols to code at all */ + //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ + //table.bits[opts.table_index] = 1; //here.bits = (var char)1; + //table.val[opts.table_index++] = 0; //here.val = (var short)0; + table[table_index++] = (1 << 24) | (64 << 16) | 0; + + + //table.op[opts.table_index] = 64; + //table.bits[opts.table_index] = 1; + //table.val[opts.table_index++] = 0; + table[table_index++] = (1 << 24) | (64 << 16) | 0; + + opts.bits = 1; + return 0; /* no symbols, but wait for decoding to report error */ + } + for (min = 1; min < max; min++) { + if (count[min] !== 0) { break; } + } + if (root < min) { + root = min; + } + + /* check for an over-subscribed or incomplete set of lengths */ + left = 1; + for (len = 1; len <= MAXBITS; len++) { + left <<= 1; + left -= count[len]; + if (left < 0) { + return -1; + } /* over-subscribed */ + } + if (left > 0 && (type === CODES || max !== 1)) { + return -1; /* incomplete set */ + } + + /* generate offsets into symbol table for each length for sorting */ + offs[1] = 0; + for (len = 1; len < MAXBITS; len++) { + offs[len + 1] = offs[len] + count[len]; + } + + /* sort symbols by length, by symbol order within each length */ + for (sym = 0; sym < codes; sym++) { + if (lens[lens_index + sym] !== 0) { + work[offs[lens[lens_index + sym]]++] = sym; + } + } + + /* + Create and fill in decoding tables. In this loop, the table being + filled is at next and has curr index bits. The code being used is huff + with length len. That code is converted to an index by dropping drop + bits off of the bottom. For codes where len is less than drop + curr, + those top drop + curr - len bits are incremented through all values to + fill the table with replicated entries. + + root is the number of index bits for the root table. When len exceeds + root, sub-tables are created pointed to by the root entry with an index + of the low root bits of huff. This is saved in low to check for when a + new sub-table should be started. drop is zero when the root table is + being filled, and drop is root when sub-tables are being filled. + + When a new sub-table is needed, it is necessary to look ahead in the + code lengths to determine what size sub-table is needed. The length + counts are used for this, and so count[] is decremented as codes are + entered in the tables. + + used keeps track of how many table entries have been allocated from the + provided *table space. It is checked for LENS and DIST tables against + the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in + the initial root table size constants. See the comments in inftrees.h + for more information. + + sym increments through all symbols, and the loop terminates when + all codes of length max, i.e. all codes, have been processed. This + routine permits incomplete codes, so another loop after this one fills + in the rest of the decoding tables with invalid code markers. + */ + + /* set up for code type */ + // poor man optimization - use if-else instead of switch, + // to avoid deopts in old v8 + if (type === CODES) { + base = extra = work; /* dummy value--not used */ + end = 19; + + } else if (type === LENS) { + base = lbase; + base_index -= 257; + extra = lext; + extra_index -= 257; + end = 256; + + } else { /* DISTS */ + base = dbase; + extra = dext; + end = -1; + } + + /* initialize opts for loop */ + huff = 0; /* starting code */ + sym = 0; /* starting code symbol */ + len = min; /* starting code length */ + next = table_index; /* current table to fill in */ + curr = root; /* current table index bits */ + drop = 0; /* current bits to drop from code for index */ + low = -1; /* trigger new sub-table when len > root */ + used = 1 << root; /* use root table entries */ + mask = used - 1; /* mask for comparing low */ + + /* check available table space */ + if ((type === LENS && used > ENOUGH_LENS) || + (type === DISTS && used > ENOUGH_DISTS)) { + return 1; + } + + /* process all codes and make table entries */ + for (;;) { + /* create table entry */ + here_bits = len - drop; + if (work[sym] < end) { + here_op = 0; + here_val = work[sym]; + } + else if (work[sym] > end) { + here_op = extra[extra_index + work[sym]]; + here_val = base[base_index + work[sym]]; + } + else { + here_op = 32 + 64; /* end of block */ + here_val = 0; + } + + /* replicate for those indices with low len bits equal to huff */ + incr = 1 << (len - drop); + fill = 1 << curr; + min = fill; /* save offset to next table */ + do { + fill -= incr; + table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0; + } while (fill !== 0); + + /* backwards increment the len-bit code huff */ + incr = 1 << (len - 1); + while (huff & incr) { + incr >>= 1; + } + if (incr !== 0) { + huff &= incr - 1; + huff += incr; + } else { + huff = 0; + } + + /* go to next symbol, update count, len */ + sym++; + if (--count[len] === 0) { + if (len === max) { break; } + len = lens[lens_index + work[sym]]; + } + + /* create new sub-table if needed */ + if (len > root && (huff & mask) !== low) { + /* if first time, transition to sub-tables */ + if (drop === 0) { + drop = root; + } + + /* increment past last table */ + next += min; /* here min is 1 << curr */ + + /* determine length of next table */ + curr = len - drop; + left = 1 << curr; + while (curr + drop < max) { + left -= count[curr + drop]; + if (left <= 0) { break; } + curr++; + left <<= 1; + } + + /* check for enough space */ + used += 1 << curr; + if ((type === LENS && used > ENOUGH_LENS) || + (type === DISTS && used > ENOUGH_DISTS)) { + return 1; + } + + /* point entry in root table to sub-table */ + low = huff & mask; + /*table.op[low] = curr; + table.bits[low] = root; + table.val[low] = next - opts.table_index;*/ + table[low] = (root << 24) | (curr << 16) | (next - table_index) |0; + } + } + + /* fill in remaining table entry if code is incomplete (guaranteed to have + at most one remaining entry, since if the code is incomplete, the + maximum code length that was allowed to get this far is one bit) */ + if (huff !== 0) { + //table.op[next + huff] = 64; /* invalid code marker */ + //table.bits[next + huff] = len - drop; + //table.val[next + huff] = 0; + table[next + huff] = ((len - drop) << 24) | (64 << 16) |0; + } + + /* set return parameters */ + //opts.table_index += used; + opts.bits = root; + return 0; +}; + + +/***/ }), + +/***/ 1890: +/***/ ((module) => { + +"use strict"; + + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +module.exports = { + 2: 'need dictionary', /* Z_NEED_DICT 2 */ + 1: 'stream end', /* Z_STREAM_END 1 */ + 0: '', /* Z_OK 0 */ + '-1': 'file error', /* Z_ERRNO (-1) */ + '-2': 'stream error', /* Z_STREAM_ERROR (-2) */ + '-3': 'data error', /* Z_DATA_ERROR (-3) */ + '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */ + '-5': 'buffer error', /* Z_BUF_ERROR (-5) */ + '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */ +}; + + +/***/ }), + +/***/ 8754: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +/* eslint-disable space-unary-ops */ + +var utils = __nccwpck_require__(5483); + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +//var Z_FILTERED = 1; +//var Z_HUFFMAN_ONLY = 2; +//var Z_RLE = 3; +var Z_FIXED = 4; +//var Z_DEFAULT_STRATEGY = 0; + +/* Possible values of the data_type field (though see inflate()) */ +var Z_BINARY = 0; +var Z_TEXT = 1; +//var Z_ASCII = 1; // = Z_TEXT +var Z_UNKNOWN = 2; + +/*============================================================================*/ + + +function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } + +// From zutil.h + +var STORED_BLOCK = 0; +var STATIC_TREES = 1; +var DYN_TREES = 2; +/* The three kinds of block type */ + +var MIN_MATCH = 3; +var MAX_MATCH = 258; +/* The minimum and maximum match lengths */ + +// From deflate.h +/* =========================================================================== + * Internal compression state. + */ + +var LENGTH_CODES = 29; +/* number of length codes, not counting the special END_BLOCK code */ + +var LITERALS = 256; +/* number of literal bytes 0..255 */ + +var L_CODES = LITERALS + 1 + LENGTH_CODES; +/* number of Literal or Length codes, including the END_BLOCK code */ + +var D_CODES = 30; +/* number of distance codes */ + +var BL_CODES = 19; +/* number of codes used to transfer the bit lengths */ + +var HEAP_SIZE = 2 * L_CODES + 1; +/* maximum heap size */ + +var MAX_BITS = 15; +/* All codes must not exceed MAX_BITS bits */ + +var Buf_size = 16; +/* size of bit buffer in bi_buf */ + + +/* =========================================================================== + * Constants + */ + +var MAX_BL_BITS = 7; +/* Bit length codes must not exceed MAX_BL_BITS bits */ + +var END_BLOCK = 256; +/* end of block literal code */ + +var REP_3_6 = 16; +/* repeat previous bit length 3-6 times (2 bits of repeat count) */ + +var REPZ_3_10 = 17; +/* repeat a zero length 3-10 times (3 bits of repeat count) */ + +var REPZ_11_138 = 18; +/* repeat a zero length 11-138 times (7 bits of repeat count) */ + +/* eslint-disable comma-spacing,array-bracket-spacing */ +var extra_lbits = /* extra bits for each length code */ + [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]; + +var extra_dbits = /* extra bits for each distance code */ + [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]; + +var extra_blbits = /* extra bits for each bit length code */ + [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]; + +var bl_order = + [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]; +/* eslint-enable comma-spacing,array-bracket-spacing */ + +/* The lengths of the bit length codes are sent in order of decreasing + * probability, to avoid transmitting the lengths for unused bit length codes. + */ + +/* =========================================================================== + * Local data. These are initialized only once. + */ + +// We pre-fill arrays with 0 to avoid uninitialized gaps + +var DIST_CODE_LEN = 512; /* see definition of array dist_code below */ + +// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1 +var static_ltree = new Array((L_CODES + 2) * 2); +zero(static_ltree); +/* The static literal tree. Since the bit lengths are imposed, there is no + * need for the L_CODES extra codes used during heap construction. However + * The codes 286 and 287 are needed to build a canonical tree (see _tr_init + * below). + */ + +var static_dtree = new Array(D_CODES * 2); +zero(static_dtree); +/* The static distance tree. (Actually a trivial tree since all codes use + * 5 bits.) + */ + +var _dist_code = new Array(DIST_CODE_LEN); +zero(_dist_code); +/* Distance codes. The first 256 values correspond to the distances + * 3 .. 258, the last 256 values correspond to the top 8 bits of + * the 15 bit distances. + */ + +var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1); +zero(_length_code); +/* length code for each normalized match length (0 == MIN_MATCH) */ + +var base_length = new Array(LENGTH_CODES); +zero(base_length); +/* First normalized length for each code (0 = MIN_MATCH) */ + +var base_dist = new Array(D_CODES); +zero(base_dist); +/* First normalized distance for each code (0 = distance of 1) */ + + +function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) { + + this.static_tree = static_tree; /* static tree or NULL */ + this.extra_bits = extra_bits; /* extra bits for each code or NULL */ + this.extra_base = extra_base; /* base index for extra_bits */ + this.elems = elems; /* max number of elements in the tree */ + this.max_length = max_length; /* max bit length for the codes */ + + // show if `static_tree` has data or dummy - needed for monomorphic objects + this.has_stree = static_tree && static_tree.length; +} + + +var static_l_desc; +var static_d_desc; +var static_bl_desc; + + +function TreeDesc(dyn_tree, stat_desc) { + this.dyn_tree = dyn_tree; /* the dynamic tree */ + this.max_code = 0; /* largest code with non zero frequency */ + this.stat_desc = stat_desc; /* the corresponding static tree */ +} + + + +function d_code(dist) { + return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; +} + + +/* =========================================================================== + * Output a short LSB first on the stream. + * IN assertion: there is enough room in pendingBuf. + */ +function put_short(s, w) { +// put_byte(s, (uch)((w) & 0xff)); +// put_byte(s, (uch)((ush)(w) >> 8)); + s.pending_buf[s.pending++] = (w) & 0xff; + s.pending_buf[s.pending++] = (w >>> 8) & 0xff; +} + + +/* =========================================================================== + * Send a value on a given number of bits. + * IN assertion: length <= 16 and value fits in length bits. + */ +function send_bits(s, value, length) { + if (s.bi_valid > (Buf_size - length)) { + s.bi_buf |= (value << s.bi_valid) & 0xffff; + put_short(s, s.bi_buf); + s.bi_buf = value >> (Buf_size - s.bi_valid); + s.bi_valid += length - Buf_size; + } else { + s.bi_buf |= (value << s.bi_valid) & 0xffff; + s.bi_valid += length; + } +} + + +function send_code(s, c, tree) { + send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/); +} + + +/* =========================================================================== + * Reverse the first len bits of a code, using straightforward code (a faster + * method would use a table) + * IN assertion: 1 <= len <= 15 + */ +function bi_reverse(code, len) { + var res = 0; + do { + res |= code & 1; + code >>>= 1; + res <<= 1; + } while (--len > 0); + return res >>> 1; +} + + +/* =========================================================================== + * Flush the bit buffer, keeping at most 7 bits in it. + */ +function bi_flush(s) { + if (s.bi_valid === 16) { + put_short(s, s.bi_buf); + s.bi_buf = 0; + s.bi_valid = 0; + + } else if (s.bi_valid >= 8) { + s.pending_buf[s.pending++] = s.bi_buf & 0xff; + s.bi_buf >>= 8; + s.bi_valid -= 8; + } +} + + +/* =========================================================================== + * Compute the optimal bit lengths for a tree and update the total bit length + * for the current block. + * IN assertion: the fields freq and dad are set, heap[heap_max] and + * above are the tree nodes sorted by increasing frequency. + * OUT assertions: the field len is set to the optimal bit length, the + * array bl_count contains the frequencies for each bit length. + * The length opt_len is updated; static_len is also updated if stree is + * not null. + */ +function gen_bitlen(s, desc) +// deflate_state *s; +// tree_desc *desc; /* the tree descriptor */ +{ + var tree = desc.dyn_tree; + var max_code = desc.max_code; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var extra = desc.stat_desc.extra_bits; + var base = desc.stat_desc.extra_base; + var max_length = desc.stat_desc.max_length; + var h; /* heap index */ + var n, m; /* iterate over the tree elements */ + var bits; /* bit length */ + var xbits; /* extra bits */ + var f; /* frequency */ + var overflow = 0; /* number of elements with bit length too large */ + + for (bits = 0; bits <= MAX_BITS; bits++) { + s.bl_count[bits] = 0; + } + + /* In a first pass, compute the optimal bit lengths (which may + * overflow in the case of the bit length tree). + */ + tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */ + + for (h = s.heap_max + 1; h < HEAP_SIZE; h++) { + n = s.heap[h]; + bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1; + if (bits > max_length) { + bits = max_length; + overflow++; + } + tree[n * 2 + 1]/*.Len*/ = bits; + /* We overwrite tree[n].Dad which is no longer needed */ + + if (n > max_code) { continue; } /* not a leaf node */ + + s.bl_count[bits]++; + xbits = 0; + if (n >= base) { + xbits = extra[n - base]; + } + f = tree[n * 2]/*.Freq*/; + s.opt_len += f * (bits + xbits); + if (has_stree) { + s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits); + } + } + if (overflow === 0) { return; } + + // Trace((stderr,"\nbit length overflow\n")); + /* This happens for example on obj2 and pic of the Calgary corpus */ + + /* Find the first bit length which could increase: */ + do { + bits = max_length - 1; + while (s.bl_count[bits] === 0) { bits--; } + s.bl_count[bits]--; /* move one leaf down the tree */ + s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */ + s.bl_count[max_length]--; + /* The brother of the overflow item also moves one step up, + * but this does not affect bl_count[max_length] + */ + overflow -= 2; + } while (overflow > 0); + + /* Now recompute all bit lengths, scanning in increasing frequency. + * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all + * lengths instead of fixing only the wrong ones. This idea is taken + * from 'ar' written by Haruhiko Okumura.) + */ + for (bits = max_length; bits !== 0; bits--) { + n = s.bl_count[bits]; + while (n !== 0) { + m = s.heap[--h]; + if (m > max_code) { continue; } + if (tree[m * 2 + 1]/*.Len*/ !== bits) { + // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); + s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/; + tree[m * 2 + 1]/*.Len*/ = bits; + } + n--; + } + } +} + + +/* =========================================================================== + * Generate the codes for a given tree and bit counts (which need not be + * optimal). + * IN assertion: the array bl_count contains the bit length statistics for + * the given tree and the field len is set for all tree elements. + * OUT assertion: the field code is set for all tree elements of non + * zero code length. + */ +function gen_codes(tree, max_code, bl_count) +// ct_data *tree; /* the tree to decorate */ +// int max_code; /* largest code with non zero frequency */ +// ushf *bl_count; /* number of codes at each bit length */ +{ + var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */ + var code = 0; /* running code value */ + var bits; /* bit index */ + var n; /* code index */ + + /* The distribution counts are first used to generate the code values + * without bit reversal. + */ + for (bits = 1; bits <= MAX_BITS; bits++) { + next_code[bits] = code = (code + bl_count[bits - 1]) << 1; + } + /* Check that the bit counts in bl_count are consistent. The last code + * must be all ones. + */ + //Assert (code + bl_count[MAX_BITS]-1 == (1< length code (0..28) */ + length = 0; + for (code = 0; code < LENGTH_CODES - 1; code++) { + base_length[code] = length; + for (n = 0; n < (1 << extra_lbits[code]); n++) { + _length_code[length++] = code; + } + } + //Assert (length == 256, "tr_static_init: length != 256"); + /* Note that the length 255 (match length 258) can be represented + * in two different ways: code 284 + 5 bits or code 285, so we + * overwrite length_code[255] to use the best encoding: + */ + _length_code[length - 1] = code; + + /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ + dist = 0; + for (code = 0; code < 16; code++) { + base_dist[code] = dist; + for (n = 0; n < (1 << extra_dbits[code]); n++) { + _dist_code[dist++] = code; + } + } + //Assert (dist == 256, "tr_static_init: dist != 256"); + dist >>= 7; /* from now on, all distances are divided by 128 */ + for (; code < D_CODES; code++) { + base_dist[code] = dist << 7; + for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) { + _dist_code[256 + dist++] = code; + } + } + //Assert (dist == 256, "tr_static_init: 256+dist != 512"); + + /* Construct the codes of the static literal tree */ + for (bits = 0; bits <= MAX_BITS; bits++) { + bl_count[bits] = 0; + } + + n = 0; + while (n <= 143) { + static_ltree[n * 2 + 1]/*.Len*/ = 8; + n++; + bl_count[8]++; + } + while (n <= 255) { + static_ltree[n * 2 + 1]/*.Len*/ = 9; + n++; + bl_count[9]++; + } + while (n <= 279) { + static_ltree[n * 2 + 1]/*.Len*/ = 7; + n++; + bl_count[7]++; + } + while (n <= 287) { + static_ltree[n * 2 + 1]/*.Len*/ = 8; + n++; + bl_count[8]++; + } + /* Codes 286 and 287 do not exist, but we must include them in the + * tree construction to get a canonical Huffman tree (longest code + * all ones) + */ + gen_codes(static_ltree, L_CODES + 1, bl_count); + + /* The static distance tree is trivial: */ + for (n = 0; n < D_CODES; n++) { + static_dtree[n * 2 + 1]/*.Len*/ = 5; + static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5); + } + + // Now data ready and we can init static trees + static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS); + static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); + static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); + + //static_init_done = true; +} + + +/* =========================================================================== + * Initialize a new block. + */ +function init_block(s) { + var n; /* iterates over tree elements */ + + /* Initialize the trees. */ + for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; } + for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; } + for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; } + + s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1; + s.opt_len = s.static_len = 0; + s.last_lit = s.matches = 0; +} + + +/* =========================================================================== + * Flush the bit buffer and align the output on a byte boundary + */ +function bi_windup(s) +{ + if (s.bi_valid > 8) { + put_short(s, s.bi_buf); + } else if (s.bi_valid > 0) { + //put_byte(s, (Byte)s->bi_buf); + s.pending_buf[s.pending++] = s.bi_buf; + } + s.bi_buf = 0; + s.bi_valid = 0; +} + +/* =========================================================================== + * Copy a stored block, storing first the length and its + * one's complement if requested. + */ +function copy_block(s, buf, len, header) +//DeflateState *s; +//charf *buf; /* the input data */ +//unsigned len; /* its length */ +//int header; /* true if block header must be written */ +{ + bi_windup(s); /* align on byte boundary */ + + if (header) { + put_short(s, len); + put_short(s, ~len); + } +// while (len--) { +// put_byte(s, *buf++); +// } + utils.arraySet(s.pending_buf, s.window, buf, len, s.pending); + s.pending += len; +} + +/* =========================================================================== + * Compares to subtrees, using the tree depth as tie breaker when + * the subtrees have equal frequency. This minimizes the worst case length. + */ +function smaller(tree, n, m, depth) { + var _n2 = n * 2; + var _m2 = m * 2; + return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || + (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m])); +} + +/* =========================================================================== + * Restore the heap property by moving down the tree starting at node k, + * exchanging a node with the smallest of its two sons if necessary, stopping + * when the heap property is re-established (each father smaller than its + * two sons). + */ +function pqdownheap(s, tree, k) +// deflate_state *s; +// ct_data *tree; /* the tree to restore */ +// int k; /* node to move down */ +{ + var v = s.heap[k]; + var j = k << 1; /* left son of k */ + while (j <= s.heap_len) { + /* Set j to the smallest of the two sons: */ + if (j < s.heap_len && + smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) { + j++; + } + /* Exit if v is smaller than both sons */ + if (smaller(tree, v, s.heap[j], s.depth)) { break; } + + /* Exchange v with the smallest son */ + s.heap[k] = s.heap[j]; + k = j; + + /* And continue down the tree, setting j to the left son of k */ + j <<= 1; + } + s.heap[k] = v; +} + + +// inlined manually +// var SMALLEST = 1; + +/* =========================================================================== + * Send the block data compressed using the given Huffman trees + */ +function compress_block(s, ltree, dtree) +// deflate_state *s; +// const ct_data *ltree; /* literal tree */ +// const ct_data *dtree; /* distance tree */ +{ + var dist; /* distance of matched string */ + var lc; /* match length or unmatched char (if dist == 0) */ + var lx = 0; /* running index in l_buf */ + var code; /* the code to send */ + var extra; /* number of extra bits to send */ + + if (s.last_lit !== 0) { + do { + dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]); + lc = s.pending_buf[s.l_buf + lx]; + lx++; + + if (dist === 0) { + send_code(s, lc, ltree); /* send a literal byte */ + //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); + } else { + /* Here, lc is the match length - MIN_MATCH */ + code = _length_code[lc]; + send_code(s, code + LITERALS + 1, ltree); /* send the length code */ + extra = extra_lbits[code]; + if (extra !== 0) { + lc -= base_length[code]; + send_bits(s, lc, extra); /* send the extra length bits */ + } + dist--; /* dist is now the match distance - 1 */ + code = d_code(dist); + //Assert (code < D_CODES, "bad d_code"); + + send_code(s, code, dtree); /* send the distance code */ + extra = extra_dbits[code]; + if (extra !== 0) { + dist -= base_dist[code]; + send_bits(s, dist, extra); /* send the extra distance bits */ + } + } /* literal or match pair ? */ + + /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ + //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, + // "pendingBuf overflow"); + + } while (lx < s.last_lit); + } + + send_code(s, END_BLOCK, ltree); +} + + +/* =========================================================================== + * Construct one Huffman tree and assigns the code bit strings and lengths. + * Update the total bit length for the current block. + * IN assertion: the field freq is set for all tree elements. + * OUT assertions: the fields len and code are set to the optimal bit length + * and corresponding code. The length opt_len is updated; static_len is + * also updated if stree is not null. The field max_code is set. + */ +function build_tree(s, desc) +// deflate_state *s; +// tree_desc *desc; /* the tree descriptor */ +{ + var tree = desc.dyn_tree; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var elems = desc.stat_desc.elems; + var n, m; /* iterate over heap elements */ + var max_code = -1; /* largest code with non zero frequency */ + var node; /* new node being created */ + + /* Construct the initial heap, with least frequent element in + * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. + * heap[0] is not used. + */ + s.heap_len = 0; + s.heap_max = HEAP_SIZE; + + for (n = 0; n < elems; n++) { + if (tree[n * 2]/*.Freq*/ !== 0) { + s.heap[++s.heap_len] = max_code = n; + s.depth[n] = 0; + + } else { + tree[n * 2 + 1]/*.Len*/ = 0; + } + } + + /* The pkzip format requires that at least one distance code exists, + * and that at least one bit should be sent even if there is only one + * possible code. So to avoid special checks later on we force at least + * two codes of non zero frequency. + */ + while (s.heap_len < 2) { + node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); + tree[node * 2]/*.Freq*/ = 1; + s.depth[node] = 0; + s.opt_len--; + + if (has_stree) { + s.static_len -= stree[node * 2 + 1]/*.Len*/; + } + /* node is 0 or 1 so it does not have extra bits */ + } + desc.max_code = max_code; + + /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, + * establish sub-heaps of increasing lengths: + */ + for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); } + + /* Construct the Huffman tree by repeatedly combining the least two + * frequent nodes. + */ + node = elems; /* next internal node of the tree */ + do { + //pqremove(s, tree, n); /* n = node of least frequency */ + /*** pqremove ***/ + n = s.heap[1/*SMALLEST*/]; + s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--]; + pqdownheap(s, tree, 1/*SMALLEST*/); + /***/ + + m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */ + + s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ + s.heap[--s.heap_max] = m; + + /* Create a new node father of n and m */ + tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/; + s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; + tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node; + + /* and insert the new node in the heap */ + s.heap[1/*SMALLEST*/] = node++; + pqdownheap(s, tree, 1/*SMALLEST*/); + + } while (s.heap_len >= 2); + + s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/]; + + /* At this point, the fields freq and dad are set. We can now + * generate the bit lengths. + */ + gen_bitlen(s, desc); + + /* The field len is now set, we can generate the bit codes */ + gen_codes(tree, max_code, s.bl_count); +} + + +/* =========================================================================== + * Scan a literal or distance tree to determine the frequencies of the codes + * in the bit length tree. + */ +function scan_tree(s, tree, max_code) +// deflate_state *s; +// ct_data *tree; /* the tree to be scanned */ +// int max_code; /* and its largest code of non zero frequency */ +{ + var n; /* iterates over all tree elements */ + var prevlen = -1; /* last emitted length */ + var curlen; /* length of current code */ + + var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ + + var count = 0; /* repeat count of the current code */ + var max_count = 7; /* max repeat count */ + var min_count = 4; /* min repeat count */ + + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */ + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; + + if (++count < max_count && curlen === nextlen) { + continue; + + } else if (count < min_count) { + s.bl_tree[curlen * 2]/*.Freq*/ += count; + + } else if (curlen !== 0) { + + if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; } + s.bl_tree[REP_3_6 * 2]/*.Freq*/++; + + } else if (count <= 10) { + s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++; + + } else { + s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++; + } + + count = 0; + prevlen = curlen; + + if (nextlen === 0) { + max_count = 138; + min_count = 3; + + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + + } else { + max_count = 7; + min_count = 4; + } + } +} + + +/* =========================================================================== + * Send a literal or distance tree in compressed form, using the codes in + * bl_tree. + */ +function send_tree(s, tree, max_code) +// deflate_state *s; +// ct_data *tree; /* the tree to be scanned */ +// int max_code; /* and its largest code of non zero frequency */ +{ + var n; /* iterates over all tree elements */ + var prevlen = -1; /* last emitted length */ + var curlen; /* length of current code */ + + var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ + + var count = 0; /* repeat count of the current code */ + var max_count = 7; /* max repeat count */ + var min_count = 4; /* min repeat count */ + + /* tree[max_code+1].Len = -1; */ /* guard already set */ + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; + + if (++count < max_count && curlen === nextlen) { + continue; + + } else if (count < min_count) { + do { send_code(s, curlen, s.bl_tree); } while (--count !== 0); + + } else if (curlen !== 0) { + if (curlen !== prevlen) { + send_code(s, curlen, s.bl_tree); + count--; + } + //Assert(count >= 3 && count <= 6, " 3_6?"); + send_code(s, REP_3_6, s.bl_tree); + send_bits(s, count - 3, 2); + + } else if (count <= 10) { + send_code(s, REPZ_3_10, s.bl_tree); + send_bits(s, count - 3, 3); + + } else { + send_code(s, REPZ_11_138, s.bl_tree); + send_bits(s, count - 11, 7); + } + + count = 0; + prevlen = curlen; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + + } else { + max_count = 7; + min_count = 4; + } + } +} + + +/* =========================================================================== + * Construct the Huffman tree for the bit lengths and return the index in + * bl_order of the last bit length code to send. + */ +function build_bl_tree(s) { + var max_blindex; /* index of last bit length code of non zero freq */ + + /* Determine the bit length frequencies for literal and distance trees */ + scan_tree(s, s.dyn_ltree, s.l_desc.max_code); + scan_tree(s, s.dyn_dtree, s.d_desc.max_code); + + /* Build the bit length tree: */ + build_tree(s, s.bl_desc); + /* opt_len now includes the length of the tree representations, except + * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. + */ + + /* Determine the number of bit length codes to send. The pkzip format + * requires that at least 4 bit length codes be sent. (appnote.txt says + * 3 but the actual value used is 4.) + */ + for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) { + if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) { + break; + } + } + /* Update opt_len to include the bit length tree and counts */ + s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; + //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", + // s->opt_len, s->static_len)); + + return max_blindex; +} + + +/* =========================================================================== + * Send the header for a block using dynamic Huffman trees: the counts, the + * lengths of the bit length codes, the literal tree and the distance tree. + * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. + */ +function send_all_trees(s, lcodes, dcodes, blcodes) +// deflate_state *s; +// int lcodes, dcodes, blcodes; /* number of codes for each tree */ +{ + var rank; /* index in bl_order */ + + //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); + //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, + // "too many codes"); + //Tracev((stderr, "\nbl counts: ")); + send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */ + send_bits(s, dcodes - 1, 5); + send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */ + for (rank = 0; rank < blcodes; rank++) { + //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); + send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3); + } + //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); + + send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */ + //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); + + send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */ + //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); +} + + +/* =========================================================================== + * Check if the data type is TEXT or BINARY, using the following algorithm: + * - TEXT if the two conditions below are satisfied: + * a) There are no non-portable control characters belonging to the + * "black list" (0..6, 14..25, 28..31). + * b) There is at least one printable character belonging to the + * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). + * - BINARY otherwise. + * - The following partially-portable control characters form a + * "gray list" that is ignored in this detection algorithm: + * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). + * IN assertion: the fields Freq of dyn_ltree are set. + */ +function detect_data_type(s) { + /* black_mask is the bit mask of black-listed bytes + * set bits 0..6, 14..25, and 28..31 + * 0xf3ffc07f = binary 11110011111111111100000001111111 + */ + var black_mask = 0xf3ffc07f; + var n; + + /* Check for non-textual ("black-listed") bytes. */ + for (n = 0; n <= 31; n++, black_mask >>>= 1) { + if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) { + return Z_BINARY; + } + } + + /* Check for textual ("white-listed") bytes. */ + if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 || + s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) { + return Z_TEXT; + } + for (n = 32; n < LITERALS; n++) { + if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { + return Z_TEXT; + } + } + + /* There are no "black-listed" or "white-listed" bytes: + * this stream either is empty or has tolerated ("gray-listed") bytes only. + */ + return Z_BINARY; +} + + +var static_init_done = false; + +/* =========================================================================== + * Initialize the tree data structures for a new zlib stream. + */ +function _tr_init(s) +{ + + if (!static_init_done) { + tr_static_init(); + static_init_done = true; + } + + s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); + s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); + s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); + + s.bi_buf = 0; + s.bi_valid = 0; + + /* Initialize the first block of the first file: */ + init_block(s); +} + + +/* =========================================================================== + * Send a stored block + */ +function _tr_stored_block(s, buf, stored_len, last) +//DeflateState *s; +//charf *buf; /* input block */ +//ulg stored_len; /* length of input block */ +//int last; /* one if this is the last block for a file */ +{ + send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */ + copy_block(s, buf, stored_len, true); /* with header */ +} + + +/* =========================================================================== + * Send one empty static block to give enough lookahead for inflate. + * This takes 10 bits, of which 7 may remain in the bit buffer. + */ +function _tr_align(s) { + send_bits(s, STATIC_TREES << 1, 3); + send_code(s, END_BLOCK, static_ltree); + bi_flush(s); +} + + +/* =========================================================================== + * Determine the best encoding for the current block: dynamic trees, static + * trees or store, and output the encoded block to the zip file. + */ +function _tr_flush_block(s, buf, stored_len, last) +//DeflateState *s; +//charf *buf; /* input block, or NULL if too old */ +//ulg stored_len; /* length of input block */ +//int last; /* one if this is the last block for a file */ +{ + var opt_lenb, static_lenb; /* opt_len and static_len in bytes */ + var max_blindex = 0; /* index of last bit length code of non zero freq */ + + /* Build the Huffman trees unless a stored block is forced */ + if (s.level > 0) { + + /* Check if the file is binary or text */ + if (s.strm.data_type === Z_UNKNOWN) { + s.strm.data_type = detect_data_type(s); + } + + /* Construct the literal and distance trees */ + build_tree(s, s.l_desc); + // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, + // s->static_len)); + + build_tree(s, s.d_desc); + // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, + // s->static_len)); + /* At this point, opt_len and static_len are the total bit lengths of + * the compressed block data, excluding the tree representations. + */ + + /* Build the bit length tree for the above two trees, and get the index + * in bl_order of the last bit length code to send. + */ + max_blindex = build_bl_tree(s); + + /* Determine the best encoding. Compute the block lengths in bytes. */ + opt_lenb = (s.opt_len + 3 + 7) >>> 3; + static_lenb = (s.static_len + 3 + 7) >>> 3; + + // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", + // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, + // s->last_lit)); + + if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; } + + } else { + // Assert(buf != (char*)0, "lost buf"); + opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ + } + + if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) { + /* 4: two words for the lengths */ + + /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. + * Otherwise we can't have processed more than WSIZE input bytes since + * the last block flush, because compression would have been + * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to + * transform a block into a stored block. + */ + _tr_stored_block(s, buf, stored_len, last); + + } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { + + send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3); + compress_block(s, static_ltree, static_dtree); + + } else { + send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3); + send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1); + compress_block(s, s.dyn_ltree, s.dyn_dtree); + } + // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); + /* The above check is made mod 2^32, for files larger than 512 MB + * and uLong implemented on 32 bits. + */ + init_block(s); + + if (last) { + bi_windup(s); + } + // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, + // s->compressed_len-7*last)); +} + +/* =========================================================================== + * Save the match info and tally the frequency counts. Return true if + * the current block must be flushed. + */ +function _tr_tally(s, dist, lc) +// deflate_state *s; +// unsigned dist; /* distance of matched string */ +// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ +{ + //var out_length, in_length, dcode; + + s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff; + s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; + + s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; + s.last_lit++; + + if (dist === 0) { + /* lc is the unmatched char */ + s.dyn_ltree[lc * 2]/*.Freq*/++; + } else { + s.matches++; + /* Here, lc is the match length - MIN_MATCH */ + dist--; /* dist = match distance - 1 */ + //Assert((ush)dist < (ush)MAX_DIST(s) && + // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && + // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); + + s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++; + s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++; + } + +// (!) This block is disabled in zlib defaults, +// don't enable it for binary compatibility + +//#ifdef TRUNCATE_BLOCK +// /* Try to guess if it is profitable to stop the current block here */ +// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { +// /* Compute an upper bound for the compressed length */ +// out_length = s.last_lit*8; +// in_length = s.strstart - s.block_start; +// +// for (dcode = 0; dcode < D_CODES; dcode++) { +// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); +// } +// out_length >>>= 3; +// //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", +// // s->last_lit, in_length, out_length, +// // 100L - out_length*100L/in_length)); +// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { +// return true; +// } +// } +//#endif + + return (s.last_lit === s.lit_bufsize - 1); + /* We avoid equality with lit_bufsize because of wraparound at 64K + * on 16 bit machines and because stored blocks are restricted to + * 64K-1 bytes. + */ +} + +exports._tr_init = _tr_init; +exports._tr_stored_block = _tr_stored_block; +exports._tr_flush_block = _tr_flush_block; +exports._tr_tally = _tr_tally; +exports._tr_align = _tr_align; + + +/***/ }), + +/***/ 6442: +/***/ ((module) => { + +"use strict"; + + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +function ZStream() { + /* next input byte */ + this.input = null; // JS specific, because we have no pointers + this.next_in = 0; + /* number of bytes available at input */ + this.avail_in = 0; + /* total number of input bytes read so far */ + this.total_in = 0; + /* next output byte should be put there */ + this.output = null; // JS specific, because we have no pointers + this.next_out = 0; + /* remaining free space at output */ + this.avail_out = 0; + /* total number of bytes output so far */ + this.total_out = 0; + /* last error message, NULL if no error */ + this.msg = ''/*Z_NULL*/; + /* not visible by applications */ + this.state = null; + /* best guess about the data type: binary or text */ + this.data_type = 2/*Z_UNKNOWN*/; + /* adler32 value of the uncompressed data */ + this.adler = 0; +} + +module.exports = ZStream; + + +/***/ }), + +/***/ 5807: +/***/ ((module) => { + +module.exports = function parseBMFontAscii(data) { + if (!data) + throw new Error('no data provided') + data = data.toString().trim() + + var output = { + pages: [], + chars: [], + kernings: [] + } + + var lines = data.split(/\r\n?|\n/g) + + if (lines.length === 0) + throw new Error('no data in BMFont file') + + for (var i = 0; i < lines.length; i++) { + var lineData = splitLine(lines[i], i) + if (!lineData) //skip empty lines + continue + + if (lineData.key === 'page') { + if (typeof lineData.data.id !== 'number') + throw new Error('malformed file at line ' + i + ' -- needs page id=N') + if (typeof lineData.data.file !== 'string') + throw new Error('malformed file at line ' + i + ' -- needs page file="path"') + output.pages[lineData.data.id] = lineData.data.file + } else if (lineData.key === 'chars' || lineData.key === 'kernings') { + //... do nothing for these two ... + } else if (lineData.key === 'char') { + output.chars.push(lineData.data) + } else if (lineData.key === 'kerning') { + output.kernings.push(lineData.data) + } else { + output[lineData.key] = lineData.data + } + } + + return output +} + +function splitLine(line, idx) { + line = line.replace(/\t+/g, ' ').trim() + if (!line) + return null + + var space = line.indexOf(' ') + if (space === -1) + throw new Error("no named row at line " + idx) + + var key = line.substring(0, space) + + line = line.substring(space + 1) + //clear "letter" field as it is non-standard and + //requires additional complexity to parse " / = symbols + line = line.replace(/letter=[\'\"]\S+[\'\"]/gi, '') + line = line.split("=") + line = line.map(function(str) { + return str.trim().match((/(".*?"|[^"\s]+)+(?=\s*|\s*$)/g)) + }) + + var data = [] + for (var i = 0; i < line.length; i++) { + var dt = line[i] + if (i === 0) { + data.push({ + key: dt[0], + data: "" + }) + } else if (i === line.length - 1) { + data[data.length - 1].data = parseData(dt[0]) + } else { + data[data.length - 1].data = parseData(dt[0]) + data.push({ + key: dt[1], + data: "" + }) + } + } + + var out = { + key: key, + data: {} + } + + data.forEach(function(v) { + out.data[v.key] = v.data; + }) + + return out +} + +function parseData(data) { + if (!data || data.length === 0) + return "" + + if (data.indexOf('"') === 0 || data.indexOf("'") === 0) + return data.substring(1, data.length - 1) + if (data.indexOf(',') !== -1) + return parseIntList(data) + return parseInt(data, 10) +} + +function parseIntList(data) { + return data.split(',').map(function(val) { + return parseInt(val, 10) + }) +} + +/***/ }), + +/***/ 4563: +/***/ ((module) => { + +var HEADER = [66, 77, 70] + +module.exports = function readBMFontBinary(buf) { + if (buf.length < 6) + throw new Error('invalid buffer length for BMFont') + + var header = HEADER.every(function(byte, i) { + return buf.readUInt8(i) === byte + }) + + if (!header) + throw new Error('BMFont missing BMF byte header') + + var i = 3 + var vers = buf.readUInt8(i++) + if (vers > 3) + throw new Error('Only supports BMFont Binary v3 (BMFont App v1.10)') + + var target = { kernings: [], chars: [] } + for (var b=0; b<5; b++) + i += readBlock(target, buf, i) + return target +} + +function readBlock(target, buf, i) { + if (i > buf.length-1) + return 0 + + var blockID = buf.readUInt8(i++) + var blockSize = buf.readInt32LE(i) + i += 4 + + switch(blockID) { + case 1: + target.info = readInfo(buf, i) + break + case 2: + target.common = readCommon(buf, i) + break + case 3: + target.pages = readPages(buf, i, blockSize) + break + case 4: + target.chars = readChars(buf, i, blockSize) + break + case 5: + target.kernings = readKernings(buf, i, blockSize) + break + } + return 5 + blockSize +} + +function readInfo(buf, i) { + var info = {} + info.size = buf.readInt16LE(i) + + var bitField = buf.readUInt8(i+2) + info.smooth = (bitField >> 7) & 1 + info.unicode = (bitField >> 6) & 1 + info.italic = (bitField >> 5) & 1 + info.bold = (bitField >> 4) & 1 + + //fixedHeight is only mentioned in binary spec + if ((bitField >> 3) & 1) + info.fixedHeight = 1 + + info.charset = buf.readUInt8(i+3) || '' + info.stretchH = buf.readUInt16LE(i+4) + info.aa = buf.readUInt8(i+6) + info.padding = [ + buf.readInt8(i+7), + buf.readInt8(i+8), + buf.readInt8(i+9), + buf.readInt8(i+10) + ] + info.spacing = [ + buf.readInt8(i+11), + buf.readInt8(i+12) + ] + info.outline = buf.readUInt8(i+13) + info.face = readStringNT(buf, i+14) + return info +} + +function readCommon(buf, i) { + var common = {} + common.lineHeight = buf.readUInt16LE(i) + common.base = buf.readUInt16LE(i+2) + common.scaleW = buf.readUInt16LE(i+4) + common.scaleH = buf.readUInt16LE(i+6) + common.pages = buf.readUInt16LE(i+8) + var bitField = buf.readUInt8(i+10) + common.packed = 0 + common.alphaChnl = buf.readUInt8(i+11) + common.redChnl = buf.readUInt8(i+12) + common.greenChnl = buf.readUInt8(i+13) + common.blueChnl = buf.readUInt8(i+14) + return common +} + +function readPages(buf, i, size) { + var pages = [] + var text = readNameNT(buf, i) + var len = text.length+1 + var count = size / len + for (var c=0; c { + +var xml2js = __nccwpck_require__(6189) +var parseAttributes = __nccwpck_require__(820) + +module.exports = function parseBMFontXML(data) { + data = data.toString().trim() + + var output = { + pages: [], + chars: [], + kernings: [] + } + + xml2js.parseString(data, function(err, result) { + if (err) + throw err + if (!result.font) + throw "XML bitmap font doesn't have root" + result = result.font + + output.common = parseAttributes(result.common[0].$) + output.info = parseAttributes(result.info[0].$) + + for (var i = 0; i < result.pages.length; i++) { + var p = result.pages[i].page[0].$ + + if (typeof p.id === "undefined") + throw new Error("malformed file -- needs page id=N") + if (typeof p.file !== "string") + throw new Error("malformed file -- needs page file=\"path\"") + + output.pages[parseInt(p.id, 10)] = p.file + } + + if (result.chars) { + var chrArray = result.chars[0]['char'] || [] + for (var i = 0; i < chrArray.length; i++) { + output.chars.push(parseAttributes(chrArray[i].$)) + } + } + + if (result.kernings) { + var kernArray = result.kernings[0]['kerning'] || [] + for (var i = 0; i < kernArray.length; i++) { + output.kernings.push(parseAttributes(kernArray[i].$)) + } + } + }) + return output +} + + +/***/ }), + +/***/ 820: +/***/ ((module) => { + +//Some versions of GlyphDesigner have a typo +//that causes some bugs with parsing. +//Need to confirm with recent version of the software +//to see whether this is still an issue or not. +var GLYPH_DESIGNER_ERROR = 'chasrset' + +module.exports = function parseAttributes(obj) { + if (GLYPH_DESIGNER_ERROR in obj) { + obj['charset'] = obj[GLYPH_DESIGNER_ERROR] + delete obj[GLYPH_DESIGNER_ERROR] + } + + for (var k in obj) { + if (k === 'face' || k === 'charset') + continue + else if (k === 'padding' || k === 'spacing') + obj[k] = parseIntList(obj[k]) + else + obj[k] = parseInt(obj[k], 10) + } + return obj +} + +function parseIntList(data) { + return data.split(',').map(function(val) { + return parseInt(val, 10) + }) +} + +/***/ }), + +/***/ 6130: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +var _typeof=typeof Symbol==='function'&&typeof Symbol.iterator==='symbol'?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==='function'&&obj.constructor===Symbol&&obj!==Symbol.prototype?'symbol':typeof obj};var http=__nccwpck_require__(3685);var https=__nccwpck_require__(5687);var url=__nccwpck_require__(7310);var qs=__nccwpck_require__(3477);var zlib=__nccwpck_require__(9796);var util=__nccwpck_require__(3837);var phin=function phin(opts,cb){if(typeof opts!=='string'){if(!opts.hasOwnProperty('url')){throw new Error('Missing url option from options for request method.')}}var addr=(typeof opts==='undefined'?'undefined':_typeof(opts))==='object'?url.parse(opts.url):url.parse(opts);var options={'hostname':addr.hostname,'port':addr.port||(addr.protocol.toLowerCase()==='http:'?80:443),'path':addr.path,'method':'GET','headers':{},'auth':addr.auth||null,'parse':'none','stream':false};if((typeof opts==='undefined'?'undefined':_typeof(opts))==='object'){options=Object.assign(options,opts)}options.port=Number(options.port);if(options.hasOwnProperty('timeout'))delete options.timeout;if(options.compressed===true){options.headers['accept-encoding']='gzip, deflate'}if(opts.hasOwnProperty('form')){if(_typeof(opts.form)!=='object'){throw new Error('phin \'form\' option must be of type Object if present.')}var formDataString=qs.stringify(opts.form);options.headers['Content-Type']='application/x-www-form-urlencoded';options.headers['Content-Length']=Buffer.byteLength(formDataString);opts.data=formDataString}var req=void 0;var resHandler=function resHandler(res){var stream=res;if(options.compressed===true){if(res.headers['content-encoding']==='gzip'){stream=res.pipe(zlib.createGunzip())}else if(res.headers['content-encoding']==='deflate'){stream=res.pipe(zlib.createInflate())}}if(options.stream===true){res.stream=stream;if(cb)cb(null,res)}else{res.body=new Buffer([]);stream.on('data',function(chunk){res.body=Buffer.concat([res.body,chunk])});stream.on('end',function(){if(cb){if(options.parse==='json'){try{res.body=JSON.parse(res.body.toString())}catch(err){cb('Invalid JSON received.',res);return}}cb(null,res)}})}};switch(addr.protocol.toLowerCase()){case'http:':req=http.request(options,resHandler);break;case'https:':req=https.request(options,resHandler);break;default:if(cb)cb(new Error('Invalid / unknown URL protocol. Expected HTTP or HTTPS.'),null);return;}if(typeof opts.timeout==='number'){req.setTimeout(opts.timeout,function(){req.abort();if(cb)cb(new Error('Timeout has been reached.'),null);cb=null})}req.on('error',function(err){if(cb)cb(err,null)});if(opts.hasOwnProperty('data')){var postData=opts.data;if(!(opts.data instanceof Buffer)&&_typeof(opts.data)==='object'){var contentType=options.headers['content-type']||options.headers['Content-Type'];if(contentType==='application/x-www-form-urlencoded'){postData=qs.stringify(opts.data)}else{try{postData=JSON.stringify(opts.data)}catch(err){if(cb)cb(new Error('Couldn\'t stringify object. (Likely due to a circular reference.)'),null)}}}req.write(postData)}req.end()};phin.promisified=function(opts,http){return new Promise(function(resolve,reject){phin(opts,function(err,res){if(err){reject(err)}else{resolve(res)}},http)})};if(util.promisify){phin[util.promisify.custom]=phin.promisified}module.exports=phin; + + +/***/ }), + +/***/ 6097: +/***/ ((module) => { + +"use strict"; + + +module.exports = pixelmatch; + +function pixelmatch(img1, img2, output, width, height, options) { + + if (!options) options = {}; + + var threshold = options.threshold === undefined ? 0.1 : options.threshold; + + // maximum acceptable square distance between two colors; + // 35215 is the maximum possible value for the YIQ difference metric + var maxDelta = 35215 * threshold * threshold, + diff = 0; + + // compare each pixel of one image against the other one + for (var y = 0; y < height; y++) { + for (var x = 0; x < width; x++) { + + var pos = (y * width + x) * 4; + + // squared YUV distance between colors at this pixel position + var delta = colorDelta(img1, img2, pos, pos); + + // the color difference is above the threshold + if (delta > maxDelta) { + // check it's a real rendering difference or just anti-aliasing + if (!options.includeAA && (antialiased(img1, x, y, width, height, img2) || + antialiased(img2, x, y, width, height, img1))) { + // one of the pixels is anti-aliasing; draw as yellow and do not count as difference + if (output) drawPixel(output, pos, 255, 255, 0); + + } else { + // found substantial difference not caused by anti-aliasing; draw it as red + if (output) drawPixel(output, pos, 255, 0, 0); + diff++; + } + + } else if (output) { + // pixels are similar; draw background as grayscale image blended with white + var val = blend(grayPixel(img1, pos), 0.1); + drawPixel(output, pos, val, val, val); + } + } + } + + // return the number of different pixels + return diff; +} + +// check if a pixel is likely a part of anti-aliasing; +// based on "Anti-aliased Pixel and Intensity Slope Detector" paper by V. Vysniauskas, 2009 + +function antialiased(img, x1, y1, width, height, img2) { + var x0 = Math.max(x1 - 1, 0), + y0 = Math.max(y1 - 1, 0), + x2 = Math.min(x1 + 1, width - 1), + y2 = Math.min(y1 + 1, height - 1), + pos = (y1 * width + x1) * 4, + zeroes = 0, + positives = 0, + negatives = 0, + min = 0, + max = 0, + minX, minY, maxX, maxY; + + // go through 8 adjacent pixels + for (var x = x0; x <= x2; x++) { + for (var y = y0; y <= y2; y++) { + if (x === x1 && y === y1) continue; + + // brightness delta between the center pixel and adjacent one + var delta = colorDelta(img, img, pos, (y * width + x) * 4, true); + + // count the number of equal, darker and brighter adjacent pixels + if (delta === 0) zeroes++; + else if (delta < 0) negatives++; + else if (delta > 0) positives++; + + // if found more than 2 equal siblings, it's definitely not anti-aliasing + if (zeroes > 2) return false; + + if (!img2) continue; + + // remember the darkest pixel + if (delta < min) { + min = delta; + minX = x; + minY = y; + } + // remember the brightest pixel + if (delta > max) { + max = delta; + maxX = x; + maxY = y; + } + } + } + + if (!img2) return true; + + // if there are no both darker and brighter pixels among siblings, it's not anti-aliasing + if (negatives === 0 || positives === 0) return false; + + // if either the darkest or the brightest pixel has more than 2 equal siblings in both images + // (definitely not anti-aliased), this pixel is anti-aliased + return (!antialiased(img, minX, minY, width, height) && !antialiased(img2, minX, minY, width, height)) || + (!antialiased(img, maxX, maxY, width, height) && !antialiased(img2, maxX, maxY, width, height)); +} + +// calculate color difference according to the paper "Measuring perceived color difference +// using YIQ NTSC transmission color space in mobile applications" by Y. Kotsarenko and F. Ramos + +function colorDelta(img1, img2, k, m, yOnly) { + var a1 = img1[k + 3] / 255, + a2 = img2[m + 3] / 255, + + r1 = blend(img1[k + 0], a1), + g1 = blend(img1[k + 1], a1), + b1 = blend(img1[k + 2], a1), + + r2 = blend(img2[m + 0], a2), + g2 = blend(img2[m + 1], a2), + b2 = blend(img2[m + 2], a2), + + y = rgb2y(r1, g1, b1) - rgb2y(r2, g2, b2); + + if (yOnly) return y; // brightness difference only + + var i = rgb2i(r1, g1, b1) - rgb2i(r2, g2, b2), + q = rgb2q(r1, g1, b1) - rgb2q(r2, g2, b2); + + return 0.5053 * y * y + 0.299 * i * i + 0.1957 * q * q; +} + +function rgb2y(r, g, b) { return r * 0.29889531 + g * 0.58662247 + b * 0.11448223; } +function rgb2i(r, g, b) { return r * 0.59597799 - g * 0.27417610 - b * 0.32180189; } +function rgb2q(r, g, b) { return r * 0.21147017 - g * 0.52261711 + b * 0.31114694; } + +// blend semi-transparent color with white +function blend(c, a) { + return 255 + (c - 255) * a; +} + +function drawPixel(output, pos, r, g, b) { + output[pos + 0] = r; + output[pos + 1] = g; + output[pos + 2] = b; + output[pos + 3] = 255; +} + +function grayPixel(img, i) { + var a = img[i + 3] / 255, + r = blend(img[i + 0], a), + g = blend(img[i + 1], a), + b = blend(img[i + 2], a); + return rgb2y(r, g, b); +} + + +/***/ }), + +/***/ 8054: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +var interlaceUtils = __nccwpck_require__(3365); + +var pixelBppMapper = [ + // 0 - dummy entry + function() {}, + + // 1 - L + // 0: 0, 1: 0, 2: 0, 3: 0xff + function(pxData, data, pxPos, rawPos) { + if (rawPos === data.length) { + throw new Error('Ran out of data'); + } + + var pixel = data[rawPos]; + pxData[pxPos] = pixel; + pxData[pxPos + 1] = pixel; + pxData[pxPos + 2] = pixel; + pxData[pxPos + 3] = 0xff; + }, + + // 2 - LA + // 0: 0, 1: 0, 2: 0, 3: 1 + function(pxData, data, pxPos, rawPos) { + if (rawPos + 1 >= data.length) { + throw new Error('Ran out of data'); + } + + var pixel = data[rawPos]; + pxData[pxPos] = pixel; + pxData[pxPos + 1] = pixel; + pxData[pxPos + 2] = pixel; + pxData[pxPos + 3] = data[rawPos + 1]; + }, + + // 3 - RGB + // 0: 0, 1: 1, 2: 2, 3: 0xff + function(pxData, data, pxPos, rawPos) { + if (rawPos + 2 >= data.length) { + throw new Error('Ran out of data'); + } + + pxData[pxPos] = data[rawPos]; + pxData[pxPos + 1] = data[rawPos + 1]; + pxData[pxPos + 2] = data[rawPos + 2]; + pxData[pxPos + 3] = 0xff; + }, + + // 4 - RGBA + // 0: 0, 1: 1, 2: 2, 3: 3 + function(pxData, data, pxPos, rawPos) { + if (rawPos + 3 >= data.length) { + throw new Error('Ran out of data'); + } + + pxData[pxPos] = data[rawPos]; + pxData[pxPos + 1] = data[rawPos + 1]; + pxData[pxPos + 2] = data[rawPos + 2]; + pxData[pxPos + 3] = data[rawPos + 3]; + } +]; + +var pixelBppCustomMapper = [ + // 0 - dummy entry + function() {}, + + // 1 - L + // 0: 0, 1: 0, 2: 0, 3: 0xff + function(pxData, pixelData, pxPos, maxBit) { + var pixel = pixelData[0]; + pxData[pxPos] = pixel; + pxData[pxPos + 1] = pixel; + pxData[pxPos + 2] = pixel; + pxData[pxPos + 3] = maxBit; + }, + + // 2 - LA + // 0: 0, 1: 0, 2: 0, 3: 1 + function(pxData, pixelData, pxPos) { + var pixel = pixelData[0]; + pxData[pxPos] = pixel; + pxData[pxPos + 1] = pixel; + pxData[pxPos + 2] = pixel; + pxData[pxPos + 3] = pixelData[1]; + }, + + // 3 - RGB + // 0: 0, 1: 1, 2: 2, 3: 0xff + function(pxData, pixelData, pxPos, maxBit) { + pxData[pxPos] = pixelData[0]; + pxData[pxPos + 1] = pixelData[1]; + pxData[pxPos + 2] = pixelData[2]; + pxData[pxPos + 3] = maxBit; + }, + + // 4 - RGBA + // 0: 0, 1: 1, 2: 2, 3: 3 + function(pxData, pixelData, pxPos) { + pxData[pxPos] = pixelData[0]; + pxData[pxPos + 1] = pixelData[1]; + pxData[pxPos + 2] = pixelData[2]; + pxData[pxPos + 3] = pixelData[3]; + } +]; + +function bitRetriever(data, depth) { + + var leftOver = []; + var i = 0; + + function split() { + if (i === data.length) { + throw new Error('Ran out of data'); + } + var byte = data[i]; + i++; + var byte8, byte7, byte6, byte5, byte4, byte3, byte2, byte1; + switch (depth) { + default: + throw new Error('unrecognised depth'); + case 16: + byte2 = data[i]; + i++; + leftOver.push(((byte << 8) + byte2)); + break; + case 4: + byte2 = byte & 0x0f; + byte1 = byte >> 4; + leftOver.push(byte1, byte2); + break; + case 2: + byte4 = byte & 3; + byte3 = byte >> 2 & 3; + byte2 = byte >> 4 & 3; + byte1 = byte >> 6 & 3; + leftOver.push(byte1, byte2, byte3, byte4); + break; + case 1: + byte8 = byte & 1; + byte7 = byte >> 1 & 1; + byte6 = byte >> 2 & 1; + byte5 = byte >> 3 & 1; + byte4 = byte >> 4 & 1; + byte3 = byte >> 5 & 1; + byte2 = byte >> 6 & 1; + byte1 = byte >> 7 & 1; + leftOver.push(byte1, byte2, byte3, byte4, byte5, byte6, byte7, byte8); + break; + } + } + + return { + get: function(count) { + while (leftOver.length < count) { + split(); + } + var returner = leftOver.slice(0, count); + leftOver = leftOver.slice(count); + return returner; + }, + resetAfterLine: function() { + leftOver.length = 0; + }, + end: function() { + if (i !== data.length) { + throw new Error('extra data found'); + } + } + }; +} + +function mapImage8Bit(image, pxData, getPxPos, bpp, data, rawPos) { // eslint-disable-line max-params + var imageWidth = image.width; + var imageHeight = image.height; + var imagePass = image.index; + for (var y = 0; y < imageHeight; y++) { + for (var x = 0; x < imageWidth; x++) { + var pxPos = getPxPos(x, y, imagePass); + pixelBppMapper[bpp](pxData, data, pxPos, rawPos); + rawPos += bpp; //eslint-disable-line no-param-reassign + } + } + return rawPos; +} + +function mapImageCustomBit(image, pxData, getPxPos, bpp, bits, maxBit) { // eslint-disable-line max-params + var imageWidth = image.width; + var imageHeight = image.height; + var imagePass = image.index; + for (var y = 0; y < imageHeight; y++) { + for (var x = 0; x < imageWidth; x++) { + var pixelData = bits.get(bpp); + var pxPos = getPxPos(x, y, imagePass); + pixelBppCustomMapper[bpp](pxData, pixelData, pxPos, maxBit); + } + bits.resetAfterLine(); + } +} + +exports.dataToBitMap = function(data, bitmapInfo) { + + var width = bitmapInfo.width; + var height = bitmapInfo.height; + var depth = bitmapInfo.depth; + var bpp = bitmapInfo.bpp; + var interlace = bitmapInfo.interlace; + + if (depth !== 8) { + var bits = bitRetriever(data, depth); + } + var pxData; + if (depth <= 8) { + pxData = new Buffer(width * height * 4); + } + else { + pxData = new Uint16Array(width * height * 4); + } + var maxBit = Math.pow(2, depth) - 1; + var rawPos = 0; + var images; + var getPxPos; + + if (interlace) { + images = interlaceUtils.getImagePasses(width, height); + getPxPos = interlaceUtils.getInterlaceIterator(width, height); + } + else { + var nonInterlacedPxPos = 0; + getPxPos = function() { + var returner = nonInterlacedPxPos; + nonInterlacedPxPos += 4; + return returner; + }; + images = [{ width: width, height: height }]; + } + + for (var imageIndex = 0; imageIndex < images.length; imageIndex++) { + if (depth === 8) { + rawPos = mapImage8Bit(images[imageIndex], pxData, getPxPos, bpp, data, rawPos); + } + else { + mapImageCustomBit(images[imageIndex], pxData, getPxPos, bpp, bits, maxBit); + } + } + if (depth === 8) { + if (rawPos !== data.length) { + throw new Error('extra data found'); + } + } + else { + bits.end(); + } + + return pxData; +}; + + +/***/ }), + +/***/ 6659: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var constants = __nccwpck_require__(3316); + +module.exports = function(dataIn, width, height, options) { + var outHasAlpha = [constants.COLORTYPE_COLOR_ALPHA, constants.COLORTYPE_ALPHA].indexOf(options.colorType) !== -1; + if (options.colorType === options.inputColorType) { + var bigEndian = (function() { + var buffer = new ArrayBuffer(2); + new DataView(buffer).setInt16(0, 256, true /* littleEndian */); + // Int16Array uses the platform's endianness. + return new Int16Array(buffer)[0] !== 256; + })(); + // If no need to convert to grayscale and alpha is present/absent in both, take a fast route + if (options.bitDepth === 8 || (options.bitDepth === 16 && bigEndian)) { + return dataIn; + } + } + + // map to a UInt16 array if data is 16bit, fix endianness below + var data = options.bitDepth !== 16 ? dataIn : new Uint16Array(dataIn.buffer); + + var maxValue = 255; + var inBpp = constants.COLORTYPE_TO_BPP_MAP[options.inputColorType]; + if (inBpp === 4 && !options.inputHasAlpha) { + inBpp = 3; + } + var outBpp = constants.COLORTYPE_TO_BPP_MAP[options.colorType]; + if (options.bitDepth === 16) { + maxValue = 65535; + outBpp *= 2; + } + var outData = new Buffer(width * height * outBpp); + + var inIndex = 0; + var outIndex = 0; + + var bgColor = options.bgColor || {}; + if (bgColor.red === undefined) { + bgColor.red = maxValue; + } + if (bgColor.green === undefined) { + bgColor.green = maxValue; + } + if (bgColor.blue === undefined) { + bgColor.blue = maxValue; + } + + function getRGBA() { + var red; + var green; + var blue; + var alpha = maxValue; + switch (options.inputColorType) { + case constants.COLORTYPE_COLOR_ALPHA: + alpha = data[inIndex + 3]; + red = data[inIndex]; + green = data[inIndex + 1]; + blue = data[inIndex + 2]; + break; + case constants.COLORTYPE_COLOR: + red = data[inIndex]; + green = data[inIndex + 1]; + blue = data[inIndex + 2]; + break; + case constants.COLORTYPE_ALPHA: + alpha = data[inIndex + 1]; + red = data[inIndex]; + green = red; + blue = red; + break; + case constants.COLORTYPE_GRAYSCALE: + red = data[inIndex]; + green = red; + blue = red; + break; + default: + throw new Error('input color type:' + options.inputColorType + ' is not supported at present'); + } + + if (options.inputHasAlpha) { + if (!outHasAlpha) { + alpha /= maxValue; + red = Math.min(Math.max(Math.round((1 - alpha) * bgColor.red + alpha * red), 0), maxValue); + green = Math.min(Math.max(Math.round((1 - alpha) * bgColor.green + alpha * green), 0), maxValue); + blue = Math.min(Math.max(Math.round((1 - alpha) * bgColor.blue + alpha * blue), 0), maxValue); + } + } + return { red: red, green: green, blue: blue, alpha: alpha }; + } + + for (var y = 0; y < height; y++) { + for (var x = 0; x < width; x++) { + var rgba = getRGBA(data, inIndex); + + switch (options.colorType) { + case constants.COLORTYPE_COLOR_ALPHA: + case constants.COLORTYPE_COLOR: + if (options.bitDepth === 8) { + outData[outIndex] = rgba.red; + outData[outIndex + 1] = rgba.green; + outData[outIndex + 2] = rgba.blue; + if (outHasAlpha) { + outData[outIndex + 3] = rgba.alpha; + } + } + else { + outData.writeUInt16BE(rgba.red, outIndex); + outData.writeUInt16BE(rgba.green, outIndex + 2); + outData.writeUInt16BE(rgba.blue, outIndex + 4); + if (outHasAlpha) { + outData.writeUInt16BE(rgba.alpha, outIndex + 6); + } + } + break; + case constants.COLORTYPE_ALPHA: + case constants.COLORTYPE_GRAYSCALE: + // Convert to grayscale and alpha + var grayscale = (rgba.red + rgba.green + rgba.blue) / 3; + if (options.bitDepth === 8) { + outData[outIndex] = grayscale; + if (outHasAlpha) { + outData[outIndex + 1] = rgba.alpha; + } + } + else { + outData.writeUInt16BE(grayscale, outIndex); + if (outHasAlpha) { + outData.writeUInt16BE(rgba.alpha, outIndex + 2); + } + } + break; + default: + throw new Error('unrecognised color Type ' + options.colorType); + } + + inIndex += inBpp; + outIndex += outBpp; + } + } + + return outData; +}; + + +/***/ }), + +/***/ 4036: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + + +var util = __nccwpck_require__(3837); +var Stream = __nccwpck_require__(2781); + + +var ChunkStream = module.exports = function() { + Stream.call(this); + + this._buffers = []; + this._buffered = 0; + + this._reads = []; + this._paused = false; + + this._encoding = 'utf8'; + this.writable = true; +}; +util.inherits(ChunkStream, Stream); + + +ChunkStream.prototype.read = function(length, callback) { + + this._reads.push({ + length: Math.abs(length), // if length < 0 then at most this length + allowLess: length < 0, + func: callback + }); + + process.nextTick(function() { + this._process(); + + // its paused and there is not enought data then ask for more + if (this._paused && this._reads.length > 0) { + this._paused = false; + + this.emit('drain'); + } + }.bind(this)); +}; + +ChunkStream.prototype.write = function(data, encoding) { + + if (!this.writable) { + this.emit('error', new Error('Stream not writable')); + return false; + } + + var dataBuffer; + if (Buffer.isBuffer(data)) { + dataBuffer = data; + } + else { + dataBuffer = new Buffer(data, encoding || this._encoding); + } + + this._buffers.push(dataBuffer); + this._buffered += dataBuffer.length; + + this._process(); + + // ok if there are no more read requests + if (this._reads && this._reads.length === 0) { + this._paused = true; + } + + return this.writable && !this._paused; +}; + +ChunkStream.prototype.end = function(data, encoding) { + + if (data) { + this.write(data, encoding); + } + + this.writable = false; + + // already destroyed + if (!this._buffers) { + return; + } + + // enqueue or handle end + if (this._buffers.length === 0) { + this._end(); + } + else { + this._buffers.push(null); + this._process(); + } +}; + +ChunkStream.prototype.destroySoon = ChunkStream.prototype.end; + +ChunkStream.prototype._end = function() { + + if (this._reads.length > 0) { + this.emit('error', + new Error('Unexpected end of input') + ); + } + + this.destroy(); +}; + +ChunkStream.prototype.destroy = function() { + + if (!this._buffers) { + return; + } + + this.writable = false; + this._reads = null; + this._buffers = null; + + this.emit('close'); +}; + +ChunkStream.prototype._processReadAllowingLess = function(read) { + // ok there is any data so that we can satisfy this request + this._reads.shift(); // == read + + // first we need to peek into first buffer + var smallerBuf = this._buffers[0]; + + // ok there is more data than we need + if (smallerBuf.length > read.length) { + + this._buffered -= read.length; + this._buffers[0] = smallerBuf.slice(read.length); + + read.func.call(this, smallerBuf.slice(0, read.length)); + + } + else { + // ok this is less than maximum length so use it all + this._buffered -= smallerBuf.length; + this._buffers.shift(); // == smallerBuf + + read.func.call(this, smallerBuf); + } +}; + +ChunkStream.prototype._processRead = function(read) { + this._reads.shift(); // == read + + var pos = 0; + var count = 0; + var data = new Buffer(read.length); + + // create buffer for all data + while (pos < read.length) { + + var buf = this._buffers[count++]; + var len = Math.min(buf.length, read.length - pos); + + buf.copy(data, pos, 0, len); + pos += len; + + // last buffer wasn't used all so just slice it and leave + if (len !== buf.length) { + this._buffers[--count] = buf.slice(len); + } + } + + // remove all used buffers + if (count > 0) { + this._buffers.splice(0, count); + } + + this._buffered -= read.length; + + read.func.call(this, data); +}; + +ChunkStream.prototype._process = function() { + + try { + // as long as there is any data and read requests + while (this._buffered > 0 && this._reads && this._reads.length > 0) { + + var read = this._reads[0]; + + // read any data (but no more than length) + if (read.allowLess) { + this._processReadAllowingLess(read); + + } + else if (this._buffered >= read.length) { + // ok we can meet some expectations + + this._processRead(read); + } + else { + // not enought data to satisfy first request in queue + // so we need to wait for more + break; + } + } + + if (this._buffers && !this.writable) { + this._end(); + } + } + catch (ex) { + this.emit('error', ex); + } +}; + + +/***/ }), + +/***/ 3316: +/***/ ((module) => { + +"use strict"; + + + +module.exports = { + + PNG_SIGNATURE: [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a], + + TYPE_IHDR: 0x49484452, + TYPE_IEND: 0x49454e44, + TYPE_IDAT: 0x49444154, + TYPE_PLTE: 0x504c5445, + TYPE_tRNS: 0x74524e53, // eslint-disable-line camelcase + TYPE_gAMA: 0x67414d41, // eslint-disable-line camelcase + + // color-type bits + COLORTYPE_GRAYSCALE: 0, + COLORTYPE_PALETTE: 1, + COLORTYPE_COLOR: 2, + COLORTYPE_ALPHA: 4, // e.g. grayscale and alpha + + // color-type combinations + COLORTYPE_PALETTE_COLOR: 3, + COLORTYPE_COLOR_ALPHA: 6, + + COLORTYPE_TO_BPP_MAP: { + 0: 1, + 2: 3, + 3: 1, + 4: 2, + 6: 4 + }, + + GAMMA_DIVISION: 100000 +}; + + +/***/ }), + +/***/ 5987: +/***/ ((module) => { + +"use strict"; + + +var crcTable = []; + +(function() { + for (var i = 0; i < 256; i++) { + var currentCrc = i; + for (var j = 0; j < 8; j++) { + if (currentCrc & 1) { + currentCrc = 0xedb88320 ^ (currentCrc >>> 1); + } + else { + currentCrc = currentCrc >>> 1; + } + } + crcTable[i] = currentCrc; + } +}()); + +var CrcCalculator = module.exports = function() { + this._crc = -1; +}; + +CrcCalculator.prototype.write = function(data) { + + for (var i = 0; i < data.length; i++) { + this._crc = crcTable[(this._crc ^ data[i]) & 0xff] ^ (this._crc >>> 8); + } + return true; +}; + +CrcCalculator.prototype.crc32 = function() { + return this._crc ^ -1; +}; + + +CrcCalculator.crc32 = function(buf) { + + var crc = -1; + for (var i = 0; i < buf.length; i++) { + crc = crcTable[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8); + } + return crc ^ -1; +}; + + +/***/ }), + +/***/ 7581: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var paethPredictor = __nccwpck_require__(5252); + +function filterNone(pxData, pxPos, byteWidth, rawData, rawPos) { + + for (var x = 0; x < byteWidth; x++) { + rawData[rawPos + x] = pxData[pxPos + x]; + } +} + +function filterSumNone(pxData, pxPos, byteWidth) { + + var sum = 0; + var length = pxPos + byteWidth; + + for (var i = pxPos; i < length; i++) { + sum += Math.abs(pxData[i]); + } + return sum; +} + +function filterSub(pxData, pxPos, byteWidth, rawData, rawPos, bpp) { + + for (var x = 0; x < byteWidth; x++) { + + var left = x >= bpp ? pxData[pxPos + x - bpp] : 0; + var val = pxData[pxPos + x] - left; + + rawData[rawPos + x] = val; + } +} + +function filterSumSub(pxData, pxPos, byteWidth, bpp) { + + var sum = 0; + for (var x = 0; x < byteWidth; x++) { + + var left = x >= bpp ? pxData[pxPos + x - bpp] : 0; + var val = pxData[pxPos + x] - left; + + sum += Math.abs(val); + } + + return sum; +} + +function filterUp(pxData, pxPos, byteWidth, rawData, rawPos) { + + for (var x = 0; x < byteWidth; x++) { + + var up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0; + var val = pxData[pxPos + x] - up; + + rawData[rawPos + x] = val; + } +} + +function filterSumUp(pxData, pxPos, byteWidth) { + + var sum = 0; + var length = pxPos + byteWidth; + for (var x = pxPos; x < length; x++) { + + var up = pxPos > 0 ? pxData[x - byteWidth] : 0; + var val = pxData[x] - up; + + sum += Math.abs(val); + } + + return sum; +} + +function filterAvg(pxData, pxPos, byteWidth, rawData, rawPos, bpp) { + + for (var x = 0; x < byteWidth; x++) { + + var left = x >= bpp ? pxData[pxPos + x - bpp] : 0; + var up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0; + var val = pxData[pxPos + x] - ((left + up) >> 1); + + rawData[rawPos + x] = val; + } +} + +function filterSumAvg(pxData, pxPos, byteWidth, bpp) { + + var sum = 0; + for (var x = 0; x < byteWidth; x++) { + + var left = x >= bpp ? pxData[pxPos + x - bpp] : 0; + var up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0; + var val = pxData[pxPos + x] - ((left + up) >> 1); + + sum += Math.abs(val); + } + + return sum; +} + +function filterPaeth(pxData, pxPos, byteWidth, rawData, rawPos, bpp) { + + for (var x = 0; x < byteWidth; x++) { + + var left = x >= bpp ? pxData[pxPos + x - bpp] : 0; + var up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0; + var upleft = pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0; + var val = pxData[pxPos + x] - paethPredictor(left, up, upleft); + + rawData[rawPos + x] = val; + } +} + +function filterSumPaeth(pxData, pxPos, byteWidth, bpp) { + var sum = 0; + for (var x = 0; x < byteWidth; x++) { + + var left = x >= bpp ? pxData[pxPos + x - bpp] : 0; + var up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0; + var upleft = pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0; + var val = pxData[pxPos + x] - paethPredictor(left, up, upleft); + + sum += Math.abs(val); + } + + return sum; +} + +var filters = { + 0: filterNone, + 1: filterSub, + 2: filterUp, + 3: filterAvg, + 4: filterPaeth +}; + +var filterSums = { + 0: filterSumNone, + 1: filterSumSub, + 2: filterSumUp, + 3: filterSumAvg, + 4: filterSumPaeth +}; + +module.exports = function(pxData, width, height, options, bpp) { + + var filterTypes; + if (!('filterType' in options) || options.filterType === -1) { + filterTypes = [0, 1, 2, 3, 4]; + } + else if (typeof options.filterType === 'number') { + filterTypes = [options.filterType]; + } + else { + throw new Error('unrecognised filter types'); + } + + if (options.bitDepth === 16) { + bpp *= 2; + } + var byteWidth = width * bpp; + var rawPos = 0; + var pxPos = 0; + var rawData = new Buffer((byteWidth + 1) * height); + + var sel = filterTypes[0]; + + for (var y = 0; y < height; y++) { + + if (filterTypes.length > 1) { + // find best filter for this line (with lowest sum of values) + var min = Infinity; + + for (var i = 0; i < filterTypes.length; i++) { + var sum = filterSums[filterTypes[i]](pxData, pxPos, byteWidth, bpp); + if (sum < min) { + sel = filterTypes[i]; + min = sum; + } + } + } + + rawData[rawPos] = sel; + rawPos++; + filters[sel](pxData, pxPos, byteWidth, rawData, rawPos, bpp); + rawPos += byteWidth; + pxPos += byteWidth; + } + return rawData; +}; + + +/***/ }), + +/***/ 528: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var util = __nccwpck_require__(3837); +var ChunkStream = __nccwpck_require__(4036); +var Filter = __nccwpck_require__(6601); + + +var FilterAsync = module.exports = function(bitmapInfo) { + ChunkStream.call(this); + + var buffers = []; + var that = this; + this._filter = new Filter(bitmapInfo, { + read: this.read.bind(this), + write: function(buffer) { + buffers.push(buffer); + }, + complete: function() { + that.emit('complete', Buffer.concat(buffers)); + } + }); + + this._filter.start(); +}; +util.inherits(FilterAsync, ChunkStream); + + +/***/ }), + +/***/ 8505: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +var SyncReader = __nccwpck_require__(3652); +var Filter = __nccwpck_require__(6601); + + +exports.process = function(inBuffer, bitmapInfo) { + + var outBuffers = []; + var reader = new SyncReader(inBuffer); + var filter = new Filter(bitmapInfo, { + read: reader.read.bind(reader), + write: function(bufferPart) { + outBuffers.push(bufferPart); + }, + complete: function() { + } + }); + + filter.start(); + reader.process(); + + return Buffer.concat(outBuffers); +}; + +/***/ }), + +/***/ 6601: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var interlaceUtils = __nccwpck_require__(3365); +var paethPredictor = __nccwpck_require__(5252); + +function getByteWidth(width, bpp, depth) { + var byteWidth = width * bpp; + if (depth !== 8) { + byteWidth = Math.ceil(byteWidth / (8 / depth)); + } + return byteWidth; +} + +var Filter = module.exports = function(bitmapInfo, dependencies) { + + var width = bitmapInfo.width; + var height = bitmapInfo.height; + var interlace = bitmapInfo.interlace; + var bpp = bitmapInfo.bpp; + var depth = bitmapInfo.depth; + + this.read = dependencies.read; + this.write = dependencies.write; + this.complete = dependencies.complete; + + this._imageIndex = 0; + this._images = []; + if (interlace) { + var passes = interlaceUtils.getImagePasses(width, height); + for (var i = 0; i < passes.length; i++) { + this._images.push({ + byteWidth: getByteWidth(passes[i].width, bpp, depth), + height: passes[i].height, + lineIndex: 0 + }); + } + } + else { + this._images.push({ + byteWidth: getByteWidth(width, bpp, depth), + height: height, + lineIndex: 0 + }); + } + + // when filtering the line we look at the pixel to the left + // the spec also says it is done on a byte level regardless of the number of pixels + // so if the depth is byte compatible (8 or 16) we subtract the bpp in order to compare back + // a pixel rather than just a different byte part. However if we are sub byte, we ignore. + if (depth === 8) { + this._xComparison = bpp; + } + else if (depth === 16) { + this._xComparison = bpp * 2; + } + else { + this._xComparison = 1; + } +}; + +Filter.prototype.start = function() { + this.read(this._images[this._imageIndex].byteWidth + 1, this._reverseFilterLine.bind(this)); +}; + +Filter.prototype._unFilterType1 = function(rawData, unfilteredLine, byteWidth) { + + var xComparison = this._xComparison; + var xBiggerThan = xComparison - 1; + + for (var x = 0; x < byteWidth; x++) { + var rawByte = rawData[1 + x]; + var f1Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0; + unfilteredLine[x] = rawByte + f1Left; + } +}; + +Filter.prototype._unFilterType2 = function(rawData, unfilteredLine, byteWidth) { + + var lastLine = this._lastLine; + + for (var x = 0; x < byteWidth; x++) { + var rawByte = rawData[1 + x]; + var f2Up = lastLine ? lastLine[x] : 0; + unfilteredLine[x] = rawByte + f2Up; + } +}; + +Filter.prototype._unFilterType3 = function(rawData, unfilteredLine, byteWidth) { + + var xComparison = this._xComparison; + var xBiggerThan = xComparison - 1; + var lastLine = this._lastLine; + + for (var x = 0; x < byteWidth; x++) { + var rawByte = rawData[1 + x]; + var f3Up = lastLine ? lastLine[x] : 0; + var f3Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0; + var f3Add = Math.floor((f3Left + f3Up) / 2); + unfilteredLine[x] = rawByte + f3Add; + } +}; + +Filter.prototype._unFilterType4 = function(rawData, unfilteredLine, byteWidth) { + + var xComparison = this._xComparison; + var xBiggerThan = xComparison - 1; + var lastLine = this._lastLine; + + for (var x = 0; x < byteWidth; x++) { + var rawByte = rawData[1 + x]; + var f4Up = lastLine ? lastLine[x] : 0; + var f4Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0; + var f4UpLeft = x > xBiggerThan && lastLine ? lastLine[x - xComparison] : 0; + var f4Add = paethPredictor(f4Left, f4Up, f4UpLeft); + unfilteredLine[x] = rawByte + f4Add; + } +}; + +Filter.prototype._reverseFilterLine = function(rawData) { + + var filter = rawData[0]; + var unfilteredLine; + var currentImage = this._images[this._imageIndex]; + var byteWidth = currentImage.byteWidth; + + if (filter === 0) { + unfilteredLine = rawData.slice(1, byteWidth + 1); + } + else { + + unfilteredLine = new Buffer(byteWidth); + + switch (filter) { + case 1: + this._unFilterType1(rawData, unfilteredLine, byteWidth); + break; + case 2: + this._unFilterType2(rawData, unfilteredLine, byteWidth); + break; + case 3: + this._unFilterType3(rawData, unfilteredLine, byteWidth); + break; + case 4: + this._unFilterType4(rawData, unfilteredLine, byteWidth); + break; + default: + throw new Error('Unrecognised filter type - ' + filter); + } + } + + this.write(unfilteredLine); + + currentImage.lineIndex++; + if (currentImage.lineIndex >= currentImage.height) { + this._lastLine = null; + this._imageIndex++; + currentImage = this._images[this._imageIndex]; + } + else { + this._lastLine = unfilteredLine; + } + + if (currentImage) { + // read, using the byte width that may be from the new current image + this.read(currentImage.byteWidth + 1, this._reverseFilterLine.bind(this)); + } + else { + this._lastLine = null; + this.complete(); + } +}; + + +/***/ }), + +/***/ 3928: +/***/ ((module) => { + +"use strict"; + + +function dePalette(indata, outdata, width, height, palette) { + var pxPos = 0; + // use values from palette + for (var y = 0; y < height; y++) { + for (var x = 0; x < width; x++) { + var color = palette[indata[pxPos]]; + + if (!color) { + throw new Error('index ' + indata[pxPos] + ' not in palette'); + } + + for (var i = 0; i < 4; i++) { + outdata[pxPos + i] = color[i]; + } + pxPos += 4; + } + } +} + +function replaceTransparentColor(indata, outdata, width, height, transColor) { + var pxPos = 0; + for (var y = 0; y < height; y++) { + for (var x = 0; x < width; x++) { + var makeTrans = false; + + if (transColor.length === 1) { + if (transColor[0] === indata[pxPos]) { + makeTrans = true; + } + } + else if (transColor[0] === indata[pxPos] && transColor[1] === indata[pxPos + 1] && transColor[2] === indata[pxPos + 2]) { + makeTrans = true; + } + if (makeTrans) { + for (var i = 0; i < 4; i++) { + outdata[pxPos + i] = 0; + } + } + pxPos += 4; + } + } +} + +function scaleDepth(indata, outdata, width, height, depth) { + var maxOutSample = 255; + var maxInSample = Math.pow(2, depth) - 1; + var pxPos = 0; + + for (var y = 0; y < height; y++) { + for (var x = 0; x < width; x++) { + for (var i = 0; i < 4; i++) { + outdata[pxPos + i] = Math.floor((indata[pxPos + i] * maxOutSample) / maxInSample + 0.5); + } + pxPos += 4; + } + } +} + +module.exports = function(indata, imageData) { + + var depth = imageData.depth; + var width = imageData.width; + var height = imageData.height; + var colorType = imageData.colorType; + var transColor = imageData.transColor; + var palette = imageData.palette; + + var outdata = indata; // only different for 16 bits + + if (colorType === 3) { // paletted + dePalette(indata, outdata, width, height, palette); + } + else { + if (transColor) { + replaceTransparentColor(indata, outdata, width, height, transColor); + } + // if it needs scaling + if (depth !== 8) { + // if we need to change the buffer size + if (depth === 16) { + outdata = new Buffer(width * height * 4); + } + scaleDepth(indata, outdata, width, height, depth); + } + } + return outdata; +}; + + +/***/ }), + +/***/ 3365: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +// Adam 7 +// 0 1 2 3 4 5 6 7 +// 0 x 6 4 6 x 6 4 6 +// 1 7 7 7 7 7 7 7 7 +// 2 5 6 5 6 5 6 5 6 +// 3 7 7 7 7 7 7 7 7 +// 4 3 6 4 6 3 6 4 6 +// 5 7 7 7 7 7 7 7 7 +// 6 5 6 5 6 5 6 5 6 +// 7 7 7 7 7 7 7 7 7 + + +var imagePasses = [ + { // pass 1 - 1px + x: [0], + y: [0] + }, + { // pass 2 - 1px + x: [4], + y: [0] + }, + { // pass 3 - 2px + x: [0, 4], + y: [4] + }, + { // pass 4 - 4px + x: [2, 6], + y: [0, 4] + }, + { // pass 5 - 8px + x: [0, 2, 4, 6], + y: [2, 6] + }, + { // pass 6 - 16px + x: [1, 3, 5, 7], + y: [0, 2, 4, 6] + }, + { // pass 7 - 32px + x: [0, 1, 2, 3, 4, 5, 6, 7], + y: [1, 3, 5, 7] + } +]; + +exports.getImagePasses = function(width, height) { + var images = []; + var xLeftOver = width % 8; + var yLeftOver = height % 8; + var xRepeats = (width - xLeftOver) / 8; + var yRepeats = (height - yLeftOver) / 8; + for (var i = 0; i < imagePasses.length; i++) { + var pass = imagePasses[i]; + var passWidth = xRepeats * pass.x.length; + var passHeight = yRepeats * pass.y.length; + for (var j = 0; j < pass.x.length; j++) { + if (pass.x[j] < xLeftOver) { + passWidth++; + } + else { + break; + } + } + for (j = 0; j < pass.y.length; j++) { + if (pass.y[j] < yLeftOver) { + passHeight++; + } + else { + break; + } + } + if (passWidth > 0 && passHeight > 0) { + images.push({ width: passWidth, height: passHeight, index: i }); + } + } + return images; +}; + +exports.getInterlaceIterator = function(width) { + return function(x, y, pass) { + var outerXLeftOver = x % imagePasses[pass].x.length; + var outerX = (((x - outerXLeftOver) / imagePasses[pass].x.length) * 8) + imagePasses[pass].x[outerXLeftOver]; + var outerYLeftOver = y % imagePasses[pass].y.length; + var outerY = (((y - outerYLeftOver) / imagePasses[pass].y.length) * 8) + imagePasses[pass].y[outerYLeftOver]; + return (outerX * 4) + (outerY * width * 4); + }; +}; + +/***/ }), + +/***/ 2584: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var util = __nccwpck_require__(3837); +var Stream = __nccwpck_require__(2781); +var constants = __nccwpck_require__(3316); +var Packer = __nccwpck_require__(1710); + +var PackerAsync = module.exports = function(opt) { + Stream.call(this); + + var options = opt || {}; + + this._packer = new Packer(options); + this._deflate = this._packer.createDeflate(); + + this.readable = true; +}; +util.inherits(PackerAsync, Stream); + + +PackerAsync.prototype.pack = function(data, width, height, gamma) { + // Signature + this.emit('data', new Buffer(constants.PNG_SIGNATURE)); + this.emit('data', this._packer.packIHDR(width, height)); + + if (gamma) { + this.emit('data', this._packer.packGAMA(gamma)); + } + + var filteredData = this._packer.filterData(data, width, height); + + // compress it + this._deflate.on('error', this.emit.bind(this, 'error')); + + this._deflate.on('data', function(compressedData) { + this.emit('data', this._packer.packIDAT(compressedData)); + }.bind(this)); + + this._deflate.on('end', function() { + this.emit('data', this._packer.packIEND()); + this.emit('end'); + }.bind(this)); + + this._deflate.end(filteredData); +}; + + +/***/ }), + +/***/ 7100: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var hasSyncZlib = true; +var zlib = __nccwpck_require__(9796); +if (!zlib.deflateSync) { + hasSyncZlib = false; +} +var constants = __nccwpck_require__(3316); +var Packer = __nccwpck_require__(1710); + +module.exports = function(metaData, opt) { + + if (!hasSyncZlib) { + throw new Error('To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0'); + } + + var options = opt || {}; + + var packer = new Packer(options); + + var chunks = []; + + // Signature + chunks.push(new Buffer(constants.PNG_SIGNATURE)); + + // Header + chunks.push(packer.packIHDR(metaData.width, metaData.height)); + + if (metaData.gamma) { + chunks.push(packer.packGAMA(metaData.gamma)); + } + + var filteredData = packer.filterData(metaData.data, metaData.width, metaData.height); + + // compress it + var compressedData = zlib.deflateSync(filteredData, packer.getDeflateOptions()); + filteredData = null; + + if (!compressedData || !compressedData.length) { + throw new Error('bad png - invalid compressed data response'); + } + chunks.push(packer.packIDAT(compressedData)); + + // End + chunks.push(packer.packIEND()); + + return Buffer.concat(chunks); +}; + + +/***/ }), + +/***/ 1710: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var constants = __nccwpck_require__(3316); +var CrcStream = __nccwpck_require__(5987); +var bitPacker = __nccwpck_require__(6659); +var filter = __nccwpck_require__(7581); +var zlib = __nccwpck_require__(9796); + +var Packer = module.exports = function(options) { + this._options = options; + + options.deflateChunkSize = options.deflateChunkSize || 32 * 1024; + options.deflateLevel = options.deflateLevel != null ? options.deflateLevel : 9; + options.deflateStrategy = options.deflateStrategy != null ? options.deflateStrategy : 3; + options.inputHasAlpha = options.inputHasAlpha != null ? options.inputHasAlpha : true; + options.deflateFactory = options.deflateFactory || zlib.createDeflate; + options.bitDepth = options.bitDepth || 8; + // This is outputColorType + options.colorType = (typeof options.colorType === 'number') ? options.colorType : constants.COLORTYPE_COLOR_ALPHA; + options.inputColorType = (typeof options.inputColorType === 'number') ? options.inputColorType : constants.COLORTYPE_COLOR_ALPHA; + + if ([ + constants.COLORTYPE_GRAYSCALE, + constants.COLORTYPE_COLOR, + constants.COLORTYPE_COLOR_ALPHA, + constants.COLORTYPE_ALPHA + ].indexOf(options.colorType) === -1) { + throw new Error('option color type:' + options.colorType + ' is not supported at present'); + } + if ([ + constants.COLORTYPE_GRAYSCALE, + constants.COLORTYPE_COLOR, + constants.COLORTYPE_COLOR_ALPHA, + constants.COLORTYPE_ALPHA + ].indexOf(options.inputColorType) === -1) { + throw new Error('option input color type:' + options.inputColorType + ' is not supported at present'); + } + if (options.bitDepth !== 8 && options.bitDepth !== 16) { + throw new Error('option bit depth:' + options.bitDepth + ' is not supported at present'); + } +}; + +Packer.prototype.getDeflateOptions = function() { + return { + chunkSize: this._options.deflateChunkSize, + level: this._options.deflateLevel, + strategy: this._options.deflateStrategy + }; +}; + +Packer.prototype.createDeflate = function() { + return this._options.deflateFactory(this.getDeflateOptions()); +}; + +Packer.prototype.filterData = function(data, width, height) { + // convert to correct format for filtering (e.g. right bpp and bit depth) + var packedData = bitPacker(data, width, height, this._options); + + // filter pixel data + var bpp = constants.COLORTYPE_TO_BPP_MAP[this._options.colorType]; + var filteredData = filter(packedData, width, height, this._options, bpp); + return filteredData; +}; + +Packer.prototype._packChunk = function(type, data) { + + var len = (data ? data.length : 0); + var buf = new Buffer(len + 12); + + buf.writeUInt32BE(len, 0); + buf.writeUInt32BE(type, 4); + + if (data) { + data.copy(buf, 8); + } + + buf.writeInt32BE(CrcStream.crc32(buf.slice(4, buf.length - 4)), buf.length - 4); + return buf; +}; + +Packer.prototype.packGAMA = function(gamma) { + var buf = new Buffer(4); + buf.writeUInt32BE(Math.floor(gamma * constants.GAMMA_DIVISION), 0); + return this._packChunk(constants.TYPE_gAMA, buf); +}; + +Packer.prototype.packIHDR = function(width, height) { + + var buf = new Buffer(13); + buf.writeUInt32BE(width, 0); + buf.writeUInt32BE(height, 4); + buf[8] = this._options.bitDepth; // Bit depth + buf[9] = this._options.colorType; // colorType + buf[10] = 0; // compression + buf[11] = 0; // filter + buf[12] = 0; // interlace + + return this._packChunk(constants.TYPE_IHDR, buf); +}; + +Packer.prototype.packIDAT = function(data) { + return this._packChunk(constants.TYPE_IDAT, data); +}; + +Packer.prototype.packIEND = function() { + return this._packChunk(constants.TYPE_IEND, null); +}; + + +/***/ }), + +/***/ 5252: +/***/ ((module) => { + +"use strict"; + + +module.exports = function paethPredictor(left, above, upLeft) { + + var paeth = left + above - upLeft; + var pLeft = Math.abs(paeth - left); + var pAbove = Math.abs(paeth - above); + var pUpLeft = Math.abs(paeth - upLeft); + + if (pLeft <= pAbove && pLeft <= pUpLeft) { + return left; + } + if (pAbove <= pUpLeft) { + return above; + } + return upLeft; +}; + +/***/ }), + +/***/ 699: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var util = __nccwpck_require__(3837); +var zlib = __nccwpck_require__(9796); +var ChunkStream = __nccwpck_require__(4036); +var FilterAsync = __nccwpck_require__(528); +var Parser = __nccwpck_require__(2225); +var bitmapper = __nccwpck_require__(8054); +var formatNormaliser = __nccwpck_require__(3928); + +var ParserAsync = module.exports = function(options) { + ChunkStream.call(this); + + this._parser = new Parser(options, { + read: this.read.bind(this), + error: this._handleError.bind(this), + metadata: this._handleMetaData.bind(this), + gamma: this.emit.bind(this, 'gamma'), + palette: this._handlePalette.bind(this), + transColor: this._handleTransColor.bind(this), + finished: this._finished.bind(this), + inflateData: this._inflateData.bind(this), + simpleTransparency: this._simpleTransparency.bind(this), + headersFinished: this._headersFinished.bind(this) + }); + this._options = options; + this.writable = true; + + this._parser.start(); +}; +util.inherits(ParserAsync, ChunkStream); + + +ParserAsync.prototype._handleError = function(err) { + + this.emit('error', err); + + this.writable = false; + + this.destroy(); + + if (this._inflate && this._inflate.destroy) { + this._inflate.destroy(); + } + + if (this._filter) { + this._filter.destroy(); + // For backward compatibility with Node 7 and below. + // Suppress errors due to _inflate calling write() even after + // it's destroy()'ed. + this._filter.on('error', function() {}); + } + + this.errord = true; +}; + +ParserAsync.prototype._inflateData = function(data) { + if (!this._inflate) { + if (this._bitmapInfo.interlace) { + this._inflate = zlib.createInflate(); + + this._inflate.on('error', this.emit.bind(this, 'error')); + this._filter.on('complete', this._complete.bind(this)); + + this._inflate.pipe(this._filter); + } + else { + var rowSize = ((this._bitmapInfo.width * this._bitmapInfo.bpp * this._bitmapInfo.depth + 7) >> 3) + 1; + var imageSize = rowSize * this._bitmapInfo.height; + var chunkSize = Math.max(imageSize, zlib.Z_MIN_CHUNK); + + this._inflate = zlib.createInflate({ chunkSize: chunkSize }); + var leftToInflate = imageSize; + + var emitError = this.emit.bind(this, 'error'); + this._inflate.on('error', function(err) { + if (!leftToInflate) { + return; + } + + emitError(err); + }); + this._filter.on('complete', this._complete.bind(this)); + + var filterWrite = this._filter.write.bind(this._filter); + this._inflate.on('data', function(chunk) { + if (!leftToInflate) { + return; + } + + if (chunk.length > leftToInflate) { + chunk = chunk.slice(0, leftToInflate); + } + + leftToInflate -= chunk.length; + + filterWrite(chunk); + }); + + this._inflate.on('end', this._filter.end.bind(this._filter)); + } + } + this._inflate.write(data); +}; + +ParserAsync.prototype._handleMetaData = function(metaData) { + this._metaData = metaData; + this._bitmapInfo = Object.create(metaData); + + this._filter = new FilterAsync(this._bitmapInfo); +}; + +ParserAsync.prototype._handleTransColor = function(transColor) { + this._bitmapInfo.transColor = transColor; +}; + +ParserAsync.prototype._handlePalette = function(palette) { + this._bitmapInfo.palette = palette; +}; + +ParserAsync.prototype._simpleTransparency = function() { + this._metaData.alpha = true; +}; + +ParserAsync.prototype._headersFinished = function() { + // Up until this point, we don't know if we have a tRNS chunk (alpha) + // so we can't emit metadata any earlier + this.emit('metadata', this._metaData); +}; + +ParserAsync.prototype._finished = function() { + if (this.errord) { + return; + } + + if (!this._inflate) { + this.emit('error', 'No Inflate block'); + } + else { + // no more data to inflate + this._inflate.end(); + } + this.destroySoon(); +}; + +ParserAsync.prototype._complete = function(filteredData) { + + if (this.errord) { + return; + } + + try { + var bitmapData = bitmapper.dataToBitMap(filteredData, this._bitmapInfo); + + var normalisedBitmapData = formatNormaliser(bitmapData, this._bitmapInfo); + bitmapData = null; + } + catch (ex) { + this._handleError(ex); + return; + } + + this.emit('parsed', normalisedBitmapData); +}; + + +/***/ }), + +/***/ 29: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var hasSyncZlib = true; +var zlib = __nccwpck_require__(9796); +var inflateSync = __nccwpck_require__(5331); +if (!zlib.deflateSync) { + hasSyncZlib = false; +} +var SyncReader = __nccwpck_require__(3652); +var FilterSync = __nccwpck_require__(8505); +var Parser = __nccwpck_require__(2225); +var bitmapper = __nccwpck_require__(8054); +var formatNormaliser = __nccwpck_require__(3928); + + +module.exports = function(buffer, options) { + + if (!hasSyncZlib) { + throw new Error('To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0'); + } + + var err; + function handleError(_err_) { + err = _err_; + } + + var metaData; + function handleMetaData(_metaData_) { + metaData = _metaData_; + } + + function handleTransColor(transColor) { + metaData.transColor = transColor; + } + + function handlePalette(palette) { + metaData.palette = palette; + } + + function handleSimpleTransparency() { + metaData.alpha = true; + } + + var gamma; + function handleGamma(_gamma_) { + gamma = _gamma_; + } + + var inflateDataList = []; + function handleInflateData(inflatedData) { + inflateDataList.push(inflatedData); + } + + var reader = new SyncReader(buffer); + + var parser = new Parser(options, { + read: reader.read.bind(reader), + error: handleError, + metadata: handleMetaData, + gamma: handleGamma, + palette: handlePalette, + transColor: handleTransColor, + inflateData: handleInflateData, + simpleTransparency: handleSimpleTransparency + }); + + parser.start(); + reader.process(); + + if (err) { + throw err; + } + + //join together the inflate datas + var inflateData = Buffer.concat(inflateDataList); + inflateDataList.length = 0; + + var inflatedData; + if (metaData.interlace) { + inflatedData = zlib.inflateSync(inflateData); + } + else { + var rowSize = ((metaData.width * metaData.bpp * metaData.depth + 7) >> 3) + 1; + var imageSize = rowSize * metaData.height; + inflatedData = inflateSync(inflateData, { chunkSize: imageSize, maxLength: imageSize }); + } + inflateData = null; + + if (!inflatedData || !inflatedData.length) { + throw new Error('bad png - invalid inflate data response'); + } + + var unfilteredData = FilterSync.process(inflatedData, metaData); + inflateData = null; + + var bitmapData = bitmapper.dataToBitMap(unfilteredData, metaData); + unfilteredData = null; + + var normalisedBitmapData = formatNormaliser(bitmapData, metaData); + + metaData.data = normalisedBitmapData; + metaData.gamma = gamma || 0; + + return metaData; +}; + + +/***/ }), + +/***/ 2225: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var constants = __nccwpck_require__(3316); +var CrcCalculator = __nccwpck_require__(5987); + + +var Parser = module.exports = function(options, dependencies) { + + this._options = options; + options.checkCRC = options.checkCRC !== false; + + this._hasIHDR = false; + this._hasIEND = false; + this._emittedHeadersFinished = false; + + // input flags/metadata + this._palette = []; + this._colorType = 0; + + this._chunks = {}; + this._chunks[constants.TYPE_IHDR] = this._handleIHDR.bind(this); + this._chunks[constants.TYPE_IEND] = this._handleIEND.bind(this); + this._chunks[constants.TYPE_IDAT] = this._handleIDAT.bind(this); + this._chunks[constants.TYPE_PLTE] = this._handlePLTE.bind(this); + this._chunks[constants.TYPE_tRNS] = this._handleTRNS.bind(this); + this._chunks[constants.TYPE_gAMA] = this._handleGAMA.bind(this); + + this.read = dependencies.read; + this.error = dependencies.error; + this.metadata = dependencies.metadata; + this.gamma = dependencies.gamma; + this.transColor = dependencies.transColor; + this.palette = dependencies.palette; + this.parsed = dependencies.parsed; + this.inflateData = dependencies.inflateData; + this.finished = dependencies.finished; + this.simpleTransparency = dependencies.simpleTransparency; + this.headersFinished = dependencies.headersFinished || function() {}; +}; + +Parser.prototype.start = function() { + this.read(constants.PNG_SIGNATURE.length, + this._parseSignature.bind(this) + ); +}; + +Parser.prototype._parseSignature = function(data) { + + var signature = constants.PNG_SIGNATURE; + + for (var i = 0; i < signature.length; i++) { + if (data[i] !== signature[i]) { + this.error(new Error('Invalid file signature')); + return; + } + } + this.read(8, this._parseChunkBegin.bind(this)); +}; + +Parser.prototype._parseChunkBegin = function(data) { + + // chunk content length + var length = data.readUInt32BE(0); + + // chunk type + var type = data.readUInt32BE(4); + var name = ''; + for (var i = 4; i < 8; i++) { + name += String.fromCharCode(data[i]); + } + + //console.log('chunk ', name, length); + + // chunk flags + var ancillary = Boolean(data[4] & 0x20); // or critical + // priv = Boolean(data[5] & 0x20), // or public + // safeToCopy = Boolean(data[7] & 0x20); // or unsafe + + if (!this._hasIHDR && type !== constants.TYPE_IHDR) { + this.error(new Error('Expected IHDR on beggining')); + return; + } + + this._crc = new CrcCalculator(); + this._crc.write(new Buffer(name)); + + if (this._chunks[type]) { + return this._chunks[type](length); + } + + if (!ancillary) { + this.error(new Error('Unsupported critical chunk type ' + name)); + return; + } + + this.read(length + 4, this._skipChunk.bind(this)); +}; + +Parser.prototype._skipChunk = function(/*data*/) { + this.read(8, this._parseChunkBegin.bind(this)); +}; + +Parser.prototype._handleChunkEnd = function() { + this.read(4, this._parseChunkEnd.bind(this)); +}; + +Parser.prototype._parseChunkEnd = function(data) { + + var fileCrc = data.readInt32BE(0); + var calcCrc = this._crc.crc32(); + + // check CRC + if (this._options.checkCRC && calcCrc !== fileCrc) { + this.error(new Error('Crc error - ' + fileCrc + ' - ' + calcCrc)); + return; + } + + if (!this._hasIEND) { + this.read(8, this._parseChunkBegin.bind(this)); + } +}; + +Parser.prototype._handleIHDR = function(length) { + this.read(length, this._parseIHDR.bind(this)); +}; +Parser.prototype._parseIHDR = function(data) { + + this._crc.write(data); + + var width = data.readUInt32BE(0); + var height = data.readUInt32BE(4); + var depth = data[8]; + var colorType = data[9]; // bits: 1 palette, 2 color, 4 alpha + var compr = data[10]; + var filter = data[11]; + var interlace = data[12]; + + // console.log(' width', width, 'height', height, + // 'depth', depth, 'colorType', colorType, + // 'compr', compr, 'filter', filter, 'interlace', interlace + // ); + + if (depth !== 8 && depth !== 4 && depth !== 2 && depth !== 1 && depth !== 16) { + this.error(new Error('Unsupported bit depth ' + depth)); + return; + } + if (!(colorType in constants.COLORTYPE_TO_BPP_MAP)) { + this.error(new Error('Unsupported color type')); + return; + } + if (compr !== 0) { + this.error(new Error('Unsupported compression method')); + return; + } + if (filter !== 0) { + this.error(new Error('Unsupported filter method')); + return; + } + if (interlace !== 0 && interlace !== 1) { + this.error(new Error('Unsupported interlace method')); + return; + } + + this._colorType = colorType; + + var bpp = constants.COLORTYPE_TO_BPP_MAP[this._colorType]; + + this._hasIHDR = true; + + this.metadata({ + width: width, + height: height, + depth: depth, + interlace: Boolean(interlace), + palette: Boolean(colorType & constants.COLORTYPE_PALETTE), + color: Boolean(colorType & constants.COLORTYPE_COLOR), + alpha: Boolean(colorType & constants.COLORTYPE_ALPHA), + bpp: bpp, + colorType: colorType + }); + + this._handleChunkEnd(); +}; + + +Parser.prototype._handlePLTE = function(length) { + this.read(length, this._parsePLTE.bind(this)); +}; +Parser.prototype._parsePLTE = function(data) { + + this._crc.write(data); + + var entries = Math.floor(data.length / 3); + // console.log('Palette:', entries); + + for (var i = 0; i < entries; i++) { + this._palette.push([ + data[i * 3], + data[i * 3 + 1], + data[i * 3 + 2], + 0xff + ]); + } + + this.palette(this._palette); + + this._handleChunkEnd(); +}; + +Parser.prototype._handleTRNS = function(length) { + this.simpleTransparency(); + this.read(length, this._parseTRNS.bind(this)); +}; +Parser.prototype._parseTRNS = function(data) { + + this._crc.write(data); + + // palette + if (this._colorType === constants.COLORTYPE_PALETTE_COLOR) { + if (this._palette.length === 0) { + this.error(new Error('Transparency chunk must be after palette')); + return; + } + if (data.length > this._palette.length) { + this.error(new Error('More transparent colors than palette size')); + return; + } + for (var i = 0; i < data.length; i++) { + this._palette[i][3] = data[i]; + } + this.palette(this._palette); + } + + // for colorType 0 (grayscale) and 2 (rgb) + // there might be one gray/color defined as transparent + if (this._colorType === constants.COLORTYPE_GRAYSCALE) { + // grey, 2 bytes + this.transColor([data.readUInt16BE(0)]); + } + if (this._colorType === constants.COLORTYPE_COLOR) { + this.transColor([data.readUInt16BE(0), data.readUInt16BE(2), data.readUInt16BE(4)]); + } + + this._handleChunkEnd(); +}; + +Parser.prototype._handleGAMA = function(length) { + this.read(length, this._parseGAMA.bind(this)); +}; +Parser.prototype._parseGAMA = function(data) { + + this._crc.write(data); + this.gamma(data.readUInt32BE(0) / constants.GAMMA_DIVISION); + + this._handleChunkEnd(); +}; + +Parser.prototype._handleIDAT = function(length) { + if (!this._emittedHeadersFinished) { + this._emittedHeadersFinished = true; + this.headersFinished(); + } + this.read(-length, this._parseIDAT.bind(this, length)); +}; +Parser.prototype._parseIDAT = function(length, data) { + + this._crc.write(data); + + if (this._colorType === constants.COLORTYPE_PALETTE_COLOR && this._palette.length === 0) { + throw new Error('Expected palette not found'); + } + + this.inflateData(data); + var leftOverLength = length - data.length; + + if (leftOverLength > 0) { + this._handleIDAT(leftOverLength); + } + else { + this._handleChunkEnd(); + } +}; + +Parser.prototype._handleIEND = function(length) { + this.read(length, this._parseIEND.bind(this)); +}; +Parser.prototype._parseIEND = function(data) { + + this._crc.write(data); + + this._hasIEND = true; + this._handleChunkEnd(); + + if (this.finished) { + this.finished(); + } +}; + + +/***/ }), + +/***/ 1436: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + + +var parse = __nccwpck_require__(29); +var pack = __nccwpck_require__(7100); + + +exports.read = function(buffer, options) { + + return parse(buffer, options || {}); +}; + +exports.write = function(png, options) { + + return pack(png, options); +}; + + +/***/ }), + +/***/ 6413: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +var util = __nccwpck_require__(3837); +var Stream = __nccwpck_require__(2781); +var Parser = __nccwpck_require__(699); +var Packer = __nccwpck_require__(2584); +var PNGSync = __nccwpck_require__(1436); + + +var PNG = exports.PNG = function(options) { + Stream.call(this); + + options = options || {}; // eslint-disable-line no-param-reassign + + // coerce pixel dimensions to integers (also coerces undefined -> 0): + this.width = options.width | 0; + this.height = options.height | 0; + + this.data = this.width > 0 && this.height > 0 ? + new Buffer(4 * this.width * this.height) : null; + + if (options.fill && this.data) { + this.data.fill(0); + } + + this.gamma = 0; + this.readable = this.writable = true; + + this._parser = new Parser(options); + + this._parser.on('error', this.emit.bind(this, 'error')); + this._parser.on('close', this._handleClose.bind(this)); + this._parser.on('metadata', this._metadata.bind(this)); + this._parser.on('gamma', this._gamma.bind(this)); + this._parser.on('parsed', function(data) { + this.data = data; + this.emit('parsed', data); + }.bind(this)); + + this._packer = new Packer(options); + this._packer.on('data', this.emit.bind(this, 'data')); + this._packer.on('end', this.emit.bind(this, 'end')); + this._parser.on('close', this._handleClose.bind(this)); + this._packer.on('error', this.emit.bind(this, 'error')); + +}; +util.inherits(PNG, Stream); + +PNG.sync = PNGSync; + +PNG.prototype.pack = function() { + + if (!this.data || !this.data.length) { + this.emit('error', 'No data provided'); + return this; + } + + process.nextTick(function() { + this._packer.pack(this.data, this.width, this.height, this.gamma); + }.bind(this)); + + return this; +}; + + +PNG.prototype.parse = function(data, callback) { + + if (callback) { + var onParsed, onError; + + onParsed = function(parsedData) { + this.removeListener('error', onError); + + this.data = parsedData; + callback(null, this); + }.bind(this); + + onError = function(err) { + this.removeListener('parsed', onParsed); + + callback(err, null); + }.bind(this); + + this.once('parsed', onParsed); + this.once('error', onError); + } + + this.end(data); + return this; +}; + +PNG.prototype.write = function(data) { + this._parser.write(data); + return true; +}; + +PNG.prototype.end = function(data) { + this._parser.end(data); +}; + +PNG.prototype._metadata = function(metadata) { + this.width = metadata.width; + this.height = metadata.height; + + this.emit('metadata', metadata); +}; + +PNG.prototype._gamma = function(gamma) { + this.gamma = gamma; +}; + +PNG.prototype._handleClose = function() { + if (!this._parser.writable && !this._packer.readable) { + this.emit('close'); + } +}; + + +PNG.bitblt = function(src, dst, srcX, srcY, width, height, deltaX, deltaY) { // eslint-disable-line max-params + // coerce pixel dimensions to integers (also coerces undefined -> 0): + /* eslint-disable no-param-reassign */ + srcX |= 0; + srcY |= 0; + width |= 0; + height |= 0; + deltaX |= 0; + deltaY |= 0; + /* eslint-enable no-param-reassign */ + + if (srcX > src.width || srcY > src.height || srcX + width > src.width || srcY + height > src.height) { + throw new Error('bitblt reading outside image'); + } + + if (deltaX > dst.width || deltaY > dst.height || deltaX + width > dst.width || deltaY + height > dst.height) { + throw new Error('bitblt writing outside image'); + } + + for (var y = 0; y < height; y++) { + src.data.copy(dst.data, + ((deltaY + y) * dst.width + deltaX) << 2, + ((srcY + y) * src.width + srcX) << 2, + ((srcY + y) * src.width + srcX + width) << 2 + ); + } +}; + + +PNG.prototype.bitblt = function(dst, srcX, srcY, width, height, deltaX, deltaY) { // eslint-disable-line max-params + + PNG.bitblt(this, dst, srcX, srcY, width, height, deltaX, deltaY); + return this; +}; + +PNG.adjustGamma = function(src) { + if (src.gamma) { + for (var y = 0; y < src.height; y++) { + for (var x = 0; x < src.width; x++) { + var idx = (src.width * y + x) << 2; + + for (var i = 0; i < 3; i++) { + var sample = src.data[idx + i] / 255; + sample = Math.pow(sample, 1 / 2.2 / src.gamma); + src.data[idx + i] = Math.round(sample * 255); + } + } + } + src.gamma = 0; + } +}; + +PNG.prototype.adjustGamma = function() { + PNG.adjustGamma(this); +}; + + +/***/ }), + +/***/ 5331: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +var assert = (__nccwpck_require__(9491).ok); +var zlib = __nccwpck_require__(9796); +var util = __nccwpck_require__(3837); + +var kMaxLength = (__nccwpck_require__(4300).kMaxLength); + +function Inflate(opts) { + if (!(this instanceof Inflate)) { + return new Inflate(opts); + } + + if (opts && opts.chunkSize < zlib.Z_MIN_CHUNK) { + opts.chunkSize = zlib.Z_MIN_CHUNK; + } + + zlib.Inflate.call(this, opts); + + // Node 8 --> 9 compatibility check + this._offset = this._offset === undefined ? this._outOffset : this._offset; + this._buffer = this._buffer || this._outBuffer; + + if (opts && opts.maxLength != null) { + this._maxLength = opts.maxLength; + } +} + +function createInflate(opts) { + return new Inflate(opts); +} + +function _close(engine, callback) { + if (callback) { + process.nextTick(callback); + } + + // Caller may invoke .close after a zlib error (which will null _handle). + if (!engine._handle) { + return; + } + + engine._handle.close(); + engine._handle = null; +} + +Inflate.prototype._processChunk = function(chunk, flushFlag, asyncCb) { + if (typeof asyncCb === 'function') { + return zlib.Inflate._processChunk.call(this, chunk, flushFlag, asyncCb); + } + + var self = this; + + var availInBefore = chunk && chunk.length; + var availOutBefore = this._chunkSize - this._offset; + var leftToInflate = this._maxLength; + var inOff = 0; + + var buffers = []; + var nread = 0; + + var error; + this.on('error', function(err) { + error = err; + }); + + function handleChunk(availInAfter, availOutAfter) { + if (self._hadError) { + return; + } + + var have = availOutBefore - availOutAfter; + assert(have >= 0, 'have should not go down'); + + if (have > 0) { + var out = self._buffer.slice(self._offset, self._offset + have); + self._offset += have; + + if (out.length > leftToInflate) { + out = out.slice(0, leftToInflate); + } + + buffers.push(out); + nread += out.length; + leftToInflate -= out.length; + + if (leftToInflate === 0) { + return false; + } + } + + if (availOutAfter === 0 || self._offset >= self._chunkSize) { + availOutBefore = self._chunkSize; + self._offset = 0; + self._buffer = Buffer.allocUnsafe(self._chunkSize); + } + + if (availOutAfter === 0) { + inOff += (availInBefore - availInAfter); + availInBefore = availInAfter; + + return true; + } + + return false; + } + + assert(this._handle, 'zlib binding closed'); + do { + var res = this._handle.writeSync(flushFlag, + chunk, // in + inOff, // in_off + availInBefore, // in_len + this._buffer, // out + this._offset, //out_off + availOutBefore); // out_len + // Node 8 --> 9 compatibility check + res = res || this._writeState; + } while (!this._hadError && handleChunk(res[0], res[1])); + + if (this._hadError) { + throw error; + } + + if (nread >= kMaxLength) { + _close(this); + throw new RangeError('Cannot create final Buffer. It would be larger than 0x' + kMaxLength.toString(16) + ' bytes'); + } + + var buf = Buffer.concat(buffers, nread); + _close(this); + + return buf; +}; + +util.inherits(Inflate, zlib.Inflate); + +function zlibBufferSync(engine, buffer) { + if (typeof buffer === 'string') { + buffer = Buffer.from(buffer); + } + if (!(buffer instanceof Buffer)) { + throw new TypeError('Not a string or buffer'); + } + + var flushFlag = engine._finishFlushFlag; + if (flushFlag == null) { + flushFlag = zlib.Z_FINISH; + } + + return engine._processChunk(buffer, flushFlag); +} + +function inflateSync(buffer, opts) { + return zlibBufferSync(new Inflate(opts), buffer); +} + +module.exports = exports = inflateSync; +exports.Inflate = Inflate; +exports.createInflate = createInflate; +exports.inflateSync = inflateSync; + + +/***/ }), + +/***/ 3652: +/***/ ((module) => { + +"use strict"; + + +var SyncReader = module.exports = function(buffer) { + + this._buffer = buffer; + this._reads = []; +}; + +SyncReader.prototype.read = function(length, callback) { + + this._reads.push({ + length: Math.abs(length), // if length < 0 then at most this length + allowLess: length < 0, + func: callback + }); +}; + +SyncReader.prototype.process = function() { + + // as long as there is any data and read requests + while (this._reads.length > 0 && this._buffer.length) { + + var read = this._reads[0]; + + if (this._buffer.length && (this._buffer.length >= read.length || read.allowLess)) { + + // ok there is any data so that we can satisfy this request + this._reads.shift(); // == read + + var buf = this._buffer; + + this._buffer = buf.slice(read.length); + + read.func.call(this, buf.slice(0, read.length)); + + } + else { + break; + } + + } + + if (this._reads.length > 0) { + return new Error('There are some read requests waitng on finished stream'); + } + + if (this._buffer.length > 0) { + return new Error('unrecognised content at end of stream'); + } + +}; + + +/***/ }), + +/***/ 2043: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +;(function (sax) { // wrapper for non-node envs + sax.parser = function (strict, opt) { return new SAXParser(strict, opt) } + sax.SAXParser = SAXParser + sax.SAXStream = SAXStream + sax.createStream = createStream + + // When we pass the MAX_BUFFER_LENGTH position, start checking for buffer overruns. + // When we check, schedule the next check for MAX_BUFFER_LENGTH - (max(buffer lengths)), + // since that's the earliest that a buffer overrun could occur. This way, checks are + // as rare as required, but as often as necessary to ensure never crossing this bound. + // Furthermore, buffers are only tested at most once per write(), so passing a very + // large string into write() might have undesirable effects, but this is manageable by + // the caller, so it is assumed to be safe. Thus, a call to write() may, in the extreme + // edge case, result in creating at most one complete copy of the string passed in. + // Set to Infinity to have unlimited buffers. + sax.MAX_BUFFER_LENGTH = 64 * 1024 + + var buffers = [ + 'comment', 'sgmlDecl', 'textNode', 'tagName', 'doctype', + 'procInstName', 'procInstBody', 'entity', 'attribName', + 'attribValue', 'cdata', 'script' + ] + + sax.EVENTS = [ + 'text', + 'processinginstruction', + 'sgmldeclaration', + 'doctype', + 'comment', + 'opentagstart', + 'attribute', + 'opentag', + 'closetag', + 'opencdata', + 'cdata', + 'closecdata', + 'error', + 'end', + 'ready', + 'script', + 'opennamespace', + 'closenamespace' + ] + + function SAXParser (strict, opt) { + if (!(this instanceof SAXParser)) { + return new SAXParser(strict, opt) + } + + var parser = this + clearBuffers(parser) + parser.q = parser.c = '' + parser.bufferCheckPosition = sax.MAX_BUFFER_LENGTH + parser.opt = opt || {} + parser.opt.lowercase = parser.opt.lowercase || parser.opt.lowercasetags + parser.looseCase = parser.opt.lowercase ? 'toLowerCase' : 'toUpperCase' + parser.tags = [] + parser.closed = parser.closedRoot = parser.sawRoot = false + parser.tag = parser.error = null + parser.strict = !!strict + parser.noscript = !!(strict || parser.opt.noscript) + parser.state = S.BEGIN + parser.strictEntities = parser.opt.strictEntities + parser.ENTITIES = parser.strictEntities ? Object.create(sax.XML_ENTITIES) : Object.create(sax.ENTITIES) + parser.attribList = [] + + // namespaces form a prototype chain. + // it always points at the current tag, + // which protos to its parent tag. + if (parser.opt.xmlns) { + parser.ns = Object.create(rootNS) + } + + // mostly just for error reporting + parser.trackPosition = parser.opt.position !== false + if (parser.trackPosition) { + parser.position = parser.line = parser.column = 0 + } + emit(parser, 'onready') + } + + if (!Object.create) { + Object.create = function (o) { + function F () {} + F.prototype = o + var newf = new F() + return newf + } + } + + if (!Object.keys) { + Object.keys = function (o) { + var a = [] + for (var i in o) if (o.hasOwnProperty(i)) a.push(i) + return a + } + } + + function checkBufferLength (parser) { + var maxAllowed = Math.max(sax.MAX_BUFFER_LENGTH, 10) + var maxActual = 0 + for (var i = 0, l = buffers.length; i < l; i++) { + var len = parser[buffers[i]].length + if (len > maxAllowed) { + // Text/cdata nodes can get big, and since they're buffered, + // we can get here under normal conditions. + // Avoid issues by emitting the text node now, + // so at least it won't get any bigger. + switch (buffers[i]) { + case 'textNode': + closeText(parser) + break + + case 'cdata': + emitNode(parser, 'oncdata', parser.cdata) + parser.cdata = '' + break + + case 'script': + emitNode(parser, 'onscript', parser.script) + parser.script = '' + break + + default: + error(parser, 'Max buffer length exceeded: ' + buffers[i]) + } + } + maxActual = Math.max(maxActual, len) + } + // schedule the next check for the earliest possible buffer overrun. + var m = sax.MAX_BUFFER_LENGTH - maxActual + parser.bufferCheckPosition = m + parser.position + } + + function clearBuffers (parser) { + for (var i = 0, l = buffers.length; i < l; i++) { + parser[buffers[i]] = '' + } + } + + function flushBuffers (parser) { + closeText(parser) + if (parser.cdata !== '') { + emitNode(parser, 'oncdata', parser.cdata) + parser.cdata = '' + } + if (parser.script !== '') { + emitNode(parser, 'onscript', parser.script) + parser.script = '' + } + } + + SAXParser.prototype = { + end: function () { end(this) }, + write: write, + resume: function () { this.error = null; return this }, + close: function () { return this.write(null) }, + flush: function () { flushBuffers(this) } + } + + var Stream + try { + Stream = (__nccwpck_require__(2781).Stream) + } catch (ex) { + Stream = function () {} + } + + var streamWraps = sax.EVENTS.filter(function (ev) { + return ev !== 'error' && ev !== 'end' + }) + + function createStream (strict, opt) { + return new SAXStream(strict, opt) + } + + function SAXStream (strict, opt) { + if (!(this instanceof SAXStream)) { + return new SAXStream(strict, opt) + } + + Stream.apply(this) + + this._parser = new SAXParser(strict, opt) + this.writable = true + this.readable = true + + var me = this + + this._parser.onend = function () { + me.emit('end') + } + + this._parser.onerror = function (er) { + me.emit('error', er) + + // if didn't throw, then means error was handled. + // go ahead and clear error, so we can write again. + me._parser.error = null + } + + this._decoder = null + + streamWraps.forEach(function (ev) { + Object.defineProperty(me, 'on' + ev, { + get: function () { + return me._parser['on' + ev] + }, + set: function (h) { + if (!h) { + me.removeAllListeners(ev) + me._parser['on' + ev] = h + return h + } + me.on(ev, h) + }, + enumerable: true, + configurable: false + }) + }) + } + + SAXStream.prototype = Object.create(Stream.prototype, { + constructor: { + value: SAXStream + } + }) + + SAXStream.prototype.write = function (data) { + if (typeof Buffer === 'function' && + typeof Buffer.isBuffer === 'function' && + Buffer.isBuffer(data)) { + if (!this._decoder) { + var SD = (__nccwpck_require__(1576).StringDecoder) + this._decoder = new SD('utf8') + } + data = this._decoder.write(data) + } + + this._parser.write(data.toString()) + this.emit('data', data) + return true + } + + SAXStream.prototype.end = function (chunk) { + if (chunk && chunk.length) { + this.write(chunk) + } + this._parser.end() + return true + } + + SAXStream.prototype.on = function (ev, handler) { + var me = this + if (!me._parser['on' + ev] && streamWraps.indexOf(ev) !== -1) { + me._parser['on' + ev] = function () { + var args = arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments) + args.splice(0, 0, ev) + me.emit.apply(me, args) + } + } + + return Stream.prototype.on.call(me, ev, handler) + } + + // this really needs to be replaced with character classes. + // XML allows all manner of ridiculous numbers and digits. + var CDATA = '[CDATA[' + var DOCTYPE = 'DOCTYPE' + var XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace' + var XMLNS_NAMESPACE = 'http://www.w3.org/2000/xmlns/' + var rootNS = { xml: XML_NAMESPACE, xmlns: XMLNS_NAMESPACE } + + // http://www.w3.org/TR/REC-xml/#NT-NameStartChar + // This implementation works on strings, a single character at a time + // as such, it cannot ever support astral-plane characters (10000-EFFFF) + // without a significant breaking change to either this parser, or the + // JavaScript language. Implementation of an emoji-capable xml parser + // is left as an exercise for the reader. + var nameStart = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/ + + var nameBody = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/ + + var entityStart = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/ + var entityBody = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/ + + function isWhitespace (c) { + return c === ' ' || c === '\n' || c === '\r' || c === '\t' + } + + function isQuote (c) { + return c === '"' || c === '\'' + } + + function isAttribEnd (c) { + return c === '>' || isWhitespace(c) + } + + function isMatch (regex, c) { + return regex.test(c) + } + + function notMatch (regex, c) { + return !isMatch(regex, c) + } + + var S = 0 + sax.STATE = { + BEGIN: S++, // leading byte order mark or whitespace + BEGIN_WHITESPACE: S++, // leading whitespace + TEXT: S++, // general stuff + TEXT_ENTITY: S++, // & and such. + OPEN_WAKA: S++, // < + SGML_DECL: S++, // + SCRIPT: S++, //