From 51708f346fbedf483fe03568633faeef4a379df4 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 3 Jul 2022 05:06:26 +0000 Subject: [PATCH] Release v5.20.0 --- dist/index.js | 52188 ++++++++++++++++++++++++++++++++++- dist/index.js.map | 2 +- dist/licenses.txt | 1638 ++ dist/presets/divx.js | 14 + dist/presets/flashvideo.js | 16 + dist/presets/podcast.js | 16 + 6 files changed, 53553 insertions(+), 321 deletions(-) create mode 100644 dist/presets/divx.js create mode 100644 dist/presets/flashvideo.js create mode 100644 dist/presets/podcast.js diff --git a/dist/index.js b/dist/index.js index 6d715cb..789c496 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 + let 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]; + text = text.replace(/\n/g, '\n//'); + let newContent = `//${text}\n${firstLine}`; + newContent += lines.slice(1).join('\n'); + return await fs_1.default.writeFileSync(path, newContent, 'utf8'); +}; +exports.writeText = writeText; + + +/***/ }), + +/***/ 1732: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -29,20 +56,304 @@ 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.concatYanAudio = void 0; +const core = __importStar(__nccwpck_require__(2186)); +/* eslint-disable @typescript-eslint/no-unsafe-call */ +/* eslint-disable @typescript-eslint/no-unsafe-member-access */ +/* eslint-disable @typescript-eslint/no-unsafe-assignment */ +/* eslint-disable @typescript-eslint/no-var-requires */ +const audioconcat = __nccwpck_require__(9165); +const fs_1 = __importDefault(__nccwpck_require__(7147)); +const child_process_1 = __nccwpck_require__(2081); +const concatYanAudio = (audioSrc, yarnSrc) => { + return new Promise((resolve, reject) => { + //Run ffmpeg command + // exec(`ffmpeg -i "concat:${audioSrc}|${yarnSrc}" -acodec copy ${audioSrc}-yan.mp3`, (err, stdout, stderr) => { + // exec(`ffmpeg -i ${audioSrc} -i ${yarnSrc} -filter_complex "[1]adelay=Ns|Ns[a1];[0:a][a1]amix=inputs=2[a]" -map "[a]" ${audioSrc}-yan.mp3`, (err, stdout, stderr) => { + (0, child_process_1.exec)(`ffmpeg -i ${audioSrc} -i ${yarnSrc} -filter_complex "[0][1]amerge=inputs=2,pan=stereo|FL { + if (err) { + core.error(`Error: ${err}`); + reject(err); + } + else { + core.info(`stdout: ${stdout}`); + //delete old and rename new file + fs_1.default.unlink(audioSrc, (err) => { + if (err) { + core.error(`Error: ${err}`); + reject(err); + } + else { + fs_1.default.rename(`${audioSrc}-yan.mp3`, audioSrc, (err) => { + if (err) { + core.error(`Error: ${err}`); + reject(err); + } + resolve(); + }); + } + }); + } + }); + }); +}; +exports.concatYanAudio = concatYanAudio; + + +/***/ }), + +/***/ 147: +/***/ (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 })); +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 core = __importStar(__nccwpck_require__(2186)); +const fsPromises = fs_1.default.promises; +const defaultAssetURL = { + assci: path_1.default.resolve(__dirname, '..', 'assets', 'ascii.txt'), + image: path_1.default.resolve(__dirname, '..', 'assets', 'image.png'), + audio: path_1.default.resolve(__dirname, '..', 'assets', 'audio.mp3'), +}; +const loadDefaultAsset = async () => { + return new Promise(async (resolve) => { + const base = (process.env.GITHUB_WORKSPACE || path_1.default.resolve(__dirname, '..')) + '/.monk/'; + core.info(`base: ${base}`); + const loc = { + assci: base + 'ascii.txt', + image: base + 'image.png', + audio: base + 'audio.mp3', + }; + //Check if base folder not exist create it + if (!fs_1.default.existsSync(base)) { + await fsPromises.mkdir(base); + } + //Check if assci file not exist download it + if (!fs_1.default.existsSync(loc.assci)) + loc.assci = defaultAssetURL.assci; + //Check if image file not exist download it + if (!fs_1.default.existsSync(loc.image)) + loc.image = defaultAssetURL.image; + //Check if audio file not exist download it + if (!fs_1.default.existsSync(loc.audio)) + loc.audio = defaultAssetURL.audio; + resolve(loc); + }); +}; +exports["default"] = loadDefaultAsset; + + +/***/ }), + +/***/ 2459: +/***/ (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 child_process_1 = __nccwpck_require__(2081); +const core = __importStar(__nccwpck_require__(2186)); +const fs_1 = __importDefault(__nccwpck_require__(7147)); +const mergeVideo = async (filePath, imagePath, audioSrc) => { + return new Promise((resolve, reject) => { + let result = (0, child_process_1.exec)(`ffmpeg -i ${filePath} -i ${imagePath} -filter_complex "overlay=(main_w-overlay_w)/2:(main_h-overlay_h)/2" -codec:a copy ${filePath}-yan.mp4`, (err) => { + if (err) { + reject(err); + } + //delete old and rename new file + fs_1.default.unlink(filePath, (err) => { + if (err) { + reject(err); + } + fs_1.default.rename(`${filePath}-yan.mp4`, filePath, (err) => { + if (err) { + reject(err); + } + (0, child_process_1.exec)(`ffmpeg -i ${filePath} -i ${audioSrc} -filter_complex "[0][1]amerge=inputs=2,pan=stereo|FL { + if (err) { + core.error(`Error: ${err}`); + reject(err); + } + else { + core.info(`stdout: ${stdout}`); + //delete old and rename new file + fs_1.default.unlink(filePath, (err) => { + if (err) { + core.error(`Error: ${err}`); + reject(err); + } + else { + fs_1.default.rename(`${filePath}-yan.mp4`, filePath, (err) => { + if (err) { + core.error(`Error: ${err}`); + reject(err); + } + resolve(); + }); + } + }); + } + }); + }); + }); + }); }); }; +exports["default"] = mergeVideo; + + +/***/ }), + +/***/ 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 +381,85 @@ 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)); +const audio_1 = __nccwpck_require__(1732); +const video_1 = __importDefault(__nccwpck_require__(2459)); // 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 40MB + const stats = await fs_1.promises.stat(i); + if (stats.size > 0 && stats.size < 40 * 1024 * 1024) { + const fileExtension = path_1.default.extname(i); + switch (fileExtension) { + //Video + case '.mp4': + case '.mov': + case '.avi': + case '.flv': + case '.wmv': + case '.m4v': + case '.mpg': + case '.mpeg': + await (0, video_1.default)(i, loc.image, loc.audio); + break; + //Music and audio + case '.mp3': + case '.wav': + case '.ogg': + case '.flac': + case '.aac': + case '.m4a': + case '.wma': + await (0, audio_1.concatYanAudio)(i, loc.audio); + break; + //Image + case '.jpg': + case '.png': + case '.gif': + case '.jpeg': + case '.bmp': + 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 +485,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 +558,7 @@ function escapeProperty(s) { /***/ }), -/***/ 186: +/***/ 2186: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -216,12 +593,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 +876,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 +923,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 +943,7 @@ exports.issueCommand = issueCommand; /***/ }), -/***/ 41: +/***/ 8041: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -582,9 +959,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 +1027,7 @@ exports.OidcClient = OidcClient; /***/ }), -/***/ 981: +/***/ 2981: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -676,7 +1053,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 +1092,7 @@ exports.toPlatformPath = toPlatformPath; /***/ }), -/***/ 327: +/***/ 1327: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -731,8 +1108,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 +1382,7 @@ exports.summary = _summary; /***/ }), -/***/ 278: +/***/ 5278: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -1052,7 +1429,7 @@ exports.toCommandProperties = toCommandProperties; /***/ }), -/***/ 526: +/***/ 5526: /***/ (function(__unused_webpack_module, exports) { "use strict"; @@ -1140,7 +1517,7 @@ exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHand /***/ }), -/***/ 255: +/***/ 6255: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -1176,10 +1553,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 +2129,7 @@ const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCa /***/ }), -/***/ 835: +/***/ 9835: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -1820,363 +2197,51522 @@ exports.checkBypass = checkBypass; /***/ }), -/***/ 294: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 4858: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; -module.exports = __nccwpck_require__(219); +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; + + 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 httpOverHttp(options) { - var agent = new TunnelingAgent(options); - agent.request = http.request; - return agent; +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 httpsOverHttp(options) { - var agent = new TunnelingAgent(options); - agent.request = http.request; - agent.createSocket = createSecureSocket; - agent.defaultPort = 443; - 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 httpOverHttps(options) { - var agent = new TunnelingAgent(options); - agent.request = https.request; - 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 httpsOverHttps(options) { - var agent = new TunnelingAgent(options); - agent.request = https.request; - agent.createSocket = createSecureSocket; - agent.defaultPort = 443; - 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 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 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 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 + }; +} - 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 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 + }; +} + +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 + }; +} +//# sourceMappingURL=composite-modes.js.map + +/***/ }), + +/***/ 5141: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; + + +var _interopRequireWildcard = __nccwpck_require__(4405); + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = composite; + +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 (!(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); + } + + var _options = options, + mode = _options.mode, + opacitySource = _options.opacitySource, + opacityDest = _options.opacityDest; + + if (!mode) { + mode = constants.BLEND_SOURCE_OVER; + } + + if (typeof opacitySource !== 'number' || opacitySource < 0 || opacitySource > 1) { + opacitySource = 1.0; + } + + if (typeof opacityDest !== 'number' || opacityDest < 0 || opacityDest > 1) { + opacityDest = 1.0; + } + + var blendmode = compositeModes[mode]; // round input + + x = Math.round(x); + y = Math.round(y); + var baseImage = this; + + if (opacityDest !== 1.0) { + baseImage.opacity(opacityDest); + } + + 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); + } + + return this; } -util.inherits(TunnelingAgent, events.EventEmitter); -TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) { - var self = this; - var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress)); +module.exports = exports.default; +//# sourceMappingURL=index.js.map - if (self.sockets.length >= this.maxSockets) { - // We are over limit so we'll add it to the queue. - self.requests.push(options); - return; +/***/ }), + +/***/ 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; - // 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); +var _construct2 = _interopRequireDefault(__nccwpck_require__(807)); - function onFree() { - self.emit('free', socket, options); - } +var _slicedToArray2 = _interopRequireDefault(__nccwpck_require__(8209)); - function onCloseOrRemove(err) { - self.removeSocket(socket); - socket.removeListener('free', onFree); - socket.removeListener('close', onCloseOrRemove); - socket.removeListener('agentRemove', onCloseOrRemove); +var _classCallCheck2 = _interopRequireDefault(__nccwpck_require__(6383)); + +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 buffer; +} + +function loadFromURL(options, cb) { + (0, _request["default"])(options, function (err, response, data) { + if (err) { + return cb(err); } - }); -}; -TunnelingAgent.prototype.createSocket = function createSocket(options, cb) { - var self = this; - var placeholder = {}; - self.sockets.push(placeholder); + if ('headers' in response && 'location' in response.headers) { + options.url = response.headers.location; + return loadFromURL(options, cb); + } - var connectOptions = mergeOptions({}, self.proxyOptions, { - method: 'CONNECT', - path: options.host + ':' + options.port, - agent: false, - headers: { - host: options.host + ':' + options.port + 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); }); - if (options.localAddress) { - connectOptions.localAddress = options.localAddress; - } - if (connectOptions.proxyAuth) { - connectOptions.headers = connectOptions.headers || {}; - connectOptions.headers['Proxy-Authorization'] = 'Basic ' + - new Buffer(connectOptions.proxyAuth).toString('base64'); +} + +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); } +} - 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(); +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); +} - function onResponse(res) { - // Very hacky. This is necessary to avoid http-parser leaks. - res.upgrade = true; +function makeRGBABufferFromRGB(buffer) { + if (buffer.length % 3 !== 0) { + throw new Error('Buffer length is incorrect'); } - function onUpgrade(res, socket, head) { - // Hacky. - process.nextTick(function() { - onConnect(res, socket, head); - }); + 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; + } + + j++; } - function onConnect(res, socket, head) { - connectReq.removeAllListeners(); - socket.removeAllListeners(); + return rgbaBuffer; +} - 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; +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 + */ + +/** + * 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 + */ + +/** + * 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 + */ + +/** + * 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 + */ + +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; + + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; } - 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; + + (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]); + } + + function finish() { + for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + + 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'); + } + + (_cb = cb).call.apply(_cb, [jimpInstance].concat(args)); + }, 1); + } + + 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 + + + if (typeof args[2] === 'string') { + _this._background = Jimp.cssColorToHex(args[2]); + cb = args[3]; + } + + 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)); + } + + _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); + } + + finish(null, (0, _assertThisInitialized2["default"])(_this)); + } else if ((0, _typeof2["default"])(args[0]) === 'object' && args[0].url) { + cb = args[1] || noop; + + 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); + } + + _this.parseBitmap(data, args[0].url, finish); + }); + } else if (args[0] instanceof Jimp) { + // clone an existing Jimp + var original = args[0]; + cb = args[1]; + + 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)); + } + + _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]; + + 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; + +/***/ }), + +/***/ 7888: +/***/ (function(__unused_webpack_module, exports) { + +(function (global, factory) { + true ? factory(exports) : + 0; +}(this, (function (exports) { 'use strict'; + + /** + * Creates a continuation function with some arguments already applied. + * + * Useful as a shorthand when combined with other control flow functions. Any + * arguments passed to the returned function are added to the arguments + * originally passed to apply. + * + * @name apply + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {Function} fn - The function you want to eventually apply all + * arguments to. Invokes with (arguments...). + * @param {...*} arguments... - Any number of arguments to automatically apply + * when the continuation is called. + * @returns {Function} the partially-applied function + * @example + * + * // using apply + * async.parallel([ + * async.apply(fs.writeFile, 'testfile1', 'test1'), + * async.apply(fs.writeFile, 'testfile2', 'test2') + * ]); + * + * + * // the same process without using apply + * async.parallel([ + * function(callback) { + * fs.writeFile('testfile1', 'test1', callback); + * }, + * function(callback) { + * fs.writeFile('testfile2', 'test2', callback); + * } + * ]); + * + * // It's possible to pass any number of additional arguments when calling the + * // continuation: + * + * node> var fn = async.apply(sys.puts, 'one'); + * node> fn('two', 'three'); + * one + * two + * three + */ + function apply(fn, ...args) { + return (...callArgs) => fn(...args,...callArgs); + } + + function initialParams (fn) { + return function (...args/*, callback*/) { + var callback = args.pop(); + return fn.call(this, args, callback); + }; + } + + /* istanbul ignore file */ + + var hasQueueMicrotask = typeof queueMicrotask === 'function' && queueMicrotask; + var hasSetImmediate = typeof setImmediate === 'function' && setImmediate; + var hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function'; + + function fallback(fn) { + setTimeout(fn, 0); + } + + function wrap(defer) { + return (fn, ...args) => defer(() => fn(...args)); + } + + var _defer; + + if (hasQueueMicrotask) { + _defer = queueMicrotask; + } else if (hasSetImmediate) { + _defer = setImmediate; + } else if (hasNextTick) { + _defer = process.nextTick; + } else { + _defer = fallback; + } + + var setImmediate$1 = wrap(_defer); + + /** + * Take a sync function and make it async, passing its return value to a + * callback. This is useful for plugging sync functions into a waterfall, + * series, or other async functions. Any arguments passed to the generated + * function will be passed to the wrapped function (except for the final + * callback argument). Errors thrown will be passed to the callback. + * + * If the function passed to `asyncify` returns a Promise, that promises's + * resolved/rejected state will be used to call the callback, rather than simply + * the synchronous return value. + * + * This also means you can asyncify ES2017 `async` functions. + * + * @name asyncify + * @static + * @memberOf module:Utils + * @method + * @alias wrapSync + * @category Util + * @param {Function} func - The synchronous function, or Promise-returning + * function to convert to an {@link AsyncFunction}. + * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be + * invoked with `(args..., callback)`. + * @example + * + * // passing a regular synchronous function + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(JSON.parse), + * function (data, next) { + * // data is the result of parsing the text. + * // If there was a parsing error, it would have been caught. + * } + * ], callback); + * + * // passing a function returning a promise + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(function (contents) { + * return db.model.create(contents); + * }), + * function (model, next) { + * // `model` is the instantiated model object. + * // If there was an error, this function would be skipped. + * } + * ], callback); + * + * // es2017 example, though `asyncify` is not needed if your JS environment + * // supports async functions out of the box + * var q = async.queue(async.asyncify(async function(file) { + * var intermediateStep = await processFile(file); + * return await somePromise(intermediateStep) + * })); + * + * q.push(files); + */ + function asyncify(func) { + if (isAsync(func)) { + return function (...args/*, callback*/) { + const callback = args.pop(); + const promise = func.apply(this, args); + return handlePromise(promise, callback) + } + } + + return initialParams(function (args, callback) { + var result; + try { + result = func.apply(this, args); + } catch (e) { + return callback(e); + } + // if result is Promise object + if (result && typeof result.then === 'function') { + return handlePromise(result, callback) + } else { + callback(null, result); + } + }); + } + + function handlePromise(promise, callback) { + return promise.then(value => { + invokeCallback(callback, null, value); + }, err => { + invokeCallback(callback, err && err.message ? err : new Error(err)); + }); + } + + function invokeCallback(callback, error, value) { + try { + callback(error, value); + } catch (err) { + setImmediate$1(e => { throw e }, err); + } + } + + function isAsync(fn) { + return fn[Symbol.toStringTag] === 'AsyncFunction'; + } + + function isAsyncGenerator(fn) { + return fn[Symbol.toStringTag] === 'AsyncGenerator'; + } + + function isAsyncIterable(obj) { + return typeof obj[Symbol.asyncIterator] === 'function'; + } + + function wrapAsync(asyncFn) { + if (typeof asyncFn !== 'function') throw new Error('expected a function') + return isAsync(asyncFn) ? asyncify(asyncFn) : asyncFn; + } + + // conditionally promisify a function. + // only return a promise if a callback is omitted + function awaitify (asyncFn, arity = asyncFn.length) { + if (!arity) throw new Error('arity is undefined') + function awaitable (...args) { + if (typeof args[arity - 1] === 'function') { + return asyncFn.apply(this, args) + } + + return new Promise((resolve, reject) => { + args[arity - 1] = (err, ...cbArgs) => { + if (err) return reject(err) + resolve(cbArgs.length > 1 ? cbArgs : cbArgs[0]); + }; + asyncFn.apply(this, args); + }) + } + + return awaitable + } + + function applyEach (eachfn) { + return function applyEach(fns, ...callArgs) { + const go = awaitify(function (callback) { + var that = this; + return eachfn(fns, (fn, cb) => { + wrapAsync(fn).apply(that, callArgs.concat(cb)); + }, callback); + }); + return go; + }; + } + + function _asyncMap(eachfn, arr, iteratee, callback) { + arr = arr || []; + var results = []; + var counter = 0; + var _iteratee = wrapAsync(iteratee); + + return eachfn(arr, (value, _, iterCb) => { + var index = counter++; + _iteratee(value, (err, v) => { + results[index] = v; + iterCb(err); + }); + }, err => { + callback(err, results); + }); + } + + function isArrayLike(value) { + return value && + typeof value.length === 'number' && + value.length >= 0 && + value.length % 1 === 0; + } + + // A temporary value used to identify if the loop should be broken. + // See #1064, #1293 + const breakLoop = {}; + + function once(fn) { + function wrapper (...args) { + if (fn === null) return; + var callFn = fn; + fn = null; + callFn.apply(this, args); + } + Object.assign(wrapper, fn); + return wrapper + } + + function getIterator (coll) { + return coll[Symbol.iterator] && coll[Symbol.iterator](); + } + + function createArrayIterator(coll) { + var i = -1; + var len = coll.length; + return function next() { + return ++i < len ? {value: coll[i], key: i} : null; + } + } + + function createES2015Iterator(iterator) { + var i = -1; + return function next() { + var item = iterator.next(); + if (item.done) + return null; + i++; + return {value: item.value, key: i}; + } + } + + function createObjectIterator(obj) { + var okeys = obj ? Object.keys(obj) : []; + var i = -1; + var len = okeys.length; + return function next() { + var key = okeys[++i]; + if (key === '__proto__') { + return next(); + } + return i < len ? {value: obj[key], key} : null; + }; + } + + function createIterator(coll) { + if (isArrayLike(coll)) { + return createArrayIterator(coll); + } + + var iterator = getIterator(coll); + return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll); + } + + function onlyOnce(fn) { + return function (...args) { + if (fn === null) throw new Error("Callback was already called."); + var callFn = fn; + fn = null; + callFn.apply(this, args); + }; + } + + // for async generators + function asyncEachOfLimit(generator, limit, iteratee, callback) { + let done = false; + let canceled = false; + let awaiting = false; + let running = 0; + let idx = 0; + + function replenish() { + //console.log('replenish') + if (running >= limit || awaiting || done) return + //console.log('replenish awaiting') + awaiting = true; + generator.next().then(({value, done: iterDone}) => { + //console.log('got value', value) + if (canceled || done) return + awaiting = false; + if (iterDone) { + done = true; + if (running <= 0) { + //console.log('done nextCb') + callback(null); + } + return; + } + running++; + iteratee(value, idx, iterateeCallback); + idx++; + replenish(); + }).catch(handleError); + } + + function iterateeCallback(err, result) { + //console.log('iterateeCallback') + running -= 1; + if (canceled) return + if (err) return handleError(err) + + if (err === false) { + done = true; + canceled = true; + return + } + + if (result === breakLoop || (done && running <= 0)) { + done = true; + //console.log('done iterCb') + return callback(null); + } + replenish(); + } + + function handleError(err) { + if (canceled) return + awaiting = false; + done = true; + callback(err); + } + + replenish(); + } + + var eachOfLimit = (limit) => { + return (obj, iteratee, callback) => { + callback = once(callback); + if (limit <= 0) { + throw new RangeError('concurrency limit cannot be less than 1') + } + if (!obj) { + return callback(null); + } + if (isAsyncGenerator(obj)) { + return asyncEachOfLimit(obj, limit, iteratee, callback) + } + if (isAsyncIterable(obj)) { + return asyncEachOfLimit(obj[Symbol.asyncIterator](), limit, iteratee, callback) + } + var nextElem = createIterator(obj); + var done = false; + var canceled = false; + var running = 0; + var looping = false; + + function iterateeCallback(err, value) { + if (canceled) return + running -= 1; + if (err) { + done = true; + callback(err); + } + else if (err === false) { + done = true; + canceled = true; + } + else if (value === breakLoop || (done && running <= 0)) { + done = true; + return callback(null); + } + else if (!looping) { + replenish(); + } + } + + function replenish () { + looping = true; + while (running < limit && !done) { + var elem = nextElem(); + if (elem === null) { + done = true; + if (running <= 0) { + callback(null); + } + return; + } + running += 1; + iteratee(elem.value, elem.key, onlyOnce(iterateeCallback)); + } + looping = false; + } + + replenish(); + }; + }; + + /** + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a + * time. + * + * @name eachOfLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. The `key` is the item's key, or index in the case of an + * array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ + function eachOfLimit$1(coll, limit, iteratee, callback) { + return eachOfLimit(limit)(coll, wrapAsync(iteratee), callback); + } + + var eachOfLimit$2 = awaitify(eachOfLimit$1, 4); + + // eachOf implementation optimized for array-likes + function eachOfArrayLike(coll, iteratee, callback) { + callback = once(callback); + var index = 0, + completed = 0, + {length} = coll, + canceled = false; + if (length === 0) { + callback(null); + } + + function iteratorCallback(err, value) { + if (err === false) { + canceled = true; + } + if (canceled === true) return + if (err) { + callback(err); + } else if ((++completed === length) || value === breakLoop) { + callback(null); + } + } + + for (; index < length; index++) { + iteratee(coll[index], index, onlyOnce(iteratorCallback)); + } + } + + // a generic version of eachOf which can handle array, object, and iterator cases. + function eachOfGeneric (coll, iteratee, callback) { + return eachOfLimit$2(coll, Infinity, iteratee, callback); + } + + /** + * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument + * to the iteratee. + * + * @name eachOf + * @static + * @memberOf module:Collections + * @method + * @alias forEachOf + * @category Collection + * @see [async.each]{@link module:Collections.each} + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each + * item in `coll`. + * The `key` is the item's key, or index in the case of an array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // dev.json is a file containing a valid json object config for dev environment + * // dev.json is a file containing a valid json object config for test environment + * // prod.json is a file containing a valid json object config for prod environment + * // invalid.json is a file with a malformed json object + * + * let configs = {}; //global variable + * let validConfigFileMap = {dev: 'dev.json', test: 'test.json', prod: 'prod.json'}; + * let invalidConfigFileMap = {dev: 'dev.json', test: 'test.json', invalid: 'invalid.json'}; + * + * // asynchronous function that reads a json file and parses the contents as json object + * function parseFile(file, key, callback) { + * fs.readFile(file, "utf8", function(err, data) { + * if (err) return calback(err); + * try { + * configs[key] = JSON.parse(data); + * } catch (e) { + * return callback(e); + * } + * callback(); + * }); + * } + * + * // Using callbacks + * async.forEachOf(validConfigFileMap, parseFile, function (err) { + * if (err) { + * console.error(err); + * } else { + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + * } + * }); + * + * //Error handing + * async.forEachOf(invalidConfigFileMap, parseFile, function (err) { + * if (err) { + * console.error(err); + * // JSON parse error exception + * } else { + * console.log(configs); + * } + * }); + * + * // Using Promises + * async.forEachOf(validConfigFileMap, parseFile) + * .then( () => { + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + * }).catch( err => { + * console.error(err); + * }); + * + * //Error handing + * async.forEachOf(invalidConfigFileMap, parseFile) + * .then( () => { + * console.log(configs); + * }).catch( err => { + * console.error(err); + * // JSON parse error exception + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.forEachOf(validConfigFileMap, parseFile); + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + * } + * catch (err) { + * console.log(err); + * } + * } + * + * //Error handing + * async () => { + * try { + * let result = await async.forEachOf(invalidConfigFileMap, parseFile); + * console.log(configs); + * } + * catch (err) { + * console.log(err); + * // JSON parse error exception + * } + * } + * + */ + function eachOf(coll, iteratee, callback) { + var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric; + return eachOfImplementation(coll, wrapAsync(iteratee), callback); + } + + var eachOf$1 = awaitify(eachOf, 3); + + /** + * Produces a new collection of values by mapping each value in `coll` through + * the `iteratee` function. The `iteratee` is called with an item from `coll` + * and a callback for when it has finished processing. Each of these callbacks + * takes 2 arguments: an `error`, and the transformed item from `coll`. If + * `iteratee` passes an error to its callback, the main `callback` (for the + * `map` function) is immediately called with the error. + * + * Note, that since this function applies the `iteratee` to each item in + * parallel, there is no guarantee that the `iteratee` functions will complete + * in order. However, the results array will be in the same order as the + * original `coll`. + * + * If `map` is passed an Object, the results will be an Array. The results + * will roughly be in the order of the original Objects' keys (but this can + * vary across JavaScript engines). + * + * @name map + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an Array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * // file4.txt does not exist + * + * const fileList = ['file1.txt','file2.txt','file3.txt']; + * const withMissingFileList = ['file1.txt','file2.txt','file4.txt']; + * + * // asynchronous function that returns the file size in bytes + * function getFileSizeInBytes(file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, stat.size); + * }); + * } + * + * // Using callbacks + * async.map(fileList, getFileSizeInBytes, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now an array of the file size in bytes for each file, e.g. + * // [ 1000, 2000, 3000] + * } + * }); + * + * // Error Handling + * async.map(withMissingFileList, getFileSizeInBytes, function(err, results) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(results); + * } + * }); + * + * // Using Promises + * async.map(fileList, getFileSizeInBytes) + * .then( results => { + * console.log(results); + * // results is now an array of the file size in bytes for each file, e.g. + * // [ 1000, 2000, 3000] + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.map(withMissingFileList, getFileSizeInBytes) + * .then( results => { + * console.log(results); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.map(fileList, getFileSizeInBytes); + * console.log(results); + * // results is now an array of the file size in bytes for each file, e.g. + * // [ 1000, 2000, 3000] + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let results = await async.map(withMissingFileList, getFileSizeInBytes); + * console.log(results); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ + function map (coll, iteratee, callback) { + return _asyncMap(eachOf$1, coll, iteratee, callback) + } + var map$1 = awaitify(map, 3); + + /** + * Applies the provided arguments to each function in the array, calling + * `callback` after all functions have completed. If you only provide the first + * argument, `fns`, then it will return a function which lets you pass in the + * arguments as if it were a single function call. If more arguments are + * provided, `callback` is required while `args` is still optional. The results + * for each of the applied async functions are passed to the final callback + * as an array. + * + * @name applyEach + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s + * to all call with the same arguments + * @param {...*} [args] - any number of separate arguments to pass to the + * function. + * @param {Function} [callback] - the final argument should be the callback, + * called when all functions have completed processing. + * @returns {AsyncFunction} - Returns a function that takes no args other than + * an optional callback, that is the result of applying the `args` to each + * of the functions. + * @example + * + * const appliedFn = async.applyEach([enableSearch, updateSchema], 'bucket') + * + * appliedFn((err, results) => { + * // results[0] is the results for `enableSearch` + * // results[1] is the results for `updateSchema` + * }); + * + * // partial application example: + * async.each( + * buckets, + * async (bucket) => async.applyEach([enableSearch, updateSchema], bucket)(), + * callback + * ); + */ + var applyEach$1 = applyEach(map$1); + + /** + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time. + * + * @name eachOfSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ + function eachOfSeries(coll, iteratee, callback) { + return eachOfLimit$2(coll, 1, iteratee, callback) + } + var eachOfSeries$1 = awaitify(eachOfSeries, 3); + + /** + * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time. + * + * @name mapSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.map]{@link module:Collections.map} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ + function mapSeries (coll, iteratee, callback) { + return _asyncMap(eachOfSeries$1, coll, iteratee, callback) + } + var mapSeries$1 = awaitify(mapSeries, 3); + + /** + * The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time. + * + * @name applyEachSeries + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.applyEach]{@link module:ControlFlow.applyEach} + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s to all + * call with the same arguments + * @param {...*} [args] - any number of separate arguments to pass to the + * function. + * @param {Function} [callback] - the final argument should be the callback, + * called when all functions have completed processing. + * @returns {AsyncFunction} - A function, that when called, is the result of + * appling the `args` to the list of functions. It takes no args, other than + * a callback. + */ + var applyEachSeries = applyEach(mapSeries$1); + + const PROMISE_SYMBOL = Symbol('promiseCallback'); + + function promiseCallback () { + let resolve, reject; + function callback (err, ...args) { + if (err) return reject(err) + resolve(args.length > 1 ? args : args[0]); + } + + callback[PROMISE_SYMBOL] = new Promise((res, rej) => { + resolve = res, + reject = rej; + }); + + return callback + } + + /** + * Determines the best order for running the {@link AsyncFunction}s in `tasks`, based on + * their requirements. Each function can optionally depend on other functions + * being completed first, and each function is run as soon as its requirements + * are satisfied. + * + * If any of the {@link AsyncFunction}s pass an error to their callback, the `auto` sequence + * will stop. Further tasks will not execute (so any other functions depending + * on it will not run), and the main `callback` is immediately called with the + * error. + * + * {@link AsyncFunction}s also receive an object containing the results of functions which + * have completed so far as the first argument, if they have dependencies. If a + * task function has no dependencies, it will only be passed a callback. + * + * @name auto + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Object} tasks - An object. Each of its properties is either a + * function or an array of requirements, with the {@link AsyncFunction} itself the last item + * in the array. The object's key of a property serves as the name of the task + * defined by that property, i.e. can be used when specifying requirements for + * other tasks. The function receives one or two arguments: + * * a `results` object, containing the results of the previously executed + * functions, only passed if the task has any dependencies, + * * a `callback(err, result)` function, which must be called when finished, + * passing an `error` (which can be `null`) and the result of the function's + * execution. + * @param {number} [concurrency=Infinity] - An optional `integer` for + * determining the maximum number of tasks that can be run in parallel. By + * default, as many as possible. + * @param {Function} [callback] - An optional callback which is called when all + * the tasks have been completed. It receives the `err` argument if any `tasks` + * pass an error to their callback. Results are always returned; however, if an + * error occurs, no further `tasks` will be performed, and the results object + * will only contain partial results. Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + * @example + * + * //Using Callbacks + * async.auto({ + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * // once the file is written let's email a link to it... + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); + * }] + * }, function(err, results) { + * if (err) { + * console.log('err = ', err); + * } + * console.log('results = ', results); + * // results = { + * // get_data: ['data', 'converted to array'] + * // make_folder; 'folder', + * // write_file: 'filename' + * // email_link: { file: 'filename', email: 'user@example.com' } + * // } + * }); + * + * //Using Promises + * async.auto({ + * get_data: function(callback) { + * console.log('in get_data'); + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * console.log('in make_folder'); + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * // once the file is written let's email a link to it... + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); + * }] + * }).then(results => { + * console.log('results = ', results); + * // results = { + * // get_data: ['data', 'converted to array'] + * // make_folder; 'folder', + * // write_file: 'filename' + * // email_link: { file: 'filename', email: 'user@example.com' } + * // } + * }).catch(err => { + * console.log('err = ', err); + * }); + * + * //Using async/await + * async () => { + * try { + * let results = await async.auto({ + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * // once the file is written let's email a link to it... + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); + * }] + * }); + * console.log('results = ', results); + * // results = { + * // get_data: ['data', 'converted to array'] + * // make_folder; 'folder', + * // write_file: 'filename' + * // email_link: { file: 'filename', email: 'user@example.com' } + * // } + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function auto(tasks, concurrency, callback) { + if (typeof concurrency !== 'number') { + // concurrency is optional, shift the args. + callback = concurrency; + concurrency = null; + } + callback = once(callback || promiseCallback()); + var numTasks = Object.keys(tasks).length; + if (!numTasks) { + return callback(null); + } + if (!concurrency) { + concurrency = numTasks; + } + + var results = {}; + var runningTasks = 0; + var canceled = false; + var hasError = false; + + var listeners = Object.create(null); + + var readyTasks = []; + + // for cycle detection: + var readyToCheck = []; // tasks that have been identified as reachable + // without the possibility of returning to an ancestor task + var uncheckedDependencies = {}; + + Object.keys(tasks).forEach(key => { + var task = tasks[key]; + if (!Array.isArray(task)) { + // no dependencies + enqueueTask(key, [task]); + readyToCheck.push(key); + return; + } + + var dependencies = task.slice(0, task.length - 1); + var remainingDependencies = dependencies.length; + if (remainingDependencies === 0) { + enqueueTask(key, task); + readyToCheck.push(key); + return; + } + uncheckedDependencies[key] = remainingDependencies; + + dependencies.forEach(dependencyName => { + if (!tasks[dependencyName]) { + throw new Error('async.auto task `' + key + + '` has a non-existent dependency `' + + dependencyName + '` in ' + + dependencies.join(', ')); + } + addListener(dependencyName, () => { + remainingDependencies--; + if (remainingDependencies === 0) { + enqueueTask(key, task); + } + }); + }); + }); + + checkForDeadlocks(); + processQueue(); + + function enqueueTask(key, task) { + readyTasks.push(() => runTask(key, task)); + } + + function processQueue() { + if (canceled) return + if (readyTasks.length === 0 && runningTasks === 0) { + return callback(null, results); + } + while(readyTasks.length && runningTasks < concurrency) { + var run = readyTasks.shift(); + run(); + } + + } + + function addListener(taskName, fn) { + var taskListeners = listeners[taskName]; + if (!taskListeners) { + taskListeners = listeners[taskName] = []; + } + + taskListeners.push(fn); + } + + function taskComplete(taskName) { + var taskListeners = listeners[taskName] || []; + taskListeners.forEach(fn => fn()); + processQueue(); + } + + + function runTask(key, task) { + if (hasError) return; + + var taskCallback = onlyOnce((err, ...result) => { + runningTasks--; + if (err === false) { + canceled = true; + return + } + if (result.length < 2) { + [result] = result; + } + if (err) { + var safeResults = {}; + Object.keys(results).forEach(rkey => { + safeResults[rkey] = results[rkey]; + }); + safeResults[key] = result; + hasError = true; + listeners = Object.create(null); + if (canceled) return + callback(err, safeResults); + } else { + results[key] = result; + taskComplete(key); + } + }); + + runningTasks++; + var taskFn = wrapAsync(task[task.length - 1]); + if (task.length > 1) { + taskFn(results, taskCallback); + } else { + taskFn(taskCallback); + } + } + + function checkForDeadlocks() { + // Kahn's algorithm + // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm + // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html + var currentTask; + var counter = 0; + while (readyToCheck.length) { + currentTask = readyToCheck.pop(); + counter++; + getDependents(currentTask).forEach(dependent => { + if (--uncheckedDependencies[dependent] === 0) { + readyToCheck.push(dependent); + } + }); + } + + if (counter !== numTasks) { + throw new Error( + 'async.auto cannot execute tasks due to a recursive dependency' + ); + } + } + + function getDependents(taskName) { + var result = []; + Object.keys(tasks).forEach(key => { + const task = tasks[key]; + if (Array.isArray(task) && task.indexOf(taskName) >= 0) { + result.push(key); + } + }); + return result; + } + + return callback[PROMISE_SYMBOL] + } + + var FN_ARGS = /^(?:async\s+)?(?:function)?\s*\w*\s*\(\s*([^)]+)\s*\)(?:\s*{)/; + var ARROW_FN_ARGS = /^(?:async\s+)?\(?\s*([^)=]+)\s*\)?(?:\s*=>)/; + var FN_ARG_SPLIT = /,/; + var FN_ARG = /(=.+)?(\s*)$/; + + function stripComments(string) { + let stripped = ''; + let index = 0; + let endBlockComment = string.indexOf('*/'); + while (index < string.length) { + if (string[index] === '/' && string[index+1] === '/') { + // inline comment + let endIndex = string.indexOf('\n', index); + index = (endIndex === -1) ? string.length : endIndex; + } else if ((endBlockComment !== -1) && (string[index] === '/') && (string[index+1] === '*')) { + // block comment + let endIndex = string.indexOf('*/', index); + if (endIndex !== -1) { + index = endIndex + 2; + endBlockComment = string.indexOf('*/', index); + } else { + stripped += string[index]; + index++; + } + } else { + stripped += string[index]; + index++; + } + } + return stripped; + } + + function parseParams(func) { + const src = stripComments(func.toString()); + let match = src.match(FN_ARGS); + if (!match) { + match = src.match(ARROW_FN_ARGS); + } + if (!match) throw new Error('could not parse args in autoInject\nSource:\n' + src) + let [, args] = match; + return args + .replace(/\s/g, '') + .split(FN_ARG_SPLIT) + .map((arg) => arg.replace(FN_ARG, '').trim()); + } + + /** + * A dependency-injected version of the [async.auto]{@link module:ControlFlow.auto} function. Dependent + * tasks are specified as parameters to the function, after the usual callback + * parameter, with the parameter names matching the names of the tasks it + * depends on. This can provide even more readable task graphs which can be + * easier to maintain. + * + * If a final callback is specified, the task results are similarly injected, + * specified as named parameters after the initial error parameter. + * + * The autoInject function is purely syntactic sugar and its semantics are + * otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}. + * + * @name autoInject + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.auto]{@link module:ControlFlow.auto} + * @category Control Flow + * @param {Object} tasks - An object, each of whose properties is an {@link AsyncFunction} of + * the form 'func([dependencies...], callback). The object's key of a property + * serves as the name of the task defined by that property, i.e. can be used + * when specifying requirements for other tasks. + * * The `callback` parameter is a `callback(err, result)` which must be called + * when finished, passing an `error` (which can be `null`) and the result of + * the function's execution. The remaining parameters name other tasks on + * which the task is dependent, and the results from those tasks are the + * arguments of those parameters. + * @param {Function} [callback] - An optional callback which is called when all + * the tasks have been completed. It receives the `err` argument if any `tasks` + * pass an error to their callback, and a `results` object with any completed + * task results, similar to `auto`. + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // The example from `auto` can be rewritten as follows: + * async.autoInject({ + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: function(get_data, make_folder, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }, + * email_link: function(write_file, callback) { + * // once the file is written let's email a link to it... + * // write_file contains the filename returned by write_file. + * callback(null, {'file':write_file, 'email':'user@example.com'}); + * } + * }, function(err, results) { + * console.log('err = ', err); + * console.log('email_link = ', results.email_link); + * }); + * + * // If you are using a JS minifier that mangles parameter names, `autoInject` + * // will not work with plain functions, since the parameter names will be + * // collapsed to a single letter identifier. To work around this, you can + * // explicitly specify the names of the parameters your task function needs + * // in an array, similar to Angular.js dependency injection. + * + * // This still has an advantage over plain `auto`, since the results a task + * // depends on are still spread into arguments. + * async.autoInject({ + * //... + * write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) { + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(write_file, callback) { + * callback(null, {'file':write_file, 'email':'user@example.com'}); + * }] + * //... + * }, function(err, results) { + * console.log('err = ', err); + * console.log('email_link = ', results.email_link); + * }); + */ + function autoInject(tasks, callback) { + var newTasks = {}; + + Object.keys(tasks).forEach(key => { + var taskFn = tasks[key]; + var params; + var fnIsAsync = isAsync(taskFn); + var hasNoDeps = + (!fnIsAsync && taskFn.length === 1) || + (fnIsAsync && taskFn.length === 0); + + if (Array.isArray(taskFn)) { + params = [...taskFn]; + taskFn = params.pop(); + + newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn); + } else if (hasNoDeps) { + // no dependencies, use the function as-is + newTasks[key] = taskFn; + } else { + params = parseParams(taskFn); + if ((taskFn.length === 0 && !fnIsAsync) && params.length === 0) { + throw new Error("autoInject task functions require explicit parameters."); + } + + // remove callback param + if (!fnIsAsync) params.pop(); + + newTasks[key] = params.concat(newTask); + } + + function newTask(results, taskCb) { + var newArgs = params.map(name => results[name]); + newArgs.push(taskCb); + wrapAsync(taskFn)(...newArgs); + } + }); + + return auto(newTasks, callback); + } + + // Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation + // used for queues. This implementation assumes that the node provided by the user can be modified + // to adjust the next and last properties. We implement only the minimal functionality + // for queue support. + class DLL { + constructor() { + this.head = this.tail = null; + this.length = 0; + } + + removeLink(node) { + if (node.prev) node.prev.next = node.next; + else this.head = node.next; + if (node.next) node.next.prev = node.prev; + else this.tail = node.prev; + + node.prev = node.next = null; + this.length -= 1; + return node; + } + + empty () { + while(this.head) this.shift(); + return this; + } + + insertAfter(node, newNode) { + newNode.prev = node; + newNode.next = node.next; + if (node.next) node.next.prev = newNode; + else this.tail = newNode; + node.next = newNode; + this.length += 1; + } + + insertBefore(node, newNode) { + newNode.prev = node.prev; + newNode.next = node; + if (node.prev) node.prev.next = newNode; + else this.head = newNode; + node.prev = newNode; + this.length += 1; + } + + unshift(node) { + if (this.head) this.insertBefore(this.head, node); + else setInitial(this, node); + } + + push(node) { + if (this.tail) this.insertAfter(this.tail, node); + else setInitial(this, node); + } + + shift() { + return this.head && this.removeLink(this.head); + } + + pop() { + return this.tail && this.removeLink(this.tail); + } + + toArray() { + return [...this] + } + + *[Symbol.iterator] () { + var cur = this.head; + while (cur) { + yield cur.data; + cur = cur.next; + } + } + + remove (testFn) { + var curr = this.head; + while(curr) { + var {next} = curr; + if (testFn(curr)) { + this.removeLink(curr); + } + curr = next; + } + return this; + } + } + + function setInitial(dll, node) { + dll.length = 1; + dll.head = dll.tail = node; + } + + function queue(worker, concurrency, payload) { + if (concurrency == null) { + concurrency = 1; + } + else if(concurrency === 0) { + throw new RangeError('Concurrency must not be zero'); + } + + var _worker = wrapAsync(worker); + var numRunning = 0; + var workersList = []; + const events = { + error: [], + drain: [], + saturated: [], + unsaturated: [], + empty: [] + }; + + function on (event, handler) { + events[event].push(handler); + } + + function once (event, handler) { + const handleAndRemove = (...args) => { + off(event, handleAndRemove); + handler(...args); + }; + events[event].push(handleAndRemove); + } + + function off (event, handler) { + if (!event) return Object.keys(events).forEach(ev => events[ev] = []) + if (!handler) return events[event] = [] + events[event] = events[event].filter(ev => ev !== handler); + } + + function trigger (event, ...args) { + events[event].forEach(handler => handler(...args)); + } + + var processingScheduled = false; + function _insert(data, insertAtFront, rejectOnError, callback) { + if (callback != null && typeof callback !== 'function') { + throw new Error('task callback must be a function'); + } + q.started = true; + + var res, rej; + function promiseCallback (err, ...args) { + // we don't care about the error, let the global error handler + // deal with it + if (err) return rejectOnError ? rej(err) : res() + if (args.length <= 1) return res(args[0]) + res(args); + } + + var item = q._createTaskItem( + data, + rejectOnError ? promiseCallback : + (callback || promiseCallback) + ); + + if (insertAtFront) { + q._tasks.unshift(item); + } else { + q._tasks.push(item); + } + + if (!processingScheduled) { + processingScheduled = true; + setImmediate$1(() => { + processingScheduled = false; + q.process(); + }); + } + + if (rejectOnError || !callback) { + return new Promise((resolve, reject) => { + res = resolve; + rej = reject; + }) + } + } + + function _createCB(tasks) { + return function (err, ...args) { + numRunning -= 1; + + for (var i = 0, l = tasks.length; i < l; i++) { + var task = tasks[i]; + + var index = workersList.indexOf(task); + if (index === 0) { + workersList.shift(); + } else if (index > 0) { + workersList.splice(index, 1); + } + + task.callback(err, ...args); + + if (err != null) { + trigger('error', err, task.data); + } + } + + if (numRunning <= (q.concurrency - q.buffer) ) { + trigger('unsaturated'); + } + + if (q.idle()) { + trigger('drain'); + } + q.process(); + }; + } + + function _maybeDrain(data) { + if (data.length === 0 && q.idle()) { + // call drain immediately if there are no tasks + setImmediate$1(() => trigger('drain')); + return true + } + return false + } + + const eventMethod = (name) => (handler) => { + if (!handler) { + return new Promise((resolve, reject) => { + once(name, (err, data) => { + if (err) return reject(err) + resolve(data); + }); + }) + } + off(name); + on(name, handler); + + }; + + var isProcessing = false; + var q = { + _tasks: new DLL(), + _createTaskItem (data, callback) { + return { + data, + callback + }; + }, + *[Symbol.iterator] () { + yield* q._tasks[Symbol.iterator](); + }, + concurrency, + payload, + buffer: concurrency / 4, + started: false, + paused: false, + push (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, false, false, callback)) + } + return _insert(data, false, false, callback); + }, + pushAsync (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, false, true, callback)) + } + return _insert(data, false, true, callback); + }, + kill () { + off(); + q._tasks.empty(); + }, + unshift (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, true, false, callback)) + } + return _insert(data, true, false, callback); + }, + unshiftAsync (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, true, true, callback)) + } + return _insert(data, true, true, callback); + }, + remove (testFn) { + q._tasks.remove(testFn); + }, + process () { + // Avoid trying to start too many processing operations. This can occur + // when callbacks resolve synchronously (#1267). + if (isProcessing) { + return; + } + isProcessing = true; + while(!q.paused && numRunning < q.concurrency && q._tasks.length){ + var tasks = [], data = []; + var l = q._tasks.length; + if (q.payload) l = Math.min(l, q.payload); + for (var i = 0; i < l; i++) { + var node = q._tasks.shift(); + tasks.push(node); + workersList.push(node); + data.push(node.data); + } + + numRunning += 1; + + if (q._tasks.length === 0) { + trigger('empty'); + } + + if (numRunning === q.concurrency) { + trigger('saturated'); + } + + var cb = onlyOnce(_createCB(tasks)); + _worker(data, cb); + } + isProcessing = false; + }, + length () { + return q._tasks.length; + }, + running () { + return numRunning; + }, + workersList () { + return workersList; + }, + idle() { + return q._tasks.length + numRunning === 0; + }, + pause () { + q.paused = true; + }, + resume () { + if (q.paused === false) { return; } + q.paused = false; + setImmediate$1(q.process); + } + }; + // define these as fixed properties, so people get useful errors when updating + Object.defineProperties(q, { + saturated: { + writable: false, + value: eventMethod('saturated') + }, + unsaturated: { + writable: false, + value: eventMethod('unsaturated') + }, + empty: { + writable: false, + value: eventMethod('empty') + }, + drain: { + writable: false, + value: eventMethod('drain') + }, + error: { + writable: false, + value: eventMethod('error') + }, + }); + return q; + } + + /** + * Creates a `cargo` object with the specified payload. Tasks added to the + * cargo will be processed altogether (up to the `payload` limit). If the + * `worker` is in progress, the task is queued until it becomes available. Once + * the `worker` has completed some tasks, each callback of those tasks is + * called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966) + * for how `cargo` and `queue` work. + * + * While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers + * at a time, cargo passes an array of tasks to a single worker, repeating + * when the worker is finished. + * + * @name cargo + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.queue]{@link module:ControlFlow.queue} + * @category Control Flow + * @param {AsyncFunction} worker - An asynchronous function for processing an array + * of queued tasks. Invoked with `(tasks, callback)`. + * @param {number} [payload=Infinity] - An optional `integer` for determining + * how many tasks should be processed per round; if omitted, the default is + * unlimited. + * @returns {module:ControlFlow.QueueObject} A cargo object to manage the tasks. Callbacks can + * attached as certain properties to listen for specific events during the + * lifecycle of the cargo and inner queue. + * @example + * + * // create a cargo object with payload 2 + * var cargo = async.cargo(function(tasks, callback) { + * for (var i=0; i { + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.reduce(withMissingFileList, 0, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.reduce(fileList, 0, getFileSizeInBytes); + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let result = await async.reduce(withMissingFileList, 0, getFileSizeInBytes); + * console.log(result); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ + function reduce(coll, memo, iteratee, callback) { + callback = once(callback); + var _iteratee = wrapAsync(iteratee); + return eachOfSeries$1(coll, (x, i, iterCb) => { + _iteratee(memo, x, (err, v) => { + memo = v; + iterCb(err); + }); + }, err => callback(err, memo)); + } + var reduce$1 = awaitify(reduce, 4); + + /** + * Version of the compose function that is more natural to read. Each function + * consumes the return value of the previous function. It is the equivalent of + * [compose]{@link module:ControlFlow.compose} with the arguments reversed. + * + * Each function is executed with the `this` binding of the composed function. + * + * @name seq + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.compose]{@link module:ControlFlow.compose} + * @category Control Flow + * @param {...AsyncFunction} functions - the asynchronous functions to compose + * @returns {Function} a function that composes the `functions` in order + * @example + * + * // Requires lodash (or underscore), express3 and dresende's orm2. + * // Part of an app, that fetches cats of the logged user. + * // This example uses `seq` function to avoid overnesting and error + * // handling clutter. + * app.get('/cats', function(request, response) { + * var User = request.models.User; + * async.seq( + * User.get.bind(User), // 'User.get' has signature (id, callback(err, data)) + * function(user, fn) { + * user.getCats(fn); // 'getCats' has signature (callback(err, data)) + * } + * )(req.session.user_id, function (err, cats) { + * if (err) { + * console.error(err); + * response.json({ status: 'error', message: err.message }); + * } else { + * response.json({ status: 'ok', message: 'Cats found', data: cats }); + * } + * }); + * }); + */ + function seq(...functions) { + var _functions = functions.map(wrapAsync); + return function (...args) { + var that = this; + + var cb = args[args.length - 1]; + if (typeof cb == 'function') { + args.pop(); + } else { + cb = promiseCallback(); + } + + reduce$1(_functions, args, (newargs, fn, iterCb) => { + fn.apply(that, newargs.concat((err, ...nextargs) => { + iterCb(err, nextargs); + })); + }, + (err, results) => cb(err, ...results)); + + return cb[PROMISE_SYMBOL] + }; + } + + /** + * Creates a function which is a composition of the passed asynchronous + * functions. Each function consumes the return value of the function that + * follows. Composing functions `f()`, `g()`, and `h()` would produce the result + * of `f(g(h()))`, only this version uses callbacks to obtain the return values. + * + * If the last argument to the composed function is not a function, a promise + * is returned when you call it. + * + * Each function is executed with the `this` binding of the composed function. + * + * @name compose + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {...AsyncFunction} functions - the asynchronous functions to compose + * @returns {Function} an asynchronous function that is the composed + * asynchronous `functions` + * @example + * + * function add1(n, callback) { + * setTimeout(function () { + * callback(null, n + 1); + * }, 10); + * } + * + * function mul3(n, callback) { + * setTimeout(function () { + * callback(null, n * 3); + * }, 10); + * } + * + * var add1mul3 = async.compose(mul3, add1); + * add1mul3(4, function (err, result) { + * // result now equals 15 + * }); + */ + function compose(...args) { + return seq(...args.reverse()); + } + + /** + * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time. + * + * @name mapLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.map]{@link module:Collections.map} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ + function mapLimit (coll, limit, iteratee, callback) { + return _asyncMap(eachOfLimit(limit), coll, iteratee, callback) + } + var mapLimit$1 = awaitify(mapLimit, 4); + + /** + * The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time. + * + * @name concatLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.concat]{@link module:Collections.concat} + * @category Collection + * @alias flatMapLimit + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, + * which should use an array as its result. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + */ + function concatLimit(coll, limit, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return mapLimit$1(coll, limit, (val, iterCb) => { + _iteratee(val, (err, ...args) => { + if (err) return iterCb(err); + return iterCb(err, args); + }); + }, (err, mapResults) => { + var result = []; + for (var i = 0; i < mapResults.length; i++) { + if (mapResults[i]) { + result = result.concat(...mapResults[i]); + } + } + + return callback(err, result); + }); + } + var concatLimit$1 = awaitify(concatLimit, 4); + + /** + * Applies `iteratee` to each item in `coll`, concatenating the results. Returns + * the concatenated list. The `iteratee`s are called in parallel, and the + * results are concatenated as they return. The results array will be returned in + * the original order of `coll` passed to the `iteratee` function. + * + * @name concat + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @alias flatMap + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, + * which should use an array as its result. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * let directoryList = ['dir1','dir2','dir3']; + * let withMissingDirectoryList = ['dir1','dir2','dir3', 'dir4']; + * + * // Using callbacks + * async.concat(directoryList, fs.readdir, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] + * } + * }); + * + * // Error Handling + * async.concat(withMissingDirectoryList, fs.readdir, function(err, results) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4 does not exist + * } else { + * console.log(results); + * } + * }); + * + * // Using Promises + * async.concat(directoryList, fs.readdir) + * .then(results => { + * console.log(results); + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] + * }).catch(err => { + * console.log(err); + * }); + * + * // Error Handling + * async.concat(withMissingDirectoryList, fs.readdir) + * .then(results => { + * console.log(results); + * }).catch(err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4 does not exist + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.concat(directoryList, fs.readdir); + * console.log(results); + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] + * } catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let results = await async.concat(withMissingDirectoryList, fs.readdir); + * console.log(results); + * } catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4 does not exist + * } + * } + * + */ + function concat(coll, iteratee, callback) { + return concatLimit$1(coll, Infinity, iteratee, callback) + } + var concat$1 = awaitify(concat, 3); + + /** + * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time. + * + * @name concatSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.concat]{@link module:Collections.concat} + * @category Collection + * @alias flatMapSeries + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`. + * The iteratee should complete with an array an array of results. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + */ + function concatSeries(coll, iteratee, callback) { + return concatLimit$1(coll, 1, iteratee, callback) + } + var concatSeries$1 = awaitify(concatSeries, 3); + + /** + * Returns a function that when called, calls-back with the values provided. + * Useful as the first function in a [`waterfall`]{@link module:ControlFlow.waterfall}, or for plugging values in to + * [`auto`]{@link module:ControlFlow.auto}. + * + * @name constant + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {...*} arguments... - Any number of arguments to automatically invoke + * callback with. + * @returns {AsyncFunction} Returns a function that when invoked, automatically + * invokes the callback with the previous given arguments. + * @example + * + * async.waterfall([ + * async.constant(42), + * function (value, next) { + * // value === 42 + * }, + * //... + * ], callback); + * + * async.waterfall([ + * async.constant(filename, "utf8"), + * fs.readFile, + * function (fileData, next) { + * //... + * } + * //... + * ], callback); + * + * async.auto({ + * hostname: async.constant("https://server.net/"), + * port: findFreePort, + * launchServer: ["hostname", "port", function (options, cb) { + * startServer(options, cb); + * }], + * //... + * }, callback); + */ + function constant(...args) { + return function (...ignoredArgs/*, callback*/) { + var callback = ignoredArgs.pop(); + return callback(null, ...args); + }; + } + + function _createTester(check, getResult) { + return (eachfn, arr, _iteratee, cb) => { + var testPassed = false; + var testResult; + const iteratee = wrapAsync(_iteratee); + eachfn(arr, (value, _, callback) => { + iteratee(value, (err, result) => { + if (err || err === false) return callback(err); + + if (check(result) && !testResult) { + testPassed = true; + testResult = getResult(true, value); + return callback(null, breakLoop); + } + callback(); + }); + }, err => { + if (err) return cb(err); + cb(null, testPassed ? testResult : getResult(false)); + }); + }; + } + + /** + * Returns the first value in `coll` that passes an async truth test. The + * `iteratee` is applied in parallel, meaning the first iteratee to return + * `true` will fire the detect `callback` with that result. That means the + * result might not be the first item in the original `coll` (in terms of order) + * that passes the test. + + * If order within the original `coll` is important, then look at + * [`detectSeries`]{@link module:Collections.detectSeries}. + * + * @name detect + * @static + * @memberOf module:Collections + * @method + * @alias find + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // dir1/file1.txt + * // result now equals the first file in the list that exists + * } + *); + * + * // Using Promises + * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists) + * .then(result => { + * console.log(result); + * // dir1/file1.txt + * // result now equals the first file in the list that exists + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists); + * console.log(result); + * // dir1/file1.txt + * // result now equals the file in the list that exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function detect(coll, iteratee, callback) { + return _createTester(bool => bool, (res, item) => item)(eachOf$1, coll, iteratee, callback) + } + var detect$1 = awaitify(detect, 3); + + /** + * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a + * time. + * + * @name detectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findLimit + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns {Promise} a promise, if a callback is omitted + */ + function detectLimit(coll, limit, iteratee, callback) { + return _createTester(bool => bool, (res, item) => item)(eachOfLimit(limit), coll, iteratee, callback) + } + var detectLimit$1 = awaitify(detectLimit, 4); + + /** + * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time. + * + * @name detectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findSeries + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns {Promise} a promise, if a callback is omitted + */ + function detectSeries(coll, iteratee, callback) { + return _createTester(bool => bool, (res, item) => item)(eachOfLimit(1), coll, iteratee, callback) + } + + var detectSeries$1 = awaitify(detectSeries, 3); + + function consoleFunc(name) { + return (fn, ...args) => wrapAsync(fn)(...args, (err, ...resultArgs) => { + /* istanbul ignore else */ + if (typeof console === 'object') { + /* istanbul ignore else */ + if (err) { + /* istanbul ignore else */ + if (console.error) { + console.error(err); + } + } else if (console[name]) { /* istanbul ignore else */ + resultArgs.forEach(x => console[name](x)); + } + } + }) + } + + /** + * Logs the result of an [`async` function]{@link AsyncFunction} to the + * `console` using `console.dir` to display the properties of the resulting object. + * Only works in Node.js or in browsers that support `console.dir` and + * `console.error` (such as FF and Chrome). + * If multiple arguments are returned from the async function, + * `console.dir` is called on each argument in order. + * + * @name dir + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} function - The function you want to eventually apply + * all arguments to. + * @param {...*} arguments... - Any number of arguments to apply to the function. + * @example + * + * // in a module + * var hello = function(name, callback) { + * setTimeout(function() { + * callback(null, {hello: name}); + * }, 1000); + * }; + * + * // in the node repl + * node> async.dir(hello, 'world'); + * {hello: 'world'} + */ + var dir = consoleFunc('dir'); + + /** + * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in + * the order of operations, the arguments `test` and `iteratee` are switched. + * + * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. + * + * @name doWhilst + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {AsyncFunction} iteratee - A function which is called each time `test` + * passes. Invoked with (callback). + * @param {AsyncFunction} test - asynchronous truth test to perform after each + * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the + * non-error args from the previous callback of `iteratee`. + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. + * `callback` will be passed an error and any arguments passed to the final + * `iteratee`'s callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + */ + function doWhilst(iteratee, test, callback) { + callback = onlyOnce(callback); + var _fn = wrapAsync(iteratee); + var _test = wrapAsync(test); + var results; + + function next(err, ...args) { + if (err) return callback(err); + if (err === false) return; + results = args; + _test(...args, check); + } + + function check(err, truth) { + if (err) return callback(err); + if (err === false) return; + if (!truth) return callback(null, ...results); + _fn(next); + } + + return check(null, true); + } + + var doWhilst$1 = awaitify(doWhilst, 3); + + /** + * Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the + * argument ordering differs from `until`. + * + * @name doUntil + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.doWhilst]{@link module:ControlFlow.doWhilst} + * @category Control Flow + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` fails. Invoked with (callback). + * @param {AsyncFunction} test - asynchronous truth test to perform after each + * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the + * non-error args from the previous callback of `iteratee` + * @param {Function} [callback] - A callback which is called after the test + * function has passed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + */ + function doUntil(iteratee, test, callback) { + const _test = wrapAsync(test); + return doWhilst$1(iteratee, (...args) => { + const cb = args.pop(); + _test(...args, (err, truth) => cb (err, !truth)); + }, callback); + } + + function _withoutIndex(iteratee) { + return (value, index, callback) => iteratee(value, callback); + } + + /** + * Applies the function `iteratee` to each item in `coll`, in parallel. + * The `iteratee` is called with an item from the list, and a callback for when + * it has finished. If the `iteratee` passes an error to its `callback`, the + * main `callback` (for the `each` function) is immediately called with the + * error. + * + * Note, that since this function applies `iteratee` to each item in parallel, + * there is no guarantee that the iteratee functions will complete in order. + * + * @name each + * @static + * @memberOf module:Collections + * @method + * @alias forEach + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to + * each item in `coll`. Invoked with (item, callback). + * The array index is not passed to the iteratee. + * If you need the index, use `eachOf`. + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * const fileList = [ 'dir1/file2.txt', 'dir2/file3.txt', 'dir/file5.txt']; + * const withMissingFileList = ['dir1/file1.txt', 'dir4/file2.txt']; + * + * // asynchronous function that deletes a file + * const deleteFile = function(file, callback) { + * fs.unlink(file, callback); + * }; + * + * // Using callbacks + * async.each(fileList, deleteFile, function(err) { + * if( err ) { + * console.log(err); + * } else { + * console.log('All files have been deleted successfully'); + * } + * }); + * + * // Error Handling + * async.each(withMissingFileList, deleteFile, function(err){ + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * }); + * + * // Using Promises + * async.each(fileList, deleteFile) + * .then( () => { + * console.log('All files have been deleted successfully'); + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.each(fileList, deleteFile) + * .then( () => { + * console.log('All files have been deleted successfully'); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * }); + * + * // Using async/await + * async () => { + * try { + * await async.each(files, deleteFile); + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * await async.each(withMissingFileList, deleteFile); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * } + * } + * + */ + function eachLimit(coll, iteratee, callback) { + return eachOf$1(coll, _withoutIndex(wrapAsync(iteratee)), callback); + } + + var each = awaitify(eachLimit, 3); + + /** + * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time. + * + * @name eachLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfLimit`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ + function eachLimit$1(coll, limit, iteratee, callback) { + return eachOfLimit(limit)(coll, _withoutIndex(wrapAsync(iteratee)), callback); + } + var eachLimit$2 = awaitify(eachLimit$1, 4); + + /** + * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time. + * + * Note, that unlike [`each`]{@link module:Collections.each}, this function applies iteratee to each item + * in series and therefore the iteratee functions will complete in order. + + * @name eachSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfSeries`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ + function eachSeries(coll, iteratee, callback) { + return eachLimit$2(coll, 1, iteratee, callback) + } + var eachSeries$1 = awaitify(eachSeries, 3); + + /** + * Wrap an async function and ensure it calls its callback on a later tick of + * the event loop. If the function already calls its callback on a next tick, + * no extra deferral is added. This is useful for preventing stack overflows + * (`RangeError: Maximum call stack size exceeded`) and generally keeping + * [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony) + * contained. ES2017 `async` functions are returned as-is -- they are immune + * to Zalgo's corrupting influences, as they always resolve on a later tick. + * + * @name ensureAsync + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - an async function, one that expects a node-style + * callback as its last argument. + * @returns {AsyncFunction} Returns a wrapped function with the exact same call + * signature as the function passed in. + * @example + * + * function sometimesAsync(arg, callback) { + * if (cache[arg]) { + * return callback(null, cache[arg]); // this would be synchronous!! + * } else { + * doSomeIO(arg, callback); // this IO would be asynchronous + * } + * } + * + * // this has a risk of stack overflows if many results are cached in a row + * async.mapSeries(args, sometimesAsync, done); + * + * // this will defer sometimesAsync's callback if necessary, + * // preventing stack overflows + * async.mapSeries(args, async.ensureAsync(sometimesAsync), done); + */ + function ensureAsync(fn) { + if (isAsync(fn)) return fn; + return function (...args/*, callback*/) { + var callback = args.pop(); + var sync = true; + args.push((...innerArgs) => { + if (sync) { + setImmediate$1(() => callback(...innerArgs)); + } else { + callback(...innerArgs); + } + }); + fn.apply(this, args); + sync = false; + }; + } + + /** + * Returns `true` if every element in `coll` satisfies an async test. If any + * iteratee call returns `false`, the main `callback` is immediately called. + * + * @name every + * @static + * @memberOf module:Collections + * @method + * @alias all + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file5.txt']; + * const withMissingFileList = ['file1.txt','file2.txt','file4.txt']; + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.every(fileList, fileExists, function(err, result) { + * console.log(result); + * // true + * // result is true since every file exists + * }); + * + * async.every(withMissingFileList, fileExists, function(err, result) { + * console.log(result); + * // false + * // result is false since NOT every file exists + * }); + * + * // Using Promises + * async.every(fileList, fileExists) + * .then( result => { + * console.log(result); + * // true + * // result is true since every file exists + * }).catch( err => { + * console.log(err); + * }); + * + * async.every(withMissingFileList, fileExists) + * .then( result => { + * console.log(result); + * // false + * // result is false since NOT every file exists + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.every(fileList, fileExists); + * console.log(result); + * // true + * // result is true since every file exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + * async () => { + * try { + * let result = await async.every(withMissingFileList, fileExists); + * console.log(result); + * // false + * // result is false since NOT every file exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function every(coll, iteratee, callback) { + return _createTester(bool => !bool, res => !res)(eachOf$1, coll, iteratee, callback) + } + var every$1 = awaitify(every, 3); + + /** + * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time. + * + * @name everyLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ + function everyLimit(coll, limit, iteratee, callback) { + return _createTester(bool => !bool, res => !res)(eachOfLimit(limit), coll, iteratee, callback) + } + var everyLimit$1 = awaitify(everyLimit, 4); + + /** + * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time. + * + * @name everySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in series. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ + function everySeries(coll, iteratee, callback) { + return _createTester(bool => !bool, res => !res)(eachOfSeries$1, coll, iteratee, callback) + } + var everySeries$1 = awaitify(everySeries, 3); + + function filterArray(eachfn, arr, iteratee, callback) { + var truthValues = new Array(arr.length); + eachfn(arr, (x, index, iterCb) => { + iteratee(x, (err, v) => { + truthValues[index] = !!v; + iterCb(err); + }); + }, err => { + if (err) return callback(err); + var results = []; + for (var i = 0; i < arr.length; i++) { + if (truthValues[i]) results.push(arr[i]); + } + callback(null, results); + }); + } + + function filterGeneric(eachfn, coll, iteratee, callback) { + var results = []; + eachfn(coll, (x, index, iterCb) => { + iteratee(x, (err, v) => { + if (err) return iterCb(err); + if (v) { + results.push({index, value: x}); + } + iterCb(err); + }); + }, err => { + if (err) return callback(err); + callback(null, results + .sort((a, b) => a.index - b.index) + .map(v => v.value)); + }); + } + + function _filter(eachfn, coll, iteratee, callback) { + var filter = isArrayLike(coll) ? filterArray : filterGeneric; + return filter(eachfn, coll, wrapAsync(iteratee), callback); + } + + /** + * Returns a new array of all the values in `coll` which pass an async truth + * test. This operation is performed in parallel, but the results array will be + * in the same order as the original. + * + * @name filter + * @static + * @memberOf module:Collections + * @method + * @alias select + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * + * const files = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt']; + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.filter(files, fileExists, function(err, results) { + * if(err) { + * console.log(err); + * } else { + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * } + * }); + * + * // Using Promises + * async.filter(files, fileExists) + * .then(results => { + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.filter(files, fileExists); + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function filter (coll, iteratee, callback) { + return _filter(eachOf$1, coll, iteratee, callback) + } + var filter$1 = awaitify(filter, 3); + + /** + * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a + * time. + * + * @name filterLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback provided + */ + function filterLimit (coll, limit, iteratee, callback) { + return _filter(eachOfLimit(limit), coll, iteratee, callback) + } + var filterLimit$1 = awaitify(filterLimit, 4); + + /** + * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time. + * + * @name filterSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results) + * @returns {Promise} a promise, if no callback provided + */ + function filterSeries (coll, iteratee, callback) { + return _filter(eachOfSeries$1, coll, iteratee, callback) + } + var filterSeries$1 = awaitify(filterSeries, 3); + + /** + * Calls the asynchronous function `fn` with a callback parameter that allows it + * to call itself again, in series, indefinitely. + + * If an error is passed to the callback then `errback` is called with the + * error, and execution stops, otherwise it will never be called. + * + * @name forever + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} fn - an async function to call repeatedly. + * Invoked with (next). + * @param {Function} [errback] - when `fn` passes an error to it's callback, + * this function will be called, and execution stops. Invoked with (err). + * @returns {Promise} a promise that rejects if an error occurs and an errback + * is not passed + * @example + * + * async.forever( + * function(next) { + * // next is suitable for passing to things that need a callback(err [, whatever]); + * // it will result in this function being called again. + * }, + * function(err) { + * // if next is called with a value in its first parameter, it will appear + * // in here as 'err', and execution will stop. + * } + * ); + */ + function forever(fn, errback) { + var done = onlyOnce(errback); + var task = wrapAsync(ensureAsync(fn)); + + function next(err) { + if (err) return done(err); + if (err === false) return; + task(next); + } + return next(); + } + var forever$1 = awaitify(forever, 2); + + /** + * The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time. + * + * @name groupByLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.groupBy]{@link module:Collections.groupBy} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + */ + function groupByLimit(coll, limit, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return mapLimit$1(coll, limit, (val, iterCb) => { + _iteratee(val, (err, key) => { + if (err) return iterCb(err); + return iterCb(err, {key, val}); + }); + }, (err, mapResults) => { + var result = {}; + // from MDN, handle object having an `hasOwnProperty` prop + var {hasOwnProperty} = Object.prototype; + + for (var i = 0; i < mapResults.length; i++) { + if (mapResults[i]) { + var {key} = mapResults[i]; + var {val} = mapResults[i]; + + if (hasOwnProperty.call(result, key)) { + result[key].push(val); + } else { + result[key] = [val]; + } + } + } + + return callback(err, result); + }); + } + + var groupByLimit$1 = awaitify(groupByLimit, 4); + + /** + * Returns a new object, where each value corresponds to an array of items, from + * `coll`, that returned the corresponding key. That is, the keys of the object + * correspond to the values passed to the `iteratee` callback. + * + * Note: Since this function applies the `iteratee` to each item in parallel, + * there is no guarantee that the `iteratee` functions will complete in order. + * However, the values for each key in the `result` will be in the same order as + * the original `coll`. For Objects, the values will roughly be in the order of + * the original Objects' keys (but this can vary across JavaScript engines). + * + * @name groupBy + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * const files = ['dir1/file1.txt','dir2','dir4'] + * + * // asynchronous function that detects file type as none, file, or directory + * function detectFile(file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(null, 'none'); + * } + * callback(null, stat.isDirectory() ? 'directory' : 'file'); + * }); + * } + * + * //Using callbacks + * async.groupBy(files, detectFile, function(err, result) { + * if(err) { + * console.log(err); + * } else { + * console.log(result); + * // { + * // file: [ 'dir1/file1.txt' ], + * // none: [ 'dir4' ], + * // directory: [ 'dir2'] + * // } + * // result is object containing the files grouped by type + * } + * }); + * + * // Using Promises + * async.groupBy(files, detectFile) + * .then( result => { + * console.log(result); + * // { + * // file: [ 'dir1/file1.txt' ], + * // none: [ 'dir4' ], + * // directory: [ 'dir2'] + * // } + * // result is object containing the files grouped by type + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.groupBy(files, detectFile); + * console.log(result); + * // { + * // file: [ 'dir1/file1.txt' ], + * // none: [ 'dir4' ], + * // directory: [ 'dir2'] + * // } + * // result is object containing the files grouped by type + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function groupBy (coll, iteratee, callback) { + return groupByLimit$1(coll, Infinity, iteratee, callback) + } + + /** + * The same as [`groupBy`]{@link module:Collections.groupBy} but runs only a single async operation at a time. + * + * @name groupBySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.groupBy]{@link module:Collections.groupBy} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whose + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + */ + function groupBySeries (coll, iteratee, callback) { + return groupByLimit$1(coll, 1, iteratee, callback) + } + + /** + * Logs the result of an `async` function to the `console`. Only works in + * Node.js or in browsers that support `console.log` and `console.error` (such + * as FF and Chrome). If multiple arguments are returned from the async + * function, `console.log` is called on each argument in order. + * + * @name log + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} function - The function you want to eventually apply + * all arguments to. + * @param {...*} arguments... - Any number of arguments to apply to the function. + * @example + * + * // in a module + * var hello = function(name, callback) { + * setTimeout(function() { + * callback(null, 'hello ' + name); + * }, 1000); + * }; + * + * // in the node repl + * node> async.log(hello, 'world'); + * 'hello world' + */ + var log = consoleFunc('log'); + + /** + * The same as [`mapValues`]{@link module:Collections.mapValues} but runs a maximum of `limit` async operations at a + * time. + * + * @name mapValuesLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.mapValues]{@link module:Collections.mapValues} + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + */ + function mapValuesLimit(obj, limit, iteratee, callback) { + callback = once(callback); + var newObj = {}; + var _iteratee = wrapAsync(iteratee); + return eachOfLimit(limit)(obj, (val, key, next) => { + _iteratee(val, key, (err, result) => { + if (err) return next(err); + newObj[key] = result; + next(err); + }); + }, err => callback(err, newObj)); + } + + var mapValuesLimit$1 = awaitify(mapValuesLimit, 4); + + /** + * A relative of [`map`]{@link module:Collections.map}, designed for use with objects. + * + * Produces a new Object by mapping each value of `obj` through the `iteratee` + * function. The `iteratee` is called each `value` and `key` from `obj` and a + * callback for when it has finished processing. Each of these callbacks takes + * two arguments: an `error`, and the transformed item from `obj`. If `iteratee` + * passes an error to its callback, the main `callback` (for the `mapValues` + * function) is immediately called with the error. + * + * Note, the order of the keys in the result is not guaranteed. The keys will + * be roughly in the order they complete, (but this is very engine-specific) + * + * @name mapValues + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * // file4.txt does not exist + * + * const fileMap = { + * f1: 'file1.txt', + * f2: 'file2.txt', + * f3: 'file3.txt' + * }; + * + * const withMissingFileMap = { + * f1: 'file1.txt', + * f2: 'file2.txt', + * f3: 'file4.txt' + * }; + * + * // asynchronous function that returns the file size in bytes + * function getFileSizeInBytes(file, key, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, stat.size); + * }); + * } + * + * // Using callbacks + * async.mapValues(fileMap, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * } else { + * console.log(result); + * // result is now a map of file size in bytes for each file, e.g. + * // { + * // f1: 1000, + * // f2: 2000, + * // f3: 3000 + * // } + * } + * }); + * + * // Error handling + * async.mapValues(withMissingFileMap, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(result); + * } + * }); + * + * // Using Promises + * async.mapValues(fileMap, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * // result is now a map of file size in bytes for each file, e.g. + * // { + * // f1: 1000, + * // f2: 2000, + * // f3: 3000 + * // } + * }).catch (err => { + * console.log(err); + * }); + * + * // Error Handling + * async.mapValues(withMissingFileMap, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * }).catch (err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.mapValues(fileMap, getFileSizeInBytes); + * console.log(result); + * // result is now a map of file size in bytes for each file, e.g. + * // { + * // f1: 1000, + * // f2: 2000, + * // f3: 3000 + * // } + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let result = await async.mapValues(withMissingFileMap, getFileSizeInBytes); + * console.log(result); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ + function mapValues(obj, iteratee, callback) { + return mapValuesLimit$1(obj, Infinity, iteratee, callback) + } + + /** + * The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time. + * + * @name mapValuesSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.mapValues]{@link module:Collections.mapValues} + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + */ + function mapValuesSeries(obj, iteratee, callback) { + return mapValuesLimit$1(obj, 1, iteratee, callback) + } + + /** + * Caches the results of an async function. When creating a hash to store + * function results against, the callback is omitted from the hash and an + * optional hash function can be used. + * + * **Note: if the async function errs, the result will not be cached and + * subsequent calls will call the wrapped function.** + * + * If no hash function is specified, the first argument is used as a hash key, + * which may work reasonably if it is a string or a data type that converts to a + * distinct string. Note that objects and arrays will not behave reasonably. + * Neither will cases where the other arguments are significant. In such cases, + * specify your own hash function. + * + * The cache of results is exposed as the `memo` property of the function + * returned by `memoize`. + * + * @name memoize + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - The async function to proxy and cache results from. + * @param {Function} hasher - An optional function for generating a custom hash + * for storing results. It has all the arguments applied to it apart from the + * callback, and must be synchronous. + * @returns {AsyncFunction} a memoized version of `fn` + * @example + * + * var slow_fn = function(name, callback) { + * // do something + * callback(null, result); + * }; + * var fn = async.memoize(slow_fn); + * + * // fn can now be used as if it were slow_fn + * fn('some name', function() { + * // callback + * }); + */ + function memoize(fn, hasher = v => v) { + var memo = Object.create(null); + var queues = Object.create(null); + var _fn = wrapAsync(fn); + var memoized = initialParams((args, callback) => { + var key = hasher(...args); + if (key in memo) { + setImmediate$1(() => callback(null, ...memo[key])); + } else if (key in queues) { + queues[key].push(callback); + } else { + queues[key] = [callback]; + _fn(...args, (err, ...resultArgs) => { + // #1465 don't memoize if an error occurred + if (!err) { + memo[key] = resultArgs; + } + var q = queues[key]; + delete queues[key]; + for (var i = 0, l = q.length; i < l; i++) { + q[i](err, ...resultArgs); + } + }); + } + }); + memoized.memo = memo; + memoized.unmemoized = fn; + return memoized; + } + + /* istanbul ignore file */ + + /** + * Calls `callback` on a later loop around the event loop. In Node.js this just + * calls `process.nextTick`. In the browser it will use `setImmediate` if + * available, otherwise `setTimeout(callback, 0)`, which means other higher + * priority events may precede the execution of `callback`. + * + * This is used internally for browser-compatibility purposes. + * + * @name nextTick + * @static + * @memberOf module:Utils + * @method + * @see [async.setImmediate]{@link module:Utils.setImmediate} + * @category Util + * @param {Function} callback - The function to call on a later loop around + * the event loop. Invoked with (args...). + * @param {...*} args... - any number of additional arguments to pass to the + * callback on the next tick. + * @example + * + * var call_order = []; + * async.nextTick(function() { + * call_order.push('two'); + * // call_order now equals ['one','two'] + * }); + * call_order.push('one'); + * + * async.setImmediate(function (a, b, c) { + * // a, b, and c equal 1, 2, and 3 + * }, 1, 2, 3); + */ + var _defer$1; + + if (hasNextTick) { + _defer$1 = process.nextTick; + } else if (hasSetImmediate) { + _defer$1 = setImmediate; + } else { + _defer$1 = fallback; + } + + var nextTick = wrap(_defer$1); + + var parallel = awaitify((eachfn, tasks, callback) => { + var results = isArrayLike(tasks) ? [] : {}; + + eachfn(tasks, (task, key, taskCb) => { + wrapAsync(task)((err, ...result) => { + if (result.length < 2) { + [result] = result; + } + results[key] = result; + taskCb(err); + }); + }, err => callback(err, results)); + }, 3); + + /** + * Run the `tasks` collection of functions in parallel, without waiting until + * the previous function has completed. If any of the functions pass an error to + * its callback, the main `callback` is immediately called with the value of the + * error. Once the `tasks` have completed, the results are passed to the final + * `callback` as an array. + * + * **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about + * parallel execution of code. If your tasks do not use any timers or perform + * any I/O, they will actually be executed in series. Any synchronous setup + * sections for each task will happen one after the other. JavaScript remains + * single-threaded. + * + * **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the + * execution of other tasks when a task fails. + * + * It is also possible to use an object instead of an array. Each property will + * be run as a function and the results will be passed to the final `callback` + * as an object instead of an array. This can be a more readable way of handling + * results from {@link async.parallel}. + * + * @name parallel + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of + * [async functions]{@link AsyncFunction} to run. + * Each async function can complete with any number of optional `result` values. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed successfully. This function gets a results array + * (or object) containing all the result arguments passed to the task callbacks. + * Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + * + * @example + * + * //Using Callbacks + * async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ], function(err, results) { + * console.log(results); + * // results is equal to ['one','two'] even though + * // the second function had a shorter timeout. + * }); + * + * // an example using an object instead of an array + * async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }, function(err, results) { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }); + * + * //Using Promises + * async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]).then(results => { + * console.log(results); + * // results is equal to ['one','two'] even though + * // the second function had a shorter timeout. + * }).catch(err => { + * console.log(err); + * }); + * + * // an example using an object instead of an array + * async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }).then(results => { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }).catch(err => { + * console.log(err); + * }); + * + * //Using async/await + * async () => { + * try { + * let results = await async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]); + * console.log(results); + * // results is equal to ['one','two'] even though + * // the second function had a shorter timeout. + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // an example using an object instead of an array + * async () => { + * try { + * let results = await async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }); + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function parallel$1(tasks, callback) { + return parallel(eachOf$1, tasks, callback); + } + + /** + * The same as [`parallel`]{@link module:ControlFlow.parallel} but runs a maximum of `limit` async operations at a + * time. + * + * @name parallelLimit + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.parallel]{@link module:ControlFlow.parallel} + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of + * [async functions]{@link AsyncFunction} to run. + * Each async function can complete with any number of optional `result` values. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed successfully. This function gets a results array + * (or object) containing all the result arguments passed to the task callbacks. + * Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + */ + function parallelLimit(tasks, limit, callback) { + return parallel(eachOfLimit(limit), tasks, callback); + } + + /** + * A queue of tasks for the worker function to complete. + * @typedef {Iterable} QueueObject + * @memberOf module:ControlFlow + * @property {Function} length - a function returning the number of items + * waiting to be processed. Invoke with `queue.length()`. + * @property {boolean} started - a boolean indicating whether or not any + * items have been pushed and processed by the queue. + * @property {Function} running - a function returning the number of items + * currently being processed. Invoke with `queue.running()`. + * @property {Function} workersList - a function returning the array of items + * currently being processed. Invoke with `queue.workersList()`. + * @property {Function} idle - a function returning false if there are items + * waiting or being processed, or true if not. Invoke with `queue.idle()`. + * @property {number} concurrency - an integer for determining how many `worker` + * functions should be run in parallel. This property can be changed after a + * `queue` is created to alter the concurrency on-the-fly. + * @property {number} payload - an integer that specifies how many items are + * passed to the worker function at a time. only applies if this is a + * [cargo]{@link module:ControlFlow.cargo} object + * @property {AsyncFunction} push - add a new task to the `queue`. Calls `callback` + * once the `worker` has finished processing the task. Instead of a single task, + * a `tasks` array can be submitted. The respective callback is used for every + * task in the list. Invoke with `queue.push(task, [callback])`, + * @property {AsyncFunction} unshift - add a new task to the front of the `queue`. + * Invoke with `queue.unshift(task, [callback])`. + * @property {AsyncFunction} pushAsync - the same as `q.push`, except this returns + * a promise that rejects if an error occurs. + * @property {AsyncFunction} unshiftAsync - the same as `q.unshift`, except this returns + * a promise that rejects if an error occurs. + * @property {Function} remove - remove items from the queue that match a test + * function. The test function will be passed an object with a `data` property, + * and a `priority` property, if this is a + * [priorityQueue]{@link module:ControlFlow.priorityQueue} object. + * Invoked with `queue.remove(testFn)`, where `testFn` is of the form + * `function ({data, priority}) {}` and returns a Boolean. + * @property {Function} saturated - a function that sets a callback that is + * called when the number of running workers hits the `concurrency` limit, and + * further tasks will be queued. If the callback is omitted, `q.saturated()` + * returns a promise for the next occurrence. + * @property {Function} unsaturated - a function that sets a callback that is + * called when the number of running workers is less than the `concurrency` & + * `buffer` limits, and further tasks will not be queued. If the callback is + * omitted, `q.unsaturated()` returns a promise for the next occurrence. + * @property {number} buffer - A minimum threshold buffer in order to say that + * the `queue` is `unsaturated`. + * @property {Function} empty - a function that sets a callback that is called + * when the last item from the `queue` is given to a `worker`. If the callback + * is omitted, `q.empty()` returns a promise for the next occurrence. + * @property {Function} drain - a function that sets a callback that is called + * when the last item from the `queue` has returned from the `worker`. If the + * callback is omitted, `q.drain()` returns a promise for the next occurrence. + * @property {Function} error - a function that sets a callback that is called + * when a task errors. Has the signature `function(error, task)`. If the + * callback is omitted, `error()` returns a promise that rejects on the next + * error. + * @property {boolean} paused - a boolean for determining whether the queue is + * in a paused state. + * @property {Function} pause - a function that pauses the processing of tasks + * until `resume()` is called. Invoke with `queue.pause()`. + * @property {Function} resume - a function that resumes the processing of + * queued tasks when the queue is paused. Invoke with `queue.resume()`. + * @property {Function} kill - a function that removes the `drain` callback and + * empties remaining tasks from the queue forcing it to go idle. No more tasks + * should be pushed to the queue after calling this function. Invoke with `queue.kill()`. + * + * @example + * const q = async.queue(worker, 2) + * q.push(item1) + * q.push(item2) + * q.push(item3) + * // queues are iterable, spread into an array to inspect + * const items = [...q] // [item1, item2, item3] + * // or use for of + * for (let item of q) { + * console.log(item) + * } + * + * q.drain(() => { + * console.log('all done') + * }) + * // or + * await q.drain() + */ + + /** + * Creates a `queue` object with the specified `concurrency`. Tasks added to the + * `queue` are processed in parallel (up to the `concurrency` limit). If all + * `worker`s are in progress, the task is queued until one becomes available. + * Once a `worker` completes a `task`, that `task`'s callback is called. + * + * @name queue + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} worker - An async function for processing a queued task. + * If you want to handle errors from an individual task, pass a callback to + * `q.push()`. Invoked with (task, callback). + * @param {number} [concurrency=1] - An `integer` for determining how many + * `worker` functions should be run in parallel. If omitted, the concurrency + * defaults to `1`. If the concurrency is `0`, an error is thrown. + * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can be + * attached as certain properties to listen for specific events during the + * lifecycle of the queue. + * @example + * + * // create a queue object with concurrency 2 + * var q = async.queue(function(task, callback) { + * console.log('hello ' + task.name); + * callback(); + * }, 2); + * + * // assign a callback + * q.drain(function() { + * console.log('all items have been processed'); + * }); + * // or await the end + * await q.drain() + * + * // assign an error callback + * q.error(function(err, task) { + * console.error('task experienced an error'); + * }); + * + * // add some items to the queue + * q.push({name: 'foo'}, function(err) { + * console.log('finished processing foo'); + * }); + * // callback is optional + * q.push({name: 'bar'}); + * + * // add some items to the queue (batch-wise) + * q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) { + * console.log('finished processing item'); + * }); + * + * // add some items to the front of the queue + * q.unshift({name: 'bar'}, function (err) { + * console.log('finished processing bar'); + * }); + */ + function queue$1 (worker, concurrency) { + var _worker = wrapAsync(worker); + return queue((items, cb) => { + _worker(items[0], cb); + }, concurrency, 1); + } + + // Binary min-heap implementation used for priority queue. + // Implementation is stable, i.e. push time is considered for equal priorities + class Heap { + constructor() { + this.heap = []; + this.pushCount = Number.MIN_SAFE_INTEGER; + } + + get length() { + return this.heap.length; + } + + empty () { + this.heap = []; + return this; + } + + percUp(index) { + let p; + + while (index > 0 && smaller(this.heap[index], this.heap[p=parent(index)])) { + let t = this.heap[index]; + this.heap[index] = this.heap[p]; + this.heap[p] = t; + + index = p; + } + } + + percDown(index) { + let l; + + while ((l=leftChi(index)) < this.heap.length) { + if (l+1 < this.heap.length && smaller(this.heap[l+1], this.heap[l])) { + l = l+1; + } + + if (smaller(this.heap[index], this.heap[l])) { + break; + } + + let t = this.heap[index]; + this.heap[index] = this.heap[l]; + this.heap[l] = t; + + index = l; + } + } + + push(node) { + node.pushCount = ++this.pushCount; + this.heap.push(node); + this.percUp(this.heap.length-1); + } + + unshift(node) { + return this.heap.push(node); + } + + shift() { + let [top] = this.heap; + + this.heap[0] = this.heap[this.heap.length-1]; + this.heap.pop(); + this.percDown(0); + + return top; + } + + toArray() { + return [...this]; + } + + *[Symbol.iterator] () { + for (let i = 0; i < this.heap.length; i++) { + yield this.heap[i].data; + } + } + + remove (testFn) { + let j = 0; + for (let i = 0; i < this.heap.length; i++) { + if (!testFn(this.heap[i])) { + this.heap[j] = this.heap[i]; + j++; + } + } + + this.heap.splice(j); + + for (let i = parent(this.heap.length-1); i >= 0; i--) { + this.percDown(i); + } + + return this; + } + } + + function leftChi(i) { + return (i<<1)+1; + } + + function parent(i) { + return ((i+1)>>1)-1; + } + + function smaller(x, y) { + if (x.priority !== y.priority) { + return x.priority < y.priority; + } + else { + return x.pushCount < y.pushCount; + } + } + + /** + * The same as [async.queue]{@link module:ControlFlow.queue} only tasks are assigned a priority and + * completed in ascending priority order. + * + * @name priorityQueue + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.queue]{@link module:ControlFlow.queue} + * @category Control Flow + * @param {AsyncFunction} worker - An async function for processing a queued task. + * If you want to handle errors from an individual task, pass a callback to + * `q.push()`. + * Invoked with (task, callback). + * @param {number} concurrency - An `integer` for determining how many `worker` + * functions should be run in parallel. If omitted, the concurrency defaults to + * `1`. If the concurrency is `0`, an error is thrown. + * @returns {module:ControlFlow.QueueObject} A priorityQueue object to manage the tasks. There are three + * differences between `queue` and `priorityQueue` objects: + * * `push(task, priority, [callback])` - `priority` should be a number. If an + * array of `tasks` is given, all tasks will be assigned the same priority. + * * `pushAsync(task, priority, [callback])` - the same as `priorityQueue.push`, + * except this returns a promise that rejects if an error occurs. + * * The `unshift` and `unshiftAsync` methods were removed. + */ + function priorityQueue(worker, concurrency) { + // Start with a normal queue + var q = queue$1(worker, concurrency); + + var { + push, + pushAsync + } = q; + + q._tasks = new Heap(); + q._createTaskItem = ({data, priority}, callback) => { + return { + data, + priority, + callback + }; + }; + + function createDataItems(tasks, priority) { + if (!Array.isArray(tasks)) { + return {data: tasks, priority}; + } + return tasks.map(data => { return {data, priority}; }); + } + + // Override push to accept second parameter representing priority + q.push = function(data, priority = 0, callback) { + return push(createDataItems(data, priority), callback); + }; + + q.pushAsync = function(data, priority = 0, callback) { + return pushAsync(createDataItems(data, priority), callback); + }; + + // Remove unshift functions + delete q.unshift; + delete q.unshiftAsync; + + return q; + } + + /** + * Runs the `tasks` array of functions in parallel, without waiting until the + * previous function has completed. Once any of the `tasks` complete or pass an + * error to its callback, the main `callback` is immediately called. It's + * equivalent to `Promise.race()`. + * + * @name race + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array} tasks - An array containing [async functions]{@link AsyncFunction} + * to run. Each function can complete with an optional `result` value. + * @param {Function} callback - A callback to run once any of the functions have + * completed. This function gets an error or result from the first function that + * completed. Invoked with (err, result). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * async.race([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ], + * // main callback + * function(err, result) { + * // the result will be equal to 'two' as it finishes earlier + * }); + */ + function race(tasks, callback) { + callback = once(callback); + if (!Array.isArray(tasks)) return callback(new TypeError('First argument to race must be an array of functions')); + if (!tasks.length) return callback(); + for (var i = 0, l = tasks.length; i < l; i++) { + wrapAsync(tasks[i])(callback); + } + } + + var race$1 = awaitify(race, 2); + + /** + * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order. + * + * @name reduceRight + * @static + * @memberOf module:Collections + * @method + * @see [async.reduce]{@link module:Collections.reduce} + * @alias foldr + * @category Collection + * @param {Array} array - A collection to iterate over. + * @param {*} memo - The initial state of the reduction. + * @param {AsyncFunction} iteratee - A function applied to each item in the + * array to produce the next step in the reduction. + * The `iteratee` should complete with the next state of the reduction. + * If the iteratee completes with an error, the reduction is stopped and the + * main `callback` is immediately called with the error. + * Invoked with (memo, item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the reduced value. Invoked with + * (err, result). + * @returns {Promise} a promise, if no callback is passed + */ + function reduceRight (array, memo, iteratee, callback) { + var reversed = [...array].reverse(); + return reduce$1(reversed, memo, iteratee, callback); + } + + /** + * Wraps the async function in another function that always completes with a + * result object, even when it errors. + * + * The result object has either the property `error` or `value`. + * + * @name reflect + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - The async function you want to wrap + * @returns {Function} - A function that always passes null to it's callback as + * the error. The second argument to the callback will be an `object` with + * either an `error` or a `value` property. + * @example + * + * async.parallel([ + * async.reflect(function(callback) { + * // do some stuff ... + * callback(null, 'one'); + * }), + * async.reflect(function(callback) { + * // do some more stuff but error ... + * callback('bad stuff happened'); + * }), + * async.reflect(function(callback) { + * // do some more stuff ... + * callback(null, 'two'); + * }) + * ], + * // optional callback + * function(err, results) { + * // values + * // results[0].value = 'one' + * // results[1].error = 'bad stuff happened' + * // results[2].value = 'two' + * }); + */ + function reflect(fn) { + var _fn = wrapAsync(fn); + return initialParams(function reflectOn(args, reflectCallback) { + args.push((error, ...cbArgs) => { + let retVal = {}; + if (error) { + retVal.error = error; + } + if (cbArgs.length > 0){ + var value = cbArgs; + if (cbArgs.length <= 1) { + [value] = cbArgs; + } + retVal.value = value; + } + reflectCallback(null, retVal); + }); + + return _fn.apply(this, args); + }); + } + + /** + * A helper function that wraps an array or an object of functions with `reflect`. + * + * @name reflectAll + * @static + * @memberOf module:Utils + * @method + * @see [async.reflect]{@link module:Utils.reflect} + * @category Util + * @param {Array|Object|Iterable} tasks - The collection of + * [async functions]{@link AsyncFunction} to wrap in `async.reflect`. + * @returns {Array} Returns an array of async functions, each wrapped in + * `async.reflect` + * @example + * + * let tasks = [ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * // do some more stuff but error ... + * callback(new Error('bad stuff happened')); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]; + * + * async.parallel(async.reflectAll(tasks), + * // optional callback + * function(err, results) { + * // values + * // results[0].value = 'one' + * // results[1].error = Error('bad stuff happened') + * // results[2].value = 'two' + * }); + * + * // an example using an object instead of an array + * let tasks = { + * one: function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * two: function(callback) { + * callback('two'); + * }, + * three: function(callback) { + * setTimeout(function() { + * callback(null, 'three'); + * }, 100); + * } + * }; + * + * async.parallel(async.reflectAll(tasks), + * // optional callback + * function(err, results) { + * // values + * // results.one.value = 'one' + * // results.two.error = 'two' + * // results.three.value = 'three' + * }); + */ + function reflectAll(tasks) { + var results; + if (Array.isArray(tasks)) { + results = tasks.map(reflect); + } else { + results = {}; + Object.keys(tasks).forEach(key => { + results[key] = reflect.call(this, tasks[key]); + }); + } + return results; + } + + function reject(eachfn, arr, _iteratee, callback) { + const iteratee = wrapAsync(_iteratee); + return _filter(eachfn, arr, (value, cb) => { + iteratee(value, (err, v) => { + cb(err, !v); + }); + }, callback); + } + + /** + * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test. + * + * @name reject + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * + * const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt']; + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.reject(fileList, fileExists, function(err, results) { + * // [ 'dir3/file6.txt' ] + * // results now equals an array of the non-existing files + * }); + * + * // Using Promises + * async.reject(fileList, fileExists) + * .then( results => { + * console.log(results); + * // [ 'dir3/file6.txt' ] + * // results now equals an array of the non-existing files + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.reject(fileList, fileExists); + * console.log(results); + * // [ 'dir3/file6.txt' ] + * // results now equals an array of the non-existing files + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function reject$1 (coll, iteratee, callback) { + return reject(eachOf$1, coll, iteratee, callback) + } + var reject$2 = awaitify(reject$1, 3); + + /** + * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a + * time. + * + * @name rejectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.reject]{@link module:Collections.reject} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ + function rejectLimit (coll, limit, iteratee, callback) { + return reject(eachOfLimit(limit), coll, iteratee, callback) + } + var rejectLimit$1 = awaitify(rejectLimit, 4); + + /** + * The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time. + * + * @name rejectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.reject]{@link module:Collections.reject} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ + function rejectSeries (coll, iteratee, callback) { + return reject(eachOfSeries$1, coll, iteratee, callback) + } + var rejectSeries$1 = awaitify(rejectSeries, 3); + + function constant$1(value) { + return function () { + return value; + } + } + + /** + * Attempts to get a successful response from `task` no more than `times` times + * before returning an error. If the task is successful, the `callback` will be + * passed the result of the successful task. If all attempts fail, the callback + * will be passed the error and result (if any) of the final attempt. + * + * @name retry + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @see [async.retryable]{@link module:ControlFlow.retryable} + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an + * object with `times` and `interval` or a number. + * * `times` - The number of attempts to make before giving up. The default + * is `5`. + * * `interval` - The time to wait between retries, in milliseconds. The + * default is `0`. The interval may also be specified as a function of the + * retry count (see example). + * * `errorFilter` - An optional synchronous function that is invoked on + * erroneous result. If it returns `true` the retry attempts will continue; + * if the function returns `false` the retry flow is aborted with the current + * attempt's error and result being returned to the final callback. + * Invoked with (err). + * * If `opts` is a number, the number specifies the number of times to retry, + * with the default interval of `0`. + * @param {AsyncFunction} task - An async function to retry. + * Invoked with (callback). + * @param {Function} [callback] - An optional callback which is called when the + * task has succeeded, or after the final failed attempt. It receives the `err` + * and `result` arguments of the last attempt at completing the `task`. Invoked + * with (err, results). + * @returns {Promise} a promise if no callback provided + * + * @example + * + * // The `retry` function can be used as a stand-alone control flow by passing + * // a callback, as shown below: + * + * // try calling apiMethod 3 times + * async.retry(3, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 3 times, waiting 200 ms between each retry + * async.retry({times: 3, interval: 200}, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 10 times with exponential backoff + * // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds) + * async.retry({ + * times: 10, + * interval: function(retryCount) { + * return 50 * Math.pow(2, retryCount); + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod the default 5 times no delay between each retry + * async.retry(apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod only when error condition satisfies, all other + * // errors will abort the retry control flow and return to final callback + * async.retry({ + * errorFilter: function(err) { + * return err.message === 'Temporary error'; // only retry on a specific error + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // to retry individual methods that are not as reliable within other + * // control flow functions, use the `retryable` wrapper: + * async.auto({ + * users: api.getUsers.bind(api), + * payments: async.retryable(3, api.getPayments.bind(api)) + * }, function(err, results) { + * // do something with the results + * }); + * + */ + const DEFAULT_TIMES = 5; + const DEFAULT_INTERVAL = 0; + + function retry(opts, task, callback) { + var options = { + times: DEFAULT_TIMES, + intervalFunc: constant$1(DEFAULT_INTERVAL) + }; + + if (arguments.length < 3 && typeof opts === 'function') { + callback = task || promiseCallback(); + task = opts; + } else { + parseTimes(options, opts); + callback = callback || promiseCallback(); + } + + if (typeof task !== 'function') { + throw new Error("Invalid arguments for async.retry"); + } + + var _task = wrapAsync(task); + + var attempt = 1; + function retryAttempt() { + _task((err, ...args) => { + if (err === false) return + if (err && attempt++ < options.times && + (typeof options.errorFilter != 'function' || + options.errorFilter(err))) { + setTimeout(retryAttempt, options.intervalFunc(attempt - 1)); + } else { + callback(err, ...args); + } + }); + } + + retryAttempt(); + return callback[PROMISE_SYMBOL] + } + + function parseTimes(acc, t) { + if (typeof t === 'object') { + acc.times = +t.times || DEFAULT_TIMES; + + acc.intervalFunc = typeof t.interval === 'function' ? + t.interval : + constant$1(+t.interval || DEFAULT_INTERVAL); + + acc.errorFilter = t.errorFilter; + } else if (typeof t === 'number' || typeof t === 'string') { + acc.times = +t || DEFAULT_TIMES; + } else { + throw new Error("Invalid arguments for async.retry"); + } + } + + /** + * A close relative of [`retry`]{@link module:ControlFlow.retry}. This method + * wraps a task and makes it retryable, rather than immediately calling it + * with retries. + * + * @name retryable + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.retry]{@link module:ControlFlow.retry} + * @category Control Flow + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional + * options, exactly the same as from `retry`, except for a `opts.arity` that + * is the arity of the `task` function, defaulting to `task.length` + * @param {AsyncFunction} task - the asynchronous function to wrap. + * This function will be passed any arguments passed to the returned wrapper. + * Invoked with (...args, callback). + * @returns {AsyncFunction} The wrapped function, which when invoked, will + * retry on an error, based on the parameters specified in `opts`. + * This function will accept the same parameters as `task`. + * @example + * + * async.auto({ + * dep1: async.retryable(3, getFromFlakyService), + * process: ["dep1", async.retryable(3, function (results, cb) { + * maybeProcessData(results.dep1, cb); + * })] + * }, callback); + */ + function retryable (opts, task) { + if (!task) { + task = opts; + opts = null; + } + let arity = (opts && opts.arity) || task.length; + if (isAsync(task)) { + arity += 1; + } + var _task = wrapAsync(task); + return initialParams((args, callback) => { + if (args.length < arity - 1 || callback == null) { + args.push(callback); + callback = promiseCallback(); + } + function taskFn(cb) { + _task(...args, cb); + } + + if (opts) retry(opts, taskFn, callback); + else retry(taskFn, callback); + + return callback[PROMISE_SYMBOL] + }); + } + + /** + * Run the functions in the `tasks` collection in series, each one running once + * the previous function has completed. If any functions in the series pass an + * error to its callback, no more functions are run, and `callback` is + * immediately called with the value of the error. Otherwise, `callback` + * receives an array of results when `tasks` have completed. + * + * It is also possible to use an object instead of an array. Each property will + * be run as a function, and the results will be passed to the final `callback` + * as an object instead of an array. This can be a more readable way of handling + * results from {@link async.series}. + * + * **Note** that while many implementations preserve the order of object + * properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6) + * explicitly states that + * + * > The mechanics and order of enumerating the properties is not specified. + * + * So if you rely on the order in which your series of functions are executed, + * and want this to work on all platforms, consider using an array. + * + * @name series + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing + * [async functions]{@link AsyncFunction} to run in series. + * Each function can complete with any number of optional `result` values. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed. This function gets a results array (or object) + * containing all the result arguments passed to the `task` callbacks. Invoked + * with (err, result). + * @return {Promise} a promise, if no callback is passed + * @example + * + * //Using Callbacks + * async.series([ + * function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 'two'); + * }, 100); + * } + * ], function(err, results) { + * console.log(results); + * // results is equal to ['one','two'] + * }); + * + * // an example using objects instead of arrays + * async.series({ + * one: function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 2); + * }, 100); + * } + * }, function(err, results) { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }); + * + * //Using Promises + * async.series([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]).then(results => { + * console.log(results); + * // results is equal to ['one','two'] + * }).catch(err => { + * console.log(err); + * }); + * + * // an example using an object instead of an array + * async.series({ + * one: function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 2); + * }, 100); + * } + * }).then(results => { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }).catch(err => { + * console.log(err); + * }); + * + * //Using async/await + * async () => { + * try { + * let results = await async.series([ + * function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 'two'); + * }, 100); + * } + * ]); + * console.log(results); + * // results is equal to ['one','two'] + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // an example using an object instead of an array + * async () => { + * try { + * let results = await async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 2); + * }, 100); + * } + * }); + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function series(tasks, callback) { + return parallel(eachOfSeries$1, tasks, callback); + } + + /** + * Returns `true` if at least one element in the `coll` satisfies an async test. + * If any iteratee call returns `true`, the main `callback` is immediately + * called. + * + * @name some + * @static + * @memberOf module:Collections + * @method + * @alias any + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // true + * // result is true since some file in the list exists + * } + *); + * + * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // false + * // result is false since none of the files exists + * } + *); + * + * // Using Promises + * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists) + * .then( result => { + * console.log(result); + * // true + * // result is true since some file in the list exists + * }).catch( err => { + * console.log(err); + * }); + * + * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists) + * .then( result => { + * console.log(result); + * // false + * // result is false since none of the files exists + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists); + * console.log(result); + * // true + * // result is true since some file in the list exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + * async () => { + * try { + * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists); + * console.log(result); + * // false + * // result is false since none of the files exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function some(coll, iteratee, callback) { + return _createTester(Boolean, res => res)(eachOf$1, coll, iteratee, callback) + } + var some$1 = awaitify(some, 3); + + /** + * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time. + * + * @name someLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anyLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ + function someLimit(coll, limit, iteratee, callback) { + return _createTester(Boolean, res => res)(eachOfLimit(limit), coll, iteratee, callback) + } + var someLimit$1 = awaitify(someLimit, 4); + + /** + * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time. + * + * @name someSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anySeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in series. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ + function someSeries(coll, iteratee, callback) { + return _createTester(Boolean, res => res)(eachOfSeries$1, coll, iteratee, callback) + } + var someSeries$1 = awaitify(someSeries, 3); + + /** + * Sorts a list by the results of running each `coll` value through an async + * `iteratee`. + * + * @name sortBy + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a value to use as the sort criteria as + * its `result`. + * Invoked with (item, callback). + * @param {Function} callback - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is the items + * from the original `coll` sorted by the values returned by the `iteratee` + * calls. Invoked with (err, results). + * @returns {Promise} a promise, if no callback passed + * @example + * + * // bigfile.txt is a file that is 251100 bytes in size + * // mediumfile.txt is a file that is 11000 bytes in size + * // smallfile.txt is a file that is 121 bytes in size + * + * // asynchronous function that returns the file size in bytes + * function getFileSizeInBytes(file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, stat.size); + * }); + * } + * + * // Using callbacks + * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes, + * function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * } + * } + * ); + * + * // By modifying the callback parameter the + * // sorting order can be influenced: + * + * // ascending order + * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], function(file, callback) { + * getFileSizeInBytes(file, function(getFileSizeErr, fileSize) { + * if (getFileSizeErr) return callback(getFileSizeErr); + * callback(null, fileSize); + * }); + * }, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * } + * } + * ); + * + * // descending order + * async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], function(file, callback) { + * getFileSizeInBytes(file, function(getFileSizeErr, fileSize) { + * if (getFileSizeErr) { + * return callback(getFileSizeErr); + * } + * callback(null, fileSize * -1); + * }); + * }, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'bigfile.txt', 'mediumfile.txt', 'smallfile.txt'] + * } + * } + * ); + * + * // Error handling + * async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes, + * function(err, results) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(results); + * } + * } + * ); + * + * // Using Promises + * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes) + * .then( results => { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * }).catch( err => { + * console.log(err); + * }); + * + * // Error handling + * async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes) + * .then( results => { + * console.log(results); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * (async () => { + * try { + * let results = await async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes); + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * } + * catch (err) { + * console.log(err); + * } + * })(); + * + * // Error handling + * async () => { + * try { + * let results = await async.sortBy(['missingfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes); + * console.log(results); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ + function sortBy (coll, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return map$1(coll, (x, iterCb) => { + _iteratee(x, (err, criteria) => { + if (err) return iterCb(err); + iterCb(err, {value: x, criteria}); + }); + }, (err, results) => { + if (err) return callback(err); + callback(null, results.sort(comparator).map(v => v.value)); + }); + + function comparator(left, right) { + var a = left.criteria, b = right.criteria; + return a < b ? -1 : a > b ? 1 : 0; + } + } + var sortBy$1 = awaitify(sortBy, 3); + + /** + * Sets a time limit on an asynchronous function. If the function does not call + * its callback within the specified milliseconds, it will be called with a + * timeout error. The code property for the error object will be `'ETIMEDOUT'`. + * + * @name timeout + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} asyncFn - The async function to limit in time. + * @param {number} milliseconds - The specified time limit. + * @param {*} [info] - Any variable you want attached (`string`, `object`, etc) + * to timeout Error for more information.. + * @returns {AsyncFunction} Returns a wrapped function that can be used with any + * of the control flow functions. + * Invoke this function with the same parameters as you would `asyncFunc`. + * @example + * + * function myFunction(foo, callback) { + * doAsyncTask(foo, function(err, data) { + * // handle errors + * if (err) return callback(err); + * + * // do some stuff ... + * + * // return processed data + * return callback(null, data); + * }); + * } + * + * var wrapped = async.timeout(myFunction, 1000); + * + * // call `wrapped` as you would `myFunction` + * wrapped({ bar: 'bar' }, function(err, data) { + * // if `myFunction` takes < 1000 ms to execute, `err` + * // and `data` will have their expected values + * + * // else `err` will be an Error with the code 'ETIMEDOUT' + * }); + */ + function timeout(asyncFn, milliseconds, info) { + var fn = wrapAsync(asyncFn); + + return initialParams((args, callback) => { + var timedOut = false; + var timer; + + function timeoutCallback() { + var name = asyncFn.name || 'anonymous'; + var error = new Error('Callback function "' + name + '" timed out.'); + error.code = 'ETIMEDOUT'; + if (info) { + error.info = info; + } + timedOut = true; + callback(error); + } + + args.push((...cbArgs) => { + if (!timedOut) { + callback(...cbArgs); + clearTimeout(timer); + } + }); + + // setup timer and call original function + timer = setTimeout(timeoutCallback, milliseconds); + fn(...args); + }); + } + + function range(size) { + var result = Array(size); + while (size--) { + result[size] = size; + } + return result; + } + + /** + * The same as [times]{@link module:ControlFlow.times} but runs a maximum of `limit` async operations at a + * time. + * + * @name timesLimit + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.times]{@link module:ControlFlow.times} + * @category Control Flow + * @param {number} count - The number of times to run the function. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see [async.map]{@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + */ + function timesLimit(count, limit, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return mapLimit$1(range(count), limit, _iteratee, callback); + } + + /** + * Calls the `iteratee` function `n` times, and accumulates results in the same + * manner you would use with [map]{@link module:Collections.map}. + * + * @name times + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.map]{@link module:Collections.map} + * @category Control Flow + * @param {number} n - The number of times to run the function. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see {@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + * @example + * + * // Pretend this is some complicated async factory + * var createUser = function(id, callback) { + * callback(null, { + * id: 'user' + id + * }); + * }; + * + * // generate 5 users + * async.times(5, function(n, next) { + * createUser(n, function(err, user) { + * next(err, user); + * }); + * }, function(err, users) { + * // we should now have 5 users + * }); + */ + function times (n, iteratee, callback) { + return timesLimit(n, Infinity, iteratee, callback) + } + + /** + * The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time. + * + * @name timesSeries + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.times]{@link module:ControlFlow.times} + * @category Control Flow + * @param {number} n - The number of times to run the function. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see {@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + */ + function timesSeries (n, iteratee, callback) { + return timesLimit(n, 1, iteratee, callback) + } + + /** + * A relative of `reduce`. Takes an Object or Array, and iterates over each + * element in parallel, each step potentially mutating an `accumulator` value. + * The type of the accumulator defaults to the type of collection passed in. + * + * @name transform + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {*} [accumulator] - The initial state of the transform. If omitted, + * it will default to an empty Object or Array, depending on the type of `coll` + * @param {AsyncFunction} iteratee - A function applied to each item in the + * collection that potentially modifies the accumulator. + * Invoked with (accumulator, item, key, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the transformed accumulator. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * + * // helper function that returns human-readable size format from bytes + * function formatBytes(bytes, decimals = 2) { + * // implementation not included for brevity + * return humanReadbleFilesize; + * } + * + * const fileList = ['file1.txt','file2.txt','file3.txt']; + * + * // asynchronous function that returns the file size, transformed to human-readable format + * // e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc. + * function transformFileSize(acc, value, key, callback) { + * fs.stat(value, function(err, stat) { + * if (err) { + * return callback(err); + * } + * acc[key] = formatBytes(stat.size); + * callback(null); + * }); + * } + * + * // Using callbacks + * async.transform(fileList, transformFileSize, function(err, result) { + * if(err) { + * console.log(err); + * } else { + * console.log(result); + * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] + * } + * }); + * + * // Using Promises + * async.transform(fileList, transformFileSize) + * .then(result => { + * console.log(result); + * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * (async () => { + * try { + * let result = await async.transform(fileList, transformFileSize); + * console.log(result); + * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] + * } + * catch (err) { + * console.log(err); + * } + * })(); + * + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * + * // helper function that returns human-readable size format from bytes + * function formatBytes(bytes, decimals = 2) { + * // implementation not included for brevity + * return humanReadbleFilesize; + * } + * + * const fileMap = { f1: 'file1.txt', f2: 'file2.txt', f3: 'file3.txt' }; + * + * // asynchronous function that returns the file size, transformed to human-readable format + * // e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc. + * function transformFileSize(acc, value, key, callback) { + * fs.stat(value, function(err, stat) { + * if (err) { + * return callback(err); + * } + * acc[key] = formatBytes(stat.size); + * callback(null); + * }); + * } + * + * // Using callbacks + * async.transform(fileMap, transformFileSize, function(err, result) { + * if(err) { + * console.log(err); + * } else { + * console.log(result); + * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' } + * } + * }); + * + * // Using Promises + * async.transform(fileMap, transformFileSize) + * .then(result => { + * console.log(result); + * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' } + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.transform(fileMap, transformFileSize); + * console.log(result); + * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' } + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function transform (coll, accumulator, iteratee, callback) { + if (arguments.length <= 3 && typeof accumulator === 'function') { + callback = iteratee; + iteratee = accumulator; + accumulator = Array.isArray(coll) ? [] : {}; + } + callback = once(callback || promiseCallback()); + var _iteratee = wrapAsync(iteratee); + + eachOf$1(coll, (v, k, cb) => { + _iteratee(accumulator, v, k, cb); + }, err => callback(err, accumulator)); + return callback[PROMISE_SYMBOL] + } + + /** + * It runs each task in series but stops whenever any of the functions were + * successful. If one of the tasks were successful, the `callback` will be + * passed the result of the successful task. If all tasks fail, the callback + * will be passed the error and result (if any) of the final attempt. + * + * @name tryEach + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing functions to + * run, each function is passed a `callback(err, result)` it must call on + * completion with an error `err` (which can be `null`) and an optional `result` + * value. + * @param {Function} [callback] - An optional callback which is called when one + * of the tasks has succeeded, or all have failed. It receives the `err` and + * `result` arguments of the last attempt at completing the `task`. Invoked with + * (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * async.tryEach([ + * function getDataFromFirstWebsite(callback) { + * // Try getting the data from the first website + * callback(err, data); + * }, + * function getDataFromSecondWebsite(callback) { + * // First website failed, + * // Try getting the data from the backup website + * callback(err, data); + * } + * ], + * // optional callback + * function(err, results) { + * Now do something with the data. + * }); + * + */ + function tryEach(tasks, callback) { + var error = null; + var result; + return eachSeries$1(tasks, (task, taskCb) => { + wrapAsync(task)((err, ...args) => { + if (err === false) return taskCb(err); + + if (args.length < 2) { + [result] = args; + } else { + result = args; + } + error = err; + taskCb(err ? null : {}); + }); + }, () => callback(error, result)); + } + + var tryEach$1 = awaitify(tryEach); + + /** + * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original, + * unmemoized form. Handy for testing. + * + * @name unmemoize + * @static + * @memberOf module:Utils + * @method + * @see [async.memoize]{@link module:Utils.memoize} + * @category Util + * @param {AsyncFunction} fn - the memoized function + * @returns {AsyncFunction} a function that calls the original unmemoized function + */ + function unmemoize(fn) { + return (...args) => { + return (fn.unmemoized || fn)(...args); + }; + } + + /** + * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. + * + * @name whilst + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `iteratee`. Invoked with (). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` passes. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + * @example + * + * var count = 0; + * async.whilst( + * function test(cb) { cb(null, count < 5); }, + * function iter(callback) { + * count++; + * setTimeout(function() { + * callback(null, count); + * }, 1000); + * }, + * function (err, n) { + * // 5 seconds have passed, n = 5 + * } + * ); + */ + function whilst(test, iteratee, callback) { + callback = onlyOnce(callback); + var _fn = wrapAsync(iteratee); + var _test = wrapAsync(test); + var results = []; + + function next(err, ...rest) { + if (err) return callback(err); + results = rest; + if (err === false) return; + _test(check); + } + + function check(err, truth) { + if (err) return callback(err); + if (err === false) return; + if (!truth) return callback(null, ...results); + _fn(next); + } + + return _test(check); + } + var whilst$1 = awaitify(whilst, 3); + + /** + * Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. `callback` will be passed an error and any + * arguments passed to the final `iteratee`'s callback. + * + * The inverse of [whilst]{@link module:ControlFlow.whilst}. + * + * @name until + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `iteratee`. Invoked with (callback). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` fails. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has passed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if a callback is not passed + * + * @example + * const results = [] + * let finished = false + * async.until(function test(cb) { + * cb(null, finished) + * }, function iter(next) { + * fetchPage(url, (err, body) => { + * if (err) return next(err) + * results = results.concat(body.objects) + * finished = !!body.next + * next(err) + * }) + * }, function done (err) { + * // all pages have been fetched + * }) + */ + function until(test, iteratee, callback) { + const _test = wrapAsync(test); + return whilst$1((cb) => _test((err, truth) => cb (err, !truth)), iteratee, callback); + } + + /** + * Runs the `tasks` array of functions in series, each passing their results to + * the next in the array. However, if any of the `tasks` pass an error to their + * own callback, the next function is not executed, and the main `callback` is + * immediately called with the error. + * + * @name waterfall + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array} tasks - An array of [async functions]{@link AsyncFunction} + * to run. + * Each function should complete with any number of `result` values. + * The `result` values will be passed as arguments, in order, to the next task. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed. This will be passed the results of the last task's + * callback. Invoked with (err, [results]). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * async.waterfall([ + * function(callback) { + * callback(null, 'one', 'two'); + * }, + * function(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * }, + * function(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + * ], function (err, result) { + * // result now equals 'done' + * }); + * + * // Or, with named functions: + * async.waterfall([ + * myFirstFunction, + * mySecondFunction, + * myLastFunction, + * ], function (err, result) { + * // result now equals 'done' + * }); + * function myFirstFunction(callback) { + * callback(null, 'one', 'two'); + * } + * function mySecondFunction(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * } + * function myLastFunction(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + */ + function waterfall (tasks, callback) { + callback = once(callback); + if (!Array.isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions')); + if (!tasks.length) return callback(); + var taskIndex = 0; + + function nextTask(args) { + var task = wrapAsync(tasks[taskIndex++]); + task(...args, onlyOnce(next)); + } + + function next(err, ...args) { + if (err === false) return + if (err || taskIndex === tasks.length) { + return callback(err, ...args); + } + nextTask(args); + } + + nextTask([]); + } + + var waterfall$1 = awaitify(waterfall); + + /** + * An "async function" in the context of Async is an asynchronous function with + * a variable number of parameters, with the final parameter being a callback. + * (`function (arg1, arg2, ..., callback) {}`) + * The final callback is of the form `callback(err, results...)`, which must be + * called once the function is completed. The callback should be called with a + * Error as its first argument to signal that an error occurred. + * Otherwise, if no error occurred, it should be called with `null` as the first + * argument, and any additional `result` arguments that may apply, to signal + * successful completion. + * The callback must be called exactly once, ideally on a later tick of the + * JavaScript event loop. + * + * This type of function is also referred to as a "Node-style async function", + * or a "continuation passing-style function" (CPS). Most of the methods of this + * library are themselves CPS/Node-style async functions, or functions that + * return CPS/Node-style async functions. + * + * Wherever we accept a Node-style async function, we also directly accept an + * [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}. + * In this case, the `async` function will not be passed a final callback + * argument, and any thrown error will be used as the `err` argument of the + * implicit callback, and the return value will be used as the `result` value. + * (i.e. a `rejected` of the returned Promise becomes the `err` callback + * argument, and a `resolved` value becomes the `result`.) + * + * Note, due to JavaScript limitations, we can only detect native `async` + * functions and not transpilied implementations. + * Your environment must have `async`/`await` support for this to work. + * (e.g. Node > v7.6, or a recent version of a modern browser). + * If you are using `async` functions through a transpiler (e.g. Babel), you + * must still wrap the function with [asyncify]{@link module:Utils.asyncify}, + * because the `async function` will be compiled to an ordinary function that + * returns a promise. + * + * @typedef {Function} AsyncFunction + * @static + */ + + var index = { + apply, + applyEach: applyEach$1, + applyEachSeries, + asyncify, + auto, + autoInject, + cargo, + cargoQueue: cargo$1, + compose, + concat: concat$1, + concatLimit: concatLimit$1, + concatSeries: concatSeries$1, + constant, + detect: detect$1, + detectLimit: detectLimit$1, + detectSeries: detectSeries$1, + dir, + doUntil, + doWhilst: doWhilst$1, + each, + eachLimit: eachLimit$2, + eachOf: eachOf$1, + eachOfLimit: eachOfLimit$2, + eachOfSeries: eachOfSeries$1, + eachSeries: eachSeries$1, + ensureAsync, + every: every$1, + everyLimit: everyLimit$1, + everySeries: everySeries$1, + filter: filter$1, + filterLimit: filterLimit$1, + filterSeries: filterSeries$1, + forever: forever$1, + groupBy, + groupByLimit: groupByLimit$1, + groupBySeries, + log, + map: map$1, + mapLimit: mapLimit$1, + mapSeries: mapSeries$1, + mapValues, + mapValuesLimit: mapValuesLimit$1, + mapValuesSeries, + memoize, + nextTick, + parallel: parallel$1, + parallelLimit, + priorityQueue, + queue: queue$1, + race: race$1, + reduce: reduce$1, + reduceRight, + reflect, + reflectAll, + reject: reject$2, + rejectLimit: rejectLimit$1, + rejectSeries: rejectSeries$1, + retry, + retryable, + seq, + series, + setImmediate: setImmediate$1, + some: some$1, + someLimit: someLimit$1, + someSeries: someSeries$1, + sortBy: sortBy$1, + timeout, + times, + timesLimit, + timesSeries, + transform, + tryEach: tryEach$1, + unmemoize, + until, + waterfall: waterfall$1, + whilst: whilst$1, + + // aliases + all: every$1, + allLimit: everyLimit$1, + allSeries: everySeries$1, + any: some$1, + anyLimit: someLimit$1, + anySeries: someSeries$1, + find: detect$1, + findLimit: detectLimit$1, + findSeries: detectSeries$1, + flatMap: concat$1, + flatMapLimit: concatLimit$1, + flatMapSeries: concatSeries$1, + forEach: each, + forEachSeries: eachSeries$1, + forEachLimit: eachLimit$2, + forEachOf: eachOf$1, + forEachOfSeries: eachOfSeries$1, + forEachOfLimit: eachOfLimit$2, + inject: reduce$1, + foldl: reduce$1, + foldr: reduceRight, + select: filter$1, + selectLimit: filterLimit$1, + selectSeries: filterSeries$1, + wrapSync: asyncify, + during: whilst$1, + doDuring: doWhilst$1 + }; + + exports.default = index; + exports.apply = apply; + exports.applyEach = applyEach$1; + exports.applyEachSeries = applyEachSeries; + exports.asyncify = asyncify; + exports.auto = auto; + exports.autoInject = autoInject; + exports.cargo = cargo; + exports.cargoQueue = cargo$1; + exports.compose = compose; + exports.concat = concat$1; + exports.concatLimit = concatLimit$1; + exports.concatSeries = concatSeries$1; + exports.constant = constant; + exports.detect = detect$1; + exports.detectLimit = detectLimit$1; + exports.detectSeries = detectSeries$1; + exports.dir = dir; + exports.doUntil = doUntil; + exports.doWhilst = doWhilst$1; + exports.each = each; + exports.eachLimit = eachLimit$2; + exports.eachOf = eachOf$1; + exports.eachOfLimit = eachOfLimit$2; + exports.eachOfSeries = eachOfSeries$1; + exports.eachSeries = eachSeries$1; + exports.ensureAsync = ensureAsync; + exports.every = every$1; + exports.everyLimit = everyLimit$1; + exports.everySeries = everySeries$1; + exports.filter = filter$1; + exports.filterLimit = filterLimit$1; + exports.filterSeries = filterSeries$1; + exports.forever = forever$1; + exports.groupBy = groupBy; + exports.groupByLimit = groupByLimit$1; + exports.groupBySeries = groupBySeries; + exports.log = log; + exports.map = map$1; + exports.mapLimit = mapLimit$1; + exports.mapSeries = mapSeries$1; + exports.mapValues = mapValues; + exports.mapValuesLimit = mapValuesLimit$1; + exports.mapValuesSeries = mapValuesSeries; + exports.memoize = memoize; + exports.nextTick = nextTick; + exports.parallel = parallel$1; + exports.parallelLimit = parallelLimit; + exports.priorityQueue = priorityQueue; + exports.queue = queue$1; + exports.race = race$1; + exports.reduce = reduce$1; + exports.reduceRight = reduceRight; + exports.reflect = reflect; + exports.reflectAll = reflectAll; + exports.reject = reject$2; + exports.rejectLimit = rejectLimit$1; + exports.rejectSeries = rejectSeries$1; + exports.retry = retry; + exports.retryable = retryable; + exports.seq = seq; + exports.series = series; + exports.setImmediate = setImmediate$1; + exports.some = some$1; + exports.someLimit = someLimit$1; + exports.someSeries = someSeries$1; + exports.sortBy = sortBy$1; + exports.timeout = timeout; + exports.times = times; + exports.timesLimit = timesLimit; + exports.timesSeries = timesSeries; + exports.transform = transform; + exports.tryEach = tryEach$1; + exports.unmemoize = unmemoize; + exports.until = until; + exports.waterfall = waterfall$1; + exports.whilst = whilst$1; + exports.all = every$1; + exports.allLimit = everyLimit$1; + exports.allSeries = everySeries$1; + exports.any = some$1; + exports.anyLimit = someLimit$1; + exports.anySeries = someSeries$1; + exports.find = detect$1; + exports.findLimit = detectLimit$1; + exports.findSeries = detectSeries$1; + exports.flatMap = concat$1; + exports.flatMapLimit = concatLimit$1; + exports.flatMapSeries = concatSeries$1; + exports.forEach = each; + exports.forEachSeries = eachSeries$1; + exports.forEachLimit = eachLimit$2; + exports.forEachOf = eachOf$1; + exports.forEachOfSeries = eachOfSeries$1; + exports.forEachOfLimit = eachOfLimit$2; + exports.inject = reduce$1; + exports.foldl = reduce$1; + exports.foldr = reduceRight; + exports.select = filter$1; + exports.selectLimit = filterLimit$1; + exports.selectSeries = filterSeries$1; + exports.wrapSync = asyncify; + exports.during = whilst$1; + exports.doDuring = doWhilst$1; + + Object.defineProperty(exports, '__esModule', { value: true }); + +}))); + + +/***/ }), + +/***/ 9165: +/***/ ((module, exports, __nccwpck_require__) => { + +var merge = __nccwpck_require__(6247) +var ffmpeg = __nccwpck_require__(1859) +var version = (__nccwpck_require__(1439)/* .version */ .i8) + +module.exports = exports = function (inputs, opts) { + return new Audioconcat(inputs, opts) +} + +exports.VERSION = version +exports.ffmpeg = ffmpeg + +function Audioconcat(inputs, opts) { + this.inputs = inputs || [] + this.opts = opts || {} +} + +Audioconcat.prototype.options = function (opts) { + merge(this.opts, opts) + return this +} + +Audioconcat.prototype.concat = function (file) { + if (file) { + this.opts.output = file + } + return concat(this.inputs, this.opts) +} + +function concat(inputs, opts) { + var filter = 'concat:' + inputs.join('|') + + var renderer = ffmpeg() + .input(filter) + .outputOptions('-acodec copy') + + var output = opts.output + if (output) { + return renderer.save(output) + } + + return renderer +} + + +/***/ }), + +/***/ 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; +}; + + +/***/ }), + +/***/ 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(' { + +module.exports = process.env.FLUENTFFMPEG_COV ? __nccwpck_require__(5607) : __nccwpck_require__(1376); + + +/***/ }), + +/***/ 2832: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +/*jshint node:true*/ + + +var fs = __nccwpck_require__(7147); +var path = __nccwpck_require__(1017); +var async = __nccwpck_require__(7888); +var utils = __nccwpck_require__(7166); + +/* + *! Capability helpers + */ + +var avCodecRegexp = /^\s*([D ])([E ])([VAS])([S ])([D ])([T ]) ([^ ]+) +(.*)$/; +var ffCodecRegexp = /^\s*([D\.])([E\.])([VAS])([I\.])([L\.])([S\.]) ([^ ]+) +(.*)$/; +var ffEncodersRegexp = /\(encoders:([^\)]+)\)/; +var ffDecodersRegexp = /\(decoders:([^\)]+)\)/; +var encodersRegexp = /^\s*([VAS\.])([F\.])([S\.])([X\.])([B\.])([D\.]) ([^ ]+) +(.*)$/; +var formatRegexp = /^\s*([D ])([E ]) ([^ ]+) +(.*)$/; +var lineBreakRegexp = /\r\n|\r|\n/; +var filterRegexp = /^(?: [T\.][S\.][C\.] )?([^ ]+) +(AA?|VV?|\|)->(AA?|VV?|\|) +(.*)$/; + +var cache = {}; + +module.exports = function(proto) { + /** + * Manually define the ffmpeg binary full path. + * + * @method FfmpegCommand#setFfmpegPath + * + * @param {String} ffmpegPath The full path to the ffmpeg binary. + * @return FfmpegCommand + */ + proto.setFfmpegPath = function(ffmpegPath) { + cache.ffmpegPath = ffmpegPath; + return this; + }; + + /** + * Manually define the ffprobe binary full path. + * + * @method FfmpegCommand#setFfprobePath + * + * @param {String} ffprobePath The full path to the ffprobe binary. + * @return FfmpegCommand + */ + proto.setFfprobePath = function(ffprobePath) { + cache.ffprobePath = ffprobePath; + return this; + }; + + /** + * Manually define the flvtool2/flvmeta binary full path. + * + * @method FfmpegCommand#setFlvtoolPath + * + * @param {String} flvtool The full path to the flvtool2 or flvmeta binary. + * @return FfmpegCommand + */ + proto.setFlvtoolPath = function(flvtool) { + cache.flvtoolPath = flvtool; + return this; + }; + + /** + * Forget executable paths + * + * (only used for testing purposes) + * + * @method FfmpegCommand#_forgetPaths + * @private + */ + proto._forgetPaths = function() { + delete cache.ffmpegPath; + delete cache.ffprobePath; + delete cache.flvtoolPath; + }; + + /** + * Check for ffmpeg availability + * + * If the FFMPEG_PATH environment variable is set, try to use it. + * If it is unset or incorrect, try to find ffmpeg in the PATH instead. + * + * @method FfmpegCommand#_getFfmpegPath + * @param {Function} callback callback with signature (err, path) + * @private + */ + proto._getFfmpegPath = function(callback) { + if ('ffmpegPath' in cache) { + return callback(null, cache.ffmpegPath); + } + + async.waterfall([ + // Try FFMPEG_PATH + function(cb) { + if (process.env.FFMPEG_PATH) { + fs.exists(process.env.FFMPEG_PATH, function(exists) { + if (exists) { + cb(null, process.env.FFMPEG_PATH); + } else { + cb(null, ''); + } + }); + } else { + cb(null, ''); + } + }, + + // Search in the PATH + function(ffmpeg, cb) { + if (ffmpeg.length) { + return cb(null, ffmpeg); + } + + utils.which('ffmpeg', function(err, ffmpeg) { + cb(err, ffmpeg); + }); + } + ], function(err, ffmpeg) { + if (err) { + callback(err); + } else { + callback(null, cache.ffmpegPath = (ffmpeg || '')); + } + }); + }; + + + /** + * Check for ffprobe availability + * + * If the FFPROBE_PATH environment variable is set, try to use it. + * If it is unset or incorrect, try to find ffprobe in the PATH instead. + * If this still fails, try to find ffprobe in the same directory as ffmpeg. + * + * @method FfmpegCommand#_getFfprobePath + * @param {Function} callback callback with signature (err, path) + * @private + */ + proto._getFfprobePath = function(callback) { + var self = this; + + if ('ffprobePath' in cache) { + return callback(null, cache.ffprobePath); + } + + async.waterfall([ + // Try FFPROBE_PATH + function(cb) { + if (process.env.FFPROBE_PATH) { + fs.exists(process.env.FFPROBE_PATH, function(exists) { + cb(null, exists ? process.env.FFPROBE_PATH : ''); + }); + } else { + cb(null, ''); + } + }, + + // Search in the PATH + function(ffprobe, cb) { + if (ffprobe.length) { + return cb(null, ffprobe); + } + + utils.which('ffprobe', function(err, ffprobe) { + cb(err, ffprobe); + }); + }, + + // Search in the same directory as ffmpeg + function(ffprobe, cb) { + if (ffprobe.length) { + return cb(null, ffprobe); + } + + self._getFfmpegPath(function(err, ffmpeg) { + if (err) { + cb(err); + } else if (ffmpeg.length) { + var name = utils.isWindows ? 'ffprobe.exe' : 'ffprobe'; + var ffprobe = path.join(path.dirname(ffmpeg), name); + fs.exists(ffprobe, function(exists) { + cb(null, exists ? ffprobe : ''); + }); + } else { + cb(null, ''); + } + }); + } + ], function(err, ffprobe) { + if (err) { + callback(err); + } else { + callback(null, cache.ffprobePath = (ffprobe || '')); + } + }); + }; + + + /** + * Check for flvtool2/flvmeta availability + * + * If the FLVTOOL2_PATH or FLVMETA_PATH environment variable are set, try to use them. + * If both are either unset or incorrect, try to find flvtool2 or flvmeta in the PATH instead. + * + * @method FfmpegCommand#_getFlvtoolPath + * @param {Function} callback callback with signature (err, path) + * @private + */ + proto._getFlvtoolPath = function(callback) { + if ('flvtoolPath' in cache) { + return callback(null, cache.flvtoolPath); + } + + async.waterfall([ + // Try FLVMETA_PATH + function(cb) { + if (process.env.FLVMETA_PATH) { + fs.exists(process.env.FLVMETA_PATH, function(exists) { + cb(null, exists ? process.env.FLVMETA_PATH : ''); + }); + } else { + cb(null, ''); + } + }, + + // Try FLVTOOL2_PATH + function(flvtool, cb) { + if (flvtool.length) { + return cb(null, flvtool); + } + + if (process.env.FLVTOOL2_PATH) { + fs.exists(process.env.FLVTOOL2_PATH, function(exists) { + cb(null, exists ? process.env.FLVTOOL2_PATH : ''); + }); + } else { + cb(null, ''); + } + }, + + // Search for flvmeta in the PATH + function(flvtool, cb) { + if (flvtool.length) { + return cb(null, flvtool); + } + + utils.which('flvmeta', function(err, flvmeta) { + cb(err, flvmeta); + }); + }, + + // Search for flvtool2 in the PATH + function(flvtool, cb) { + if (flvtool.length) { + return cb(null, flvtool); + } + + utils.which('flvtool2', function(err, flvtool2) { + cb(err, flvtool2); + }); + }, + ], function(err, flvtool) { + if (err) { + callback(err); + } else { + callback(null, cache.flvtoolPath = (flvtool || '')); + } + }); + }; + + + /** + * A callback passed to {@link FfmpegCommand#availableFilters}. + * + * @callback FfmpegCommand~filterCallback + * @param {Error|null} err error object or null if no error happened + * @param {Object} filters filter object with filter names as keys and the following + * properties for each filter: + * @param {String} filters.description filter description + * @param {String} filters.input input type, one of 'audio', 'video' and 'none' + * @param {Boolean} filters.multipleInputs whether the filter supports multiple inputs + * @param {String} filters.output output type, one of 'audio', 'video' and 'none' + * @param {Boolean} filters.multipleOutputs whether the filter supports multiple outputs + */ + + /** + * Query ffmpeg for available filters + * + * @method FfmpegCommand#availableFilters + * @category Capabilities + * @aliases getAvailableFilters + * + * @param {FfmpegCommand~filterCallback} callback callback function + */ + proto.availableFilters = + proto.getAvailableFilters = function(callback) { + if ('filters' in cache) { + return callback(null, cache.filters); + } + + this._spawnFfmpeg(['-filters'], { captureStdout: true, stdoutLines: 0 }, function (err, stdoutRing) { + if (err) { + return callback(err); + } + + var stdout = stdoutRing.get(); + var lines = stdout.split('\n'); + var data = {}; + var types = { A: 'audio', V: 'video', '|': 'none' }; + + lines.forEach(function(line) { + var match = line.match(filterRegexp); + if (match) { + data[match[1]] = { + description: match[4], + input: types[match[2].charAt(0)], + multipleInputs: match[2].length > 1, + output: types[match[3].charAt(0)], + multipleOutputs: match[3].length > 1 + }; + } + }); + + callback(null, cache.filters = data); + }); + }; + + + /** + * A callback passed to {@link FfmpegCommand#availableCodecs}. + * + * @callback FfmpegCommand~codecCallback + * @param {Error|null} err error object or null if no error happened + * @param {Object} codecs codec object with codec names as keys and the following + * properties for each codec (more properties may be available depending on the + * ffmpeg version used): + * @param {String} codecs.description codec description + * @param {Boolean} codecs.canDecode whether the codec is able to decode streams + * @param {Boolean} codecs.canEncode whether the codec is able to encode streams + */ + + /** + * Query ffmpeg for available codecs + * + * @method FfmpegCommand#availableCodecs + * @category Capabilities + * @aliases getAvailableCodecs + * + * @param {FfmpegCommand~codecCallback} callback callback function + */ + proto.availableCodecs = + proto.getAvailableCodecs = function(callback) { + if ('codecs' in cache) { + return callback(null, cache.codecs); + } + + this._spawnFfmpeg(['-codecs'], { captureStdout: true, stdoutLines: 0 }, function(err, stdoutRing) { + if (err) { + return callback(err); + } + + var stdout = stdoutRing.get(); + var lines = stdout.split(lineBreakRegexp); + var data = {}; + + lines.forEach(function(line) { + var match = line.match(avCodecRegexp); + if (match && match[7] !== '=') { + data[match[7]] = { + type: { 'V': 'video', 'A': 'audio', 'S': 'subtitle' }[match[3]], + description: match[8], + canDecode: match[1] === 'D', + canEncode: match[2] === 'E', + drawHorizBand: match[4] === 'S', + directRendering: match[5] === 'D', + weirdFrameTruncation: match[6] === 'T' + }; + } + + match = line.match(ffCodecRegexp); + if (match && match[7] !== '=') { + var codecData = data[match[7]] = { + type: { 'V': 'video', 'A': 'audio', 'S': 'subtitle' }[match[3]], + description: match[8], + canDecode: match[1] === 'D', + canEncode: match[2] === 'E', + intraFrameOnly: match[4] === 'I', + isLossy: match[5] === 'L', + isLossless: match[6] === 'S' + }; + + var encoders = codecData.description.match(ffEncodersRegexp); + encoders = encoders ? encoders[1].trim().split(' ') : []; + + var decoders = codecData.description.match(ffDecodersRegexp); + decoders = decoders ? decoders[1].trim().split(' ') : []; + + if (encoders.length || decoders.length) { + var coderData = {}; + utils.copy(codecData, coderData); + delete coderData.canEncode; + delete coderData.canDecode; + + encoders.forEach(function(name) { + data[name] = {}; + utils.copy(coderData, data[name]); + data[name].canEncode = true; + }); + + decoders.forEach(function(name) { + if (name in data) { + data[name].canDecode = true; + } else { + data[name] = {}; + utils.copy(coderData, data[name]); + data[name].canDecode = true; + } + }); + } + } + }); + + callback(null, cache.codecs = data); + }); + }; + + + /** + * A callback passed to {@link FfmpegCommand#availableEncoders}. + * + * @callback FfmpegCommand~encodersCallback + * @param {Error|null} err error object or null if no error happened + * @param {Object} encoders encoders object with encoder names as keys and the following + * properties for each encoder: + * @param {String} encoders.description codec description + * @param {Boolean} encoders.type "audio", "video" or "subtitle" + * @param {Boolean} encoders.frameMT whether the encoder is able to do frame-level multithreading + * @param {Boolean} encoders.sliceMT whether the encoder is able to do slice-level multithreading + * @param {Boolean} encoders.experimental whether the encoder is experimental + * @param {Boolean} encoders.drawHorizBand whether the encoder supports draw_horiz_band + * @param {Boolean} encoders.directRendering whether the encoder supports direct encoding method 1 + */ + + /** + * Query ffmpeg for available encoders + * + * @method FfmpegCommand#availableEncoders + * @category Capabilities + * @aliases getAvailableEncoders + * + * @param {FfmpegCommand~encodersCallback} callback callback function + */ + proto.availableEncoders = + proto.getAvailableEncoders = function(callback) { + if ('encoders' in cache) { + return callback(null, cache.encoders); + } + + this._spawnFfmpeg(['-encoders'], { captureStdout: true, stdoutLines: 0 }, function(err, stdoutRing) { + if (err) { + return callback(err); + } + + var stdout = stdoutRing.get(); + var lines = stdout.split(lineBreakRegexp); + var data = {}; + + lines.forEach(function(line) { + var match = line.match(encodersRegexp); + if (match && match[7] !== '=') { + data[match[7]] = { + type: { 'V': 'video', 'A': 'audio', 'S': 'subtitle' }[match[1]], + description: match[8], + frameMT: match[2] === 'F', + sliceMT: match[3] === 'S', + experimental: match[4] === 'X', + drawHorizBand: match[5] === 'B', + directRendering: match[6] === 'D' + }; + } + }); + + callback(null, cache.encoders = data); + }); + }; + + + /** + * A callback passed to {@link FfmpegCommand#availableFormats}. + * + * @callback FfmpegCommand~formatCallback + * @param {Error|null} err error object or null if no error happened + * @param {Object} formats format object with format names as keys and the following + * properties for each format: + * @param {String} formats.description format description + * @param {Boolean} formats.canDemux whether the format is able to demux streams from an input file + * @param {Boolean} formats.canMux whether the format is able to mux streams into an output file + */ + + /** + * Query ffmpeg for available formats + * + * @method FfmpegCommand#availableFormats + * @category Capabilities + * @aliases getAvailableFormats + * + * @param {FfmpegCommand~formatCallback} callback callback function + */ + proto.availableFormats = + proto.getAvailableFormats = function(callback) { + if ('formats' in cache) { + return callback(null, cache.formats); + } + + // Run ffmpeg -formats + this._spawnFfmpeg(['-formats'], { captureStdout: true, stdoutLines: 0 }, function (err, stdoutRing) { + if (err) { + return callback(err); + } + + // Parse output + var stdout = stdoutRing.get(); + var lines = stdout.split(lineBreakRegexp); + var data = {}; + + lines.forEach(function(line) { + var match = line.match(formatRegexp); + if (match) { + match[3].split(',').forEach(function(format) { + if (!(format in data)) { + data[format] = { + description: match[4], + canDemux: false, + canMux: false + }; + } + + if (match[1] === 'D') { + data[format].canDemux = true; + } + if (match[2] === 'E') { + data[format].canMux = true; + } + }); + } + }); + + callback(null, cache.formats = data); + }); + }; + + + /** + * Check capabilities before executing a command + * + * Checks whether all used codecs and formats are indeed available + * + * @method FfmpegCommand#_checkCapabilities + * @param {Function} callback callback with signature (err) + * @private + */ + proto._checkCapabilities = function(callback) { + var self = this; + async.waterfall([ + // Get available formats + function(cb) { + self.availableFormats(cb); + }, + + // Check whether specified formats are available + function(formats, cb) { + var unavailable; + + // Output format(s) + unavailable = self._outputs + .reduce(function(fmts, output) { + var format = output.options.find('-f', 1); + if (format) { + if (!(format[0] in formats) || !(formats[format[0]].canMux)) { + fmts.push(format); + } + } + + return fmts; + }, []); + + if (unavailable.length === 1) { + return cb(new Error('Output format ' + unavailable[0] + ' is not available')); + } else if (unavailable.length > 1) { + return cb(new Error('Output formats ' + unavailable.join(', ') + ' are not available')); + } + + // Input format(s) + unavailable = self._inputs + .reduce(function(fmts, input) { + var format = input.options.find('-f', 1); + if (format) { + if (!(format[0] in formats) || !(formats[format[0]].canDemux)) { + fmts.push(format[0]); + } + } + + return fmts; + }, []); + + if (unavailable.length === 1) { + return cb(new Error('Input format ' + unavailable[0] + ' is not available')); + } else if (unavailable.length > 1) { + return cb(new Error('Input formats ' + unavailable.join(', ') + ' are not available')); + } + + cb(); + }, + + // Get available codecs + function(cb) { + self.availableEncoders(cb); + }, + + // Check whether specified codecs are available and add strict experimental options if needed + function(encoders, cb) { + var unavailable; + + // Audio codec(s) + unavailable = self._outputs.reduce(function(cdcs, output) { + var acodec = output.audio.find('-acodec', 1); + if (acodec && acodec[0] !== 'copy') { + if (!(acodec[0] in encoders) || encoders[acodec[0]].type !== 'audio') { + cdcs.push(acodec[0]); + } + } + + return cdcs; + }, []); + + if (unavailable.length === 1) { + return cb(new Error('Audio codec ' + unavailable[0] + ' is not available')); + } else if (unavailable.length > 1) { + return cb(new Error('Audio codecs ' + unavailable.join(', ') + ' are not available')); + } + + // Video codec(s) + unavailable = self._outputs.reduce(function(cdcs, output) { + var vcodec = output.video.find('-vcodec', 1); + if (vcodec && vcodec[0] !== 'copy') { + if (!(vcodec[0] in encoders) || encoders[vcodec[0]].type !== 'video') { + cdcs.push(vcodec[0]); + } + } + + return cdcs; + }, []); + + if (unavailable.length === 1) { + return cb(new Error('Video codec ' + unavailable[0] + ' is not available')); + } else if (unavailable.length > 1) { + return cb(new Error('Video codecs ' + unavailable.join(', ') + ' are not available')); + } + + cb(); + } + ], callback); + }; +}; + + +/***/ }), + +/***/ 960: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +/*jshint node:true, laxcomma:true*/ + + +var spawn = (__nccwpck_require__(2081).spawn); + + +function legacyTag(key) { return key.match(/^TAG:/); } +function legacyDisposition(key) { return key.match(/^DISPOSITION:/); } + +function parseFfprobeOutput(out) { + var lines = out.split(/\r\n|\r|\n/); + + lines = lines.filter(function (line) { + return line.length > 0; + }); + + var data = { + streams: [], + format: {}, + chapters: [] + }; + + function parseBlock(name) { + var data = {}; + + var line = lines.shift(); + while (typeof line !== 'undefined') { + if (line.toLowerCase() == '[/'+name+']') { + return data; + } else if (line.match(/^\[/)) { + line = lines.shift(); + continue; + } + + var kv = line.match(/^([^=]+)=(.*)$/); + if (kv) { + if (!(kv[1].match(/^TAG:/)) && kv[2].match(/^[0-9]+(\.[0-9]+)?$/)) { + data[kv[1]] = Number(kv[2]); + } else { + data[kv[1]] = kv[2]; + } + } + + line = lines.shift(); + } + + return data; + } + + var line = lines.shift(); + while (typeof line !== 'undefined') { + if (line.match(/^\[stream/i)) { + var stream = parseBlock('stream'); + data.streams.push(stream); + } else if (line.match(/^\[chapter/i)) { + var chapter = parseBlock('chapter'); + data.chapters.push(chapter); + } else if (line.toLowerCase() === '[format]') { + data.format = parseBlock('format'); + } + + line = lines.shift(); + } + + return data; +} + + + +module.exports = function(proto) { + /** + * A callback passed to the {@link FfmpegCommand#ffprobe} method. + * + * @callback FfmpegCommand~ffprobeCallback + * + * @param {Error|null} err error object or null if no error happened + * @param {Object} ffprobeData ffprobe output data; this object + * has the same format as what the following command returns: + * + * `ffprobe -print_format json -show_streams -show_format INPUTFILE` + * @param {Array} ffprobeData.streams stream information + * @param {Object} ffprobeData.format format information + */ + + /** + * Run ffprobe on last specified input + * + * @method FfmpegCommand#ffprobe + * @category Metadata + * + * @param {?Number} [index] 0-based index of input to probe (defaults to last input) + * @param {?String[]} [options] array of output options to return + * @param {FfmpegCommand~ffprobeCallback} callback callback function + * + */ + proto.ffprobe = function() { + var input, index = null, options = [], callback; + + // the last argument should be the callback + var callback = arguments[arguments.length - 1]; + + var ended = false + function handleCallback(err, data) { + if (!ended) { + ended = true; + callback(err, data); + } + }; + + // map the arguments to the correct variable names + switch (arguments.length) { + case 3: + index = arguments[0]; + options = arguments[1]; + break; + case 2: + if (typeof arguments[0] === 'number') { + index = arguments[0]; + } else if (Array.isArray(arguments[0])) { + options = arguments[0]; + } + break; + } + + + if (index === null) { + if (!this._currentInput) { + return handleCallback(new Error('No input specified')); + } + + input = this._currentInput; + } else { + input = this._inputs[index]; + + if (!input) { + return handleCallback(new Error('Invalid input index')); + } + } + + // Find ffprobe + this._getFfprobePath(function(err, path) { + if (err) { + return handleCallback(err); + } else if (!path) { + return handleCallback(new Error('Cannot find ffprobe')); + } + + var stdout = ''; + var stdoutClosed = false; + var stderr = ''; + var stderrClosed = false; + + // Spawn ffprobe + var src = input.isStream ? 'pipe:0' : input.source; + var ffprobe = spawn(path, ['-show_streams', '-show_format'].concat(options, src)); + + if (input.isStream) { + // Skip errors on stdin. These get thrown when ffprobe is complete and + // there seems to be no way hook in and close stdin before it throws. + ffprobe.stdin.on('error', function(err) { + if (['ECONNRESET', 'EPIPE'].indexOf(err.code) >= 0) { return; } + handleCallback(err); + }); + + // Once ffprobe's input stream closes, we need no more data from the + // input + ffprobe.stdin.on('close', function() { + input.source.pause(); + input.source.unpipe(ffprobe.stdin); + }); + + input.source.pipe(ffprobe.stdin); + } + + ffprobe.on('error', callback); + + // Ensure we wait for captured streams to end before calling callback + var exitError = null; + function handleExit(err) { + if (err) { + exitError = err; + } + + if (processExited && stdoutClosed && stderrClosed) { + if (exitError) { + if (stderr) { + exitError.message += '\n' + stderr; + } + + return handleCallback(exitError); + } + + // Process output + var data = parseFfprobeOutput(stdout); + + // Handle legacy output with "TAG:x" and "DISPOSITION:x" keys + [data.format].concat(data.streams).forEach(function(target) { + if (target) { + var legacyTagKeys = Object.keys(target).filter(legacyTag); + + if (legacyTagKeys.length) { + target.tags = target.tags || {}; + + legacyTagKeys.forEach(function(tagKey) { + target.tags[tagKey.substr(4)] = target[tagKey]; + delete target[tagKey]; + }); + } + + var legacyDispositionKeys = Object.keys(target).filter(legacyDisposition); + + if (legacyDispositionKeys.length) { + target.disposition = target.disposition || {}; + + legacyDispositionKeys.forEach(function(dispositionKey) { + target.disposition[dispositionKey.substr(12)] = target[dispositionKey]; + delete target[dispositionKey]; + }); + } + } + }); + + handleCallback(null, data); + } + } + + // Handle ffprobe exit + var processExited = false; + ffprobe.on('exit', function(code, signal) { + processExited = true; + + if (code) { + handleExit(new Error('ffprobe exited with code ' + code)); + } else if (signal) { + handleExit(new Error('ffprobe was killed with signal ' + signal)); + } else { + handleExit(); + } + }); + + // Handle stdout/stderr streams + ffprobe.stdout.on('data', function(data) { + stdout += data; + }); + + ffprobe.stdout.on('close', function() { + stdoutClosed = true; + handleExit(); + }); + + ffprobe.stderr.on('data', function(data) { + stderr += data; + }); + + ffprobe.stderr.on('close', function() { + stderrClosed = true; + handleExit(); + }); + }); + }; +}; + + +/***/ }), + +/***/ 1376: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +/*jshint node:true*/ + + +var path = __nccwpck_require__(1017); +var util = __nccwpck_require__(3837); +var EventEmitter = (__nccwpck_require__(2361).EventEmitter); + +var utils = __nccwpck_require__(7166); +var ARGLISTS = (/* unused pure expression or super */ null && (['_global', '_audio', '_audioFilters', '_video', '_videoFilters', '_sizeFilters', '_complexFilters'])); + + +/** + * Create an ffmpeg command + * + * Can be called with or without the 'new' operator, and the 'input' parameter + * may be specified as 'options.source' instead (or passed later with the + * addInput method). + * + * @constructor + * @param {String|ReadableStream} [input] input file path or readable stream + * @param {Object} [options] command options + * @param {Object} [options.logger=] logger object with 'error', 'warning', 'info' and 'debug' methods + * @param {Number} [options.niceness=0] ffmpeg process niceness, ignored on Windows + * @param {Number} [options.priority=0] alias for `niceness` + * @param {String} [options.presets="fluent-ffmpeg/lib/presets"] directory to load presets from + * @param {String} [options.preset="fluent-ffmpeg/lib/presets"] alias for `presets` + * @param {String} [options.stdoutLines=100] maximum lines of ffmpeg output to keep in memory, use 0 for unlimited + * @param {Number} [options.timeout=] ffmpeg processing timeout in seconds + * @param {String|ReadableStream} [options.source=] alias for the `input` parameter + */ +function FfmpegCommand(input, options) { + // Make 'new' optional + if (!(this instanceof FfmpegCommand)) { + return new FfmpegCommand(input, options); + } + + EventEmitter.call(this); + + if (typeof input === 'object' && !('readable' in input)) { + // Options object passed directly + options = input; + } else { + // Input passed first + options = options || {}; + options.source = input; + } + + // Add input if present + this._inputs = []; + if (options.source) { + this.input(options.source); + } + + // Add target-less output for backwards compatibility + this._outputs = []; + this.output(); + + // Create argument lists + var self = this; + ['_global', '_complexFilters'].forEach(function(prop) { + self[prop] = utils.args(); + }); + + // Set default option values + options.stdoutLines = 'stdoutLines' in options ? options.stdoutLines : 100; + options.presets = options.presets || options.preset || __nccwpck_require__.ab + "presets"; + options.niceness = options.niceness || options.priority || 0; + + // Save options + this.options = options; + + // Setup logger + this.logger = options.logger || { + debug: function() {}, + info: function() {}, + warn: function() {}, + error: function() {} + }; +} +util.inherits(FfmpegCommand, EventEmitter); +module.exports = FfmpegCommand; + + +/** + * Clone an ffmpeg command + * + * This method is useful when you want to process the same input multiple times. + * It returns a new FfmpegCommand instance with the exact same options. + * + * All options set _after_ the clone() call will only be applied to the instance + * it has been called on. + * + * @example + * var command = ffmpeg('/path/to/source.avi') + * .audioCodec('libfaac') + * .videoCodec('libx264') + * .format('mp4'); + * + * command.clone() + * .size('320x200') + * .save('/path/to/output-small.mp4'); + * + * command.clone() + * .size('640x400') + * .save('/path/to/output-medium.mp4'); + * + * command.save('/path/to/output-original-size.mp4'); + * + * @method FfmpegCommand#clone + * @return FfmpegCommand + */ +FfmpegCommand.prototype.clone = function() { + var clone = new FfmpegCommand(); + var self = this; + + // Clone options and logger + clone.options = this.options; + clone.logger = this.logger; + + // Clone inputs + clone._inputs = this._inputs.map(function(input) { + return { + source: input.source, + options: input.options.clone() + }; + }); + + // Create first output + if ('target' in this._outputs[0]) { + // We have outputs set, don't clone them and create first output + clone._outputs = []; + clone.output(); + } else { + // No outputs set, clone first output options + clone._outputs = [ + clone._currentOutput = { + flags: {} + } + ]; + + ['audio', 'audioFilters', 'video', 'videoFilters', 'sizeFilters', 'options'].forEach(function(key) { + clone._currentOutput[key] = self._currentOutput[key].clone(); + }); + + if (this._currentOutput.sizeData) { + clone._currentOutput.sizeData = {}; + utils.copy(this._currentOutput.sizeData, clone._currentOutput.sizeData); + } + + utils.copy(this._currentOutput.flags, clone._currentOutput.flags); + } + + // Clone argument lists + ['_global', '_complexFilters'].forEach(function(prop) { + clone[prop] = self[prop].clone(); + }); + + return clone; +}; + + +/* Add methods from options submodules */ + +__nccwpck_require__(8781)(FfmpegCommand.prototype); +__nccwpck_require__(8117)(FfmpegCommand.prototype); +__nccwpck_require__(7215)(FfmpegCommand.prototype); +__nccwpck_require__(4773)(FfmpegCommand.prototype); +__nccwpck_require__(6488)(FfmpegCommand.prototype); +__nccwpck_require__(1117)(FfmpegCommand.prototype); +__nccwpck_require__(81)(FfmpegCommand.prototype); + + +/* Add processor methods */ + +__nccwpck_require__(981)(FfmpegCommand.prototype); + + +/* Add capabilities methods */ + +__nccwpck_require__(2832)(FfmpegCommand.prototype); + +FfmpegCommand.setFfmpegPath = function(path) { + (new FfmpegCommand()).setFfmpegPath(path); +}; + +FfmpegCommand.setFfprobePath = function(path) { + (new FfmpegCommand()).setFfprobePath(path); +}; + +FfmpegCommand.setFlvtoolPath = function(path) { + (new FfmpegCommand()).setFlvtoolPath(path); +}; + +FfmpegCommand.availableFilters = +FfmpegCommand.getAvailableFilters = function(callback) { + (new FfmpegCommand()).availableFilters(callback); +}; + +FfmpegCommand.availableCodecs = +FfmpegCommand.getAvailableCodecs = function(callback) { + (new FfmpegCommand()).availableCodecs(callback); +}; + +FfmpegCommand.availableFormats = +FfmpegCommand.getAvailableFormats = function(callback) { + (new FfmpegCommand()).availableFormats(callback); +}; + +FfmpegCommand.availableEncoders = +FfmpegCommand.getAvailableEncoders = function(callback) { + (new FfmpegCommand()).availableEncoders(callback); +}; + + +/* Add ffprobe methods */ + +__nccwpck_require__(960)(FfmpegCommand.prototype); + +FfmpegCommand.ffprobe = function(file) { + var instance = new FfmpegCommand(file); + instance.ffprobe.apply(instance, Array.prototype.slice.call(arguments, 1)); +}; + +/* Add processing recipes */ + +__nccwpck_require__(9341)(FfmpegCommand.prototype); + + +/***/ }), + +/***/ 8117: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +/*jshint node:true*/ + + +var utils = __nccwpck_require__(7166); + + +/* + *! Audio-related methods + */ + +module.exports = function(proto) { + /** + * Disable audio in the output + * + * @method FfmpegCommand#noAudio + * @category Audio + * @aliases withNoAudio + * @return FfmpegCommand + */ + proto.withNoAudio = + proto.noAudio = function() { + this._currentOutput.audio.clear(); + this._currentOutput.audioFilters.clear(); + this._currentOutput.audio('-an'); + + return this; + }; + + + /** + * Specify audio codec + * + * @method FfmpegCommand#audioCodec + * @category Audio + * @aliases withAudioCodec + * + * @param {String} codec audio codec name + * @return FfmpegCommand + */ + proto.withAudioCodec = + proto.audioCodec = function(codec) { + this._currentOutput.audio('-acodec', codec); + + return this; + }; + + + /** + * Specify audio bitrate + * + * @method FfmpegCommand#audioBitrate + * @category Audio + * @aliases withAudioBitrate + * + * @param {String|Number} bitrate audio bitrate in kbps (with an optional 'k' suffix) + * @return FfmpegCommand + */ + proto.withAudioBitrate = + proto.audioBitrate = function(bitrate) { + this._currentOutput.audio('-b:a', ('' + bitrate).replace(/k?$/, 'k')); + return this; + }; + + + /** + * Specify audio channel count + * + * @method FfmpegCommand#audioChannels + * @category Audio + * @aliases withAudioChannels + * + * @param {Number} channels channel count + * @return FfmpegCommand + */ + proto.withAudioChannels = + proto.audioChannels = function(channels) { + this._currentOutput.audio('-ac', channels); + return this; + }; + + + /** + * Specify audio frequency + * + * @method FfmpegCommand#audioFrequency + * @category Audio + * @aliases withAudioFrequency + * + * @param {Number} freq audio frequency in Hz + * @return FfmpegCommand + */ + proto.withAudioFrequency = + proto.audioFrequency = function(freq) { + this._currentOutput.audio('-ar', freq); + return this; + }; + + + /** + * Specify audio quality + * + * @method FfmpegCommand#audioQuality + * @category Audio + * @aliases withAudioQuality + * + * @param {Number} quality audio quality factor + * @return FfmpegCommand + */ + proto.withAudioQuality = + proto.audioQuality = function(quality) { + this._currentOutput.audio('-aq', quality); + return this; + }; + + + /** + * Specify custom audio filter(s) + * + * Can be called both with one or many filters, or a filter array. + * + * @example + * command.audioFilters('filter1'); + * + * @example + * command.audioFilters('filter1', 'filter2=param1=value1:param2=value2'); + * + * @example + * command.audioFilters(['filter1', 'filter2']); + * + * @example + * command.audioFilters([ + * { + * filter: 'filter1' + * }, + * { + * filter: 'filter2', + * options: 'param=value:param=value' + * } + * ]); + * + * @example + * command.audioFilters( + * { + * filter: 'filter1', + * options: ['value1', 'value2'] + * }, + * { + * filter: 'filter2', + * options: { param1: 'value1', param2: 'value2' } + * } + * ); + * + * @method FfmpegCommand#audioFilters + * @aliases withAudioFilter,withAudioFilters,audioFilter + * @category Audio + * + * @param {...String|String[]|Object[]} filters audio filter strings, string array or + * filter specification array, each with the following properties: + * @param {String} filters.filter filter name + * @param {String|String[]|Object} [filters.options] filter option string, array, or object + * @return FfmpegCommand + */ + proto.withAudioFilter = + proto.withAudioFilters = + proto.audioFilter = + proto.audioFilters = function(filters) { + if (arguments.length > 1) { + filters = [].slice.call(arguments); + } + + if (!Array.isArray(filters)) { + filters = [filters]; + } + + this._currentOutput.audioFilters(utils.makeFilterStrings(filters)); + return this; + }; +}; + + +/***/ }), + +/***/ 1117: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +/*jshint node:true*/ + + +var utils = __nccwpck_require__(7166); + + +/* + *! Custom options methods + */ + +module.exports = function(proto) { + /** + * Add custom input option(s) + * + * When passing a single string or an array, each string containing two + * words is split (eg. inputOptions('-option value') is supported) for + * compatibility reasons. This is not the case when passing more than + * one argument. + * + * @example + * command.inputOptions('option1'); + * + * @example + * command.inputOptions('option1', 'option2'); + * + * @example + * command.inputOptions(['option1', 'option2']); + * + * @method FfmpegCommand#inputOptions + * @category Custom options + * @aliases addInputOption,addInputOptions,withInputOption,withInputOptions,inputOption + * + * @param {...String} options option string(s) or string array + * @return FfmpegCommand + */ + proto.addInputOption = + proto.addInputOptions = + proto.withInputOption = + proto.withInputOptions = + proto.inputOption = + proto.inputOptions = function(options) { + if (!this._currentInput) { + throw new Error('No input specified'); + } + + var doSplit = true; + + if (arguments.length > 1) { + options = [].slice.call(arguments); + doSplit = false; + } + + if (!Array.isArray(options)) { + options = [options]; + } + + this._currentInput.options(options.reduce(function(options, option) { + var split = String(option).split(' '); + + if (doSplit && split.length === 2) { + options.push(split[0], split[1]); + } else { + options.push(option); + } + + return options; + }, [])); + return this; + }; + + + /** + * Add custom output option(s) + * + * @example + * command.outputOptions('option1'); + * + * @example + * command.outputOptions('option1', 'option2'); + * + * @example + * command.outputOptions(['option1', 'option2']); + * + * @method FfmpegCommand#outputOptions + * @category Custom options + * @aliases addOutputOption,addOutputOptions,addOption,addOptions,withOutputOption,withOutputOptions,withOption,withOptions,outputOption + * + * @param {...String} options option string(s) or string array + * @return FfmpegCommand + */ + proto.addOutputOption = + proto.addOutputOptions = + proto.addOption = + proto.addOptions = + proto.withOutputOption = + proto.withOutputOptions = + proto.withOption = + proto.withOptions = + proto.outputOption = + proto.outputOptions = function(options) { + var doSplit = true; + + if (arguments.length > 1) { + options = [].slice.call(arguments); + doSplit = false; + } + + if (!Array.isArray(options)) { + options = [options]; + } + + this._currentOutput.options(options.reduce(function(options, option) { + var split = String(option).split(' '); + + if (doSplit && split.length === 2) { + options.push(split[0], split[1]); + } else { + options.push(option); + } + + return options; + }, [])); + return this; + }; + + + /** + * Specify a complex filtergraph + * + * Calling this method will override any previously set filtergraph, but you can set + * as many filters as needed in one call. + * + * @example Overlay an image over a video (using a filtergraph string) + * ffmpeg() + * .input('video.avi') + * .input('image.png') + * .complexFilter('[0:v][1:v]overlay[out]', ['out']); + * + * @example Overlay an image over a video (using a filter array) + * ffmpeg() + * .input('video.avi') + * .input('image.png') + * .complexFilter([{ + * filter: 'overlay', + * inputs: ['0:v', '1:v'], + * outputs: ['out'] + * }], ['out']); + * + * @example Split video into RGB channels and output a 3x1 video with channels side to side + * ffmpeg() + * .input('video.avi') + * .complexFilter([ + * // Duplicate video stream 3 times into streams a, b, and c + * { filter: 'split', options: '3', outputs: ['a', 'b', 'c'] }, + * + * // Create stream 'red' by cancelling green and blue channels from stream 'a' + * { filter: 'lutrgb', options: { g: 0, b: 0 }, inputs: 'a', outputs: 'red' }, + * + * // Create stream 'green' by cancelling red and blue channels from stream 'b' + * { filter: 'lutrgb', options: { r: 0, b: 0 }, inputs: 'b', outputs: 'green' }, + * + * // Create stream 'blue' by cancelling red and green channels from stream 'c' + * { filter: 'lutrgb', options: { r: 0, g: 0 }, inputs: 'c', outputs: 'blue' }, + * + * // Pad stream 'red' to 3x width, keeping the video on the left, and name output 'padded' + * { filter: 'pad', options: { w: 'iw*3', h: 'ih' }, inputs: 'red', outputs: 'padded' }, + * + * // Overlay 'green' onto 'padded', moving it to the center, and name output 'redgreen' + * { filter: 'overlay', options: { x: 'w', y: 0 }, inputs: ['padded', 'green'], outputs: 'redgreen'}, + * + * // Overlay 'blue' onto 'redgreen', moving it to the right + * { filter: 'overlay', options: { x: '2*w', y: 0 }, inputs: ['redgreen', 'blue']}, + * ]); + * + * @method FfmpegCommand#complexFilter + * @category Custom options + * @aliases filterGraph + * + * @param {String|Array} spec filtergraph string or array of filter specification + * objects, each having the following properties: + * @param {String} spec.filter filter name + * @param {String|Array} [spec.inputs] (array of) input stream specifier(s) for the filter, + * defaults to ffmpeg automatically choosing the first unused matching streams + * @param {String|Array} [spec.outputs] (array of) output stream specifier(s) for the filter, + * defaults to ffmpeg automatically assigning the output to the output file + * @param {Object|String|Array} [spec.options] filter options, can be omitted to not set any options + * @param {Array} [map] (array of) stream specifier(s) from the graph to include in + * ffmpeg output, defaults to ffmpeg automatically choosing the first matching streams. + * @return FfmpegCommand + */ + proto.filterGraph = + proto.complexFilter = function(spec, map) { + this._complexFilters.clear(); + + if (!Array.isArray(spec)) { + spec = [spec]; + } + + this._complexFilters('-filter_complex', utils.makeFilterStrings(spec).join(';')); + + if (Array.isArray(map)) { + var self = this; + map.forEach(function(streamSpec) { + self._complexFilters('-map', streamSpec.replace(utils.streamRegexp, '[$1]')); + }); + } else if (typeof map === 'string') { + this._complexFilters('-map', map.replace(utils.streamRegexp, '[$1]')); + } + + return this; + }; +}; + + +/***/ }), + +/***/ 8781: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +/*jshint node:true*/ + + +var utils = __nccwpck_require__(7166); + +/* + *! Input-related methods + */ + +module.exports = function(proto) { + /** + * Add an input to command + * + * Also switches "current input", that is the input that will be affected + * by subsequent input-related methods. + * + * Note: only one stream input is supported for now. + * + * @method FfmpegCommand#input + * @category Input + * @aliases mergeAdd,addInput + * + * @param {String|Readable} source input file path or readable stream + * @return FfmpegCommand + */ + proto.mergeAdd = + proto.addInput = + proto.input = function(source) { + var isFile = false; + var isStream = false; + + if (typeof source !== 'string') { + if (!('readable' in source) || !(source.readable)) { + throw new Error('Invalid input'); + } + + var hasInputStream = this._inputs.some(function(input) { + return input.isStream; + }); + + if (hasInputStream) { + throw new Error('Only one input stream is supported'); + } + + isStream = true; + source.pause(); + } else { + var protocol = source.match(/^([a-z]{2,}):/i); + isFile = !protocol || protocol[0] === 'file'; + } + + this._inputs.push(this._currentInput = { + source: source, + isFile: isFile, + isStream: isStream, + options: utils.args() + }); + + return this; + }; + + + /** + * Specify input format for the last specified input + * + * @method FfmpegCommand#inputFormat + * @category Input + * @aliases withInputFormat,fromFormat + * + * @param {String} format input format + * @return FfmpegCommand + */ + proto.withInputFormat = + proto.inputFormat = + proto.fromFormat = function(format) { + if (!this._currentInput) { + throw new Error('No input specified'); + } + + this._currentInput.options('-f', format); + return this; + }; + + + /** + * Specify input FPS for the last specified input + * (only valid for raw video formats) + * + * @method FfmpegCommand#inputFps + * @category Input + * @aliases withInputFps,withInputFPS,withFpsInput,withFPSInput,inputFPS,inputFps,fpsInput + * + * @param {Number} fps input FPS + * @return FfmpegCommand + */ + proto.withInputFps = + proto.withInputFPS = + proto.withFpsInput = + proto.withFPSInput = + proto.inputFPS = + proto.inputFps = + proto.fpsInput = + proto.FPSInput = function(fps) { + if (!this._currentInput) { + throw new Error('No input specified'); + } + + this._currentInput.options('-r', fps); + return this; + }; + + + /** + * Use native framerate for the last specified input + * + * @method FfmpegCommand#native + * @category Input + * @aliases nativeFramerate,withNativeFramerate + * + * @return FfmmegCommand + */ + proto.nativeFramerate = + proto.withNativeFramerate = + proto.native = function() { + if (!this._currentInput) { + throw new Error('No input specified'); + } + + this._currentInput.options('-re'); + return this; + }; + + + /** + * Specify input seek time for the last specified input + * + * @method FfmpegCommand#seekInput + * @category Input + * @aliases setStartTime,seekTo + * + * @param {String|Number} seek seek time in seconds or as a '[hh:[mm:]]ss[.xxx]' string + * @return FfmpegCommand + */ + proto.setStartTime = + proto.seekInput = function(seek) { + if (!this._currentInput) { + throw new Error('No input specified'); + } + + this._currentInput.options('-ss', seek); + + return this; + }; + + + /** + * Loop over the last specified input + * + * @method FfmpegCommand#loop + * @category Input + * + * @param {String|Number} [duration] loop duration in seconds or as a '[[hh:]mm:]ss[.xxx]' string + * @return FfmpegCommand + */ + proto.loop = function(duration) { + if (!this._currentInput) { + throw new Error('No input specified'); + } + + this._currentInput.options('-loop', '1'); + + if (typeof duration !== 'undefined') { + this.duration(duration); + } + + return this; + }; +}; + + +/***/ }), + +/***/ 81: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +/*jshint node:true*/ + + +var path = __nccwpck_require__(1017); + +/* + *! Miscellaneous methods + */ + +module.exports = function(proto) { + /** + * Use preset + * + * @method FfmpegCommand#preset + * @category Miscellaneous + * @aliases usingPreset + * + * @param {String|Function} preset preset name or preset function + */ + proto.usingPreset = + proto.preset = function(preset) { + if (typeof preset === 'function') { + preset(this); + } else { + try { + var modulePath = path.join(this.options.presets, preset); + var module = require(modulePath); + + if (typeof module.load === 'function') { + module.load(this); + } else { + throw new Error('preset ' + modulePath + ' has no load() function'); + } + } catch (err) { + throw new Error('preset ' + modulePath + ' could not be loaded: ' + err.message); + } + } + + return this; + }; +}; + + +/***/ }), + +/***/ 6488: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +/*jshint node:true*/ + + +var utils = __nccwpck_require__(7166); + + +/* + *! Output-related methods + */ + +module.exports = function(proto) { + /** + * Add output + * + * @method FfmpegCommand#output + * @category Output + * @aliases addOutput + * + * @param {String|Writable} target target file path or writable stream + * @param {Object} [pipeopts={}] pipe options (only applies to streams) + * @return FfmpegCommand + */ + proto.addOutput = + proto.output = function(target, pipeopts) { + var isFile = false; + + if (!target && this._currentOutput) { + // No target is only allowed when called from constructor + throw new Error('Invalid output'); + } + + if (target && typeof target !== 'string') { + if (!('writable' in target) || !(target.writable)) { + throw new Error('Invalid output'); + } + } else if (typeof target === 'string') { + var protocol = target.match(/^([a-z]{2,}):/i); + isFile = !protocol || protocol[0] === 'file'; + } + + if (target && !('target' in this._currentOutput)) { + // For backwards compatibility, set target for first output + this._currentOutput.target = target; + this._currentOutput.isFile = isFile; + this._currentOutput.pipeopts = pipeopts || {}; + } else { + if (target && typeof target !== 'string') { + var hasOutputStream = this._outputs.some(function(output) { + return typeof output.target !== 'string'; + }); + + if (hasOutputStream) { + throw new Error('Only one output stream is supported'); + } + } + + this._outputs.push(this._currentOutput = { + target: target, + isFile: isFile, + flags: {}, + pipeopts: pipeopts || {} + }); + + var self = this; + ['audio', 'audioFilters', 'video', 'videoFilters', 'sizeFilters', 'options'].forEach(function(key) { + self._currentOutput[key] = utils.args(); + }); + + if (!target) { + // Call from constructor: remove target key + delete this._currentOutput.target; + } + } + + return this; + }; + + + /** + * Specify output seek time + * + * @method FfmpegCommand#seek + * @category Input + * @aliases seekOutput + * + * @param {String|Number} seek seek time in seconds or as a '[hh:[mm:]]ss[.xxx]' string + * @return FfmpegCommand + */ + proto.seekOutput = + proto.seek = function(seek) { + this._currentOutput.options('-ss', seek); + return this; + }; + + + /** + * Set output duration + * + * @method FfmpegCommand#duration + * @category Output + * @aliases withDuration,setDuration + * + * @param {String|Number} duration duration in seconds or as a '[[hh:]mm:]ss[.xxx]' string + * @return FfmpegCommand + */ + proto.withDuration = + proto.setDuration = + proto.duration = function(duration) { + this._currentOutput.options('-t', duration); + return this; + }; + + + /** + * Set output format + * + * @method FfmpegCommand#format + * @category Output + * @aliases toFormat,withOutputFormat,outputFormat + * + * @param {String} format output format name + * @return FfmpegCommand + */ + proto.toFormat = + proto.withOutputFormat = + proto.outputFormat = + proto.format = function(format) { + this._currentOutput.options('-f', format); + return this; + }; + + + /** + * Add stream mapping to output + * + * @method FfmpegCommand#map + * @category Output + * + * @param {String} spec stream specification string, with optional square brackets + * @return FfmpegCommand + */ + proto.map = function(spec) { + this._currentOutput.options('-map', spec.replace(utils.streamRegexp, '[$1]')); + return this; + }; + + + /** + * Run flvtool2/flvmeta on output + * + * @method FfmpegCommand#flvmeta + * @category Output + * @aliases updateFlvMetadata + * + * @return FfmpegCommand + */ + proto.updateFlvMetadata = + proto.flvmeta = function() { + this._currentOutput.flags.flvmeta = true; + return this; + }; +}; + + +/***/ }), + +/***/ 7215: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +/*jshint node:true*/ + + +var utils = __nccwpck_require__(7166); + + +/* + *! Video-related methods + */ + +module.exports = function(proto) { + /** + * Disable video in the output + * + * @method FfmpegCommand#noVideo + * @category Video + * @aliases withNoVideo + * + * @return FfmpegCommand + */ + proto.withNoVideo = + proto.noVideo = function() { + this._currentOutput.video.clear(); + this._currentOutput.videoFilters.clear(); + this._currentOutput.video('-vn'); + + return this; + }; + + + /** + * Specify video codec + * + * @method FfmpegCommand#videoCodec + * @category Video + * @aliases withVideoCodec + * + * @param {String} codec video codec name + * @return FfmpegCommand + */ + proto.withVideoCodec = + proto.videoCodec = function(codec) { + this._currentOutput.video('-vcodec', codec); + return this; + }; + + + /** + * Specify video bitrate + * + * @method FfmpegCommand#videoBitrate + * @category Video + * @aliases withVideoBitrate + * + * @param {String|Number} bitrate video bitrate in kbps (with an optional 'k' suffix) + * @param {Boolean} [constant=false] enforce constant bitrate + * @return FfmpegCommand + */ + proto.withVideoBitrate = + proto.videoBitrate = function(bitrate, constant) { + bitrate = ('' + bitrate).replace(/k?$/, 'k'); + + this._currentOutput.video('-b:v', bitrate); + if (constant) { + this._currentOutput.video( + '-maxrate', bitrate, + '-minrate', bitrate, + '-bufsize', '3M' + ); + } + + return this; + }; + + + /** + * Specify custom video filter(s) + * + * Can be called both with one or many filters, or a filter array. + * + * @example + * command.videoFilters('filter1'); + * + * @example + * command.videoFilters('filter1', 'filter2=param1=value1:param2=value2'); + * + * @example + * command.videoFilters(['filter1', 'filter2']); + * + * @example + * command.videoFilters([ + * { + * filter: 'filter1' + * }, + * { + * filter: 'filter2', + * options: 'param=value:param=value' + * } + * ]); + * + * @example + * command.videoFilters( + * { + * filter: 'filter1', + * options: ['value1', 'value2'] + * }, + * { + * filter: 'filter2', + * options: { param1: 'value1', param2: 'value2' } + * } + * ); + * + * @method FfmpegCommand#videoFilters + * @category Video + * @aliases withVideoFilter,withVideoFilters,videoFilter + * + * @param {...String|String[]|Object[]} filters video filter strings, string array or + * filter specification array, each with the following properties: + * @param {String} filters.filter filter name + * @param {String|String[]|Object} [filters.options] filter option string, array, or object + * @return FfmpegCommand + */ + proto.withVideoFilter = + proto.withVideoFilters = + proto.videoFilter = + proto.videoFilters = function(filters) { + if (arguments.length > 1) { + filters = [].slice.call(arguments); + } + + if (!Array.isArray(filters)) { + filters = [filters]; + } + + this._currentOutput.videoFilters(utils.makeFilterStrings(filters)); + + return this; + }; + + + /** + * Specify output FPS + * + * @method FfmpegCommand#fps + * @category Video + * @aliases withOutputFps,withOutputFPS,withFpsOutput,withFPSOutput,withFps,withFPS,outputFPS,outputFps,fpsOutput,FPSOutput,FPS + * + * @param {Number} fps output FPS + * @return FfmpegCommand + */ + proto.withOutputFps = + proto.withOutputFPS = + proto.withFpsOutput = + proto.withFPSOutput = + proto.withFps = + proto.withFPS = + proto.outputFPS = + proto.outputFps = + proto.fpsOutput = + proto.FPSOutput = + proto.fps = + proto.FPS = function(fps) { + this._currentOutput.video('-r', fps); + return this; + }; + + + /** + * Only transcode a certain number of frames + * + * @method FfmpegCommand#frames + * @category Video + * @aliases takeFrames,withFrames + * + * @param {Number} frames frame count + * @return FfmpegCommand + */ + proto.takeFrames = + proto.withFrames = + proto.frames = function(frames) { + this._currentOutput.video('-vframes', frames); + return this; + }; +}; + + +/***/ }), + +/***/ 4773: +/***/ ((module) => { + +"use strict"; +/*jshint node:true*/ + + +/* + *! Size helpers + */ + + +/** + * Return filters to pad video to width*height, + * + * @param {Number} width output width + * @param {Number} height output height + * @param {Number} aspect video aspect ratio (without padding) + * @param {Number} color padding color + * @return scale/pad filters + * @private + */ +function getScalePadFilters(width, height, aspect, color) { + /* + let a be the input aspect ratio, A be the requested aspect ratio + + if a > A, padding is done on top and bottom + if a < A, padding is done on left and right + */ + + return [ + /* + In both cases, we first have to scale the input to match the requested size. + When using computed width/height, we truncate them to multiples of 2 + */ + { + filter: 'scale', + options: { + w: 'if(gt(a,' + aspect + '),' + width + ',trunc(' + height + '*a/2)*2)', + h: 'if(lt(a,' + aspect + '),' + height + ',trunc(' + width + '/a/2)*2)' + } + }, + + /* + Then we pad the scaled input to match the target size + (here iw and ih refer to the padding input, i.e the scaled output) + */ + + { + filter: 'pad', + options: { + w: width, + h: height, + x: 'if(gt(a,' + aspect + '),0,(' + width + '-iw)/2)', + y: 'if(lt(a,' + aspect + '),0,(' + height + '-ih)/2)', + color: color + } + } + ]; +} + + +/** + * Recompute size filters + * + * @param {Object} output + * @param {String} key newly-added parameter name ('size', 'aspect' or 'pad') + * @param {String} value newly-added parameter value + * @return filter string array + * @private + */ +function createSizeFilters(output, key, value) { + // Store parameters + var data = output.sizeData = output.sizeData || {}; + data[key] = value; + + if (!('size' in data)) { + // No size requested, keep original size + return []; + } + + // Try to match the different size string formats + var fixedSize = data.size.match(/([0-9]+)x([0-9]+)/); + var fixedWidth = data.size.match(/([0-9]+)x\?/); + var fixedHeight = data.size.match(/\?x([0-9]+)/); + var percentRatio = data.size.match(/\b([0-9]{1,3})%/); + var width, height, aspect; + + if (percentRatio) { + var ratio = Number(percentRatio[1]) / 100; + return [{ + filter: 'scale', + options: { + w: 'trunc(iw*' + ratio + '/2)*2', + h: 'trunc(ih*' + ratio + '/2)*2' + } + }]; + } else if (fixedSize) { + // Round target size to multiples of 2 + width = Math.round(Number(fixedSize[1]) / 2) * 2; + height = Math.round(Number(fixedSize[2]) / 2) * 2; + + aspect = width / height; + + if (data.pad) { + return getScalePadFilters(width, height, aspect, data.pad); + } else { + // No autopad requested, rescale to target size + return [{ filter: 'scale', options: { w: width, h: height }}]; + } + } else if (fixedWidth || fixedHeight) { + if ('aspect' in data) { + // Specified aspect ratio + width = fixedWidth ? fixedWidth[1] : Math.round(Number(fixedHeight[1]) * data.aspect); + height = fixedHeight ? fixedHeight[1] : Math.round(Number(fixedWidth[1]) / data.aspect); + + // Round to multiples of 2 + width = Math.round(width / 2) * 2; + height = Math.round(height / 2) * 2; + + if (data.pad) { + return getScalePadFilters(width, height, data.aspect, data.pad); + } else { + // No autopad requested, rescale to target size + return [{ filter: 'scale', options: { w: width, h: height }}]; + } + } else { + // Keep input aspect ratio + + if (fixedWidth) { + return [{ + filter: 'scale', + options: { + w: Math.round(Number(fixedWidth[1]) / 2) * 2, + h: 'trunc(ow/a/2)*2' + } + }]; + } else { + return [{ + filter: 'scale', + options: { + w: 'trunc(oh*a/2)*2', + h: Math.round(Number(fixedHeight[1]) / 2) * 2 + } + }]; + } + } + } else { + throw new Error('Invalid size specified: ' + data.size); + } +} + + +/* + *! Video size-related methods + */ + +module.exports = function(proto) { + /** + * Keep display aspect ratio + * + * This method is useful when converting an input with non-square pixels to an output format + * that does not support non-square pixels. It rescales the input so that the display aspect + * ratio is the same. + * + * @method FfmpegCommand#keepDAR + * @category Video size + * @aliases keepPixelAspect,keepDisplayAspect,keepDisplayAspectRatio + * + * @return FfmpegCommand + */ + proto.keepPixelAspect = // Only for compatibility, this is not about keeping _pixel_ aspect ratio + proto.keepDisplayAspect = + proto.keepDisplayAspectRatio = + proto.keepDAR = function() { + return this.videoFilters([ + { + filter: 'scale', + options: { + w: 'if(gt(sar,1),iw*sar,iw)', + h: 'if(lt(sar,1),ih/sar,ih)' + } + }, + { + filter: 'setsar', + options: '1' + } + ]); + }; + + + /** + * Set output size + * + * The 'size' parameter can have one of 4 forms: + * - 'X%': rescale to xx % of the original size + * - 'WxH': specify width and height + * - 'Wx?': specify width and compute height from input aspect ratio + * - '?xH': specify height and compute width from input aspect ratio + * + * Note: both dimensions will be truncated to multiples of 2. + * + * @method FfmpegCommand#size + * @category Video size + * @aliases withSize,setSize + * + * @param {String} size size string, eg. '33%', '320x240', '320x?', '?x240' + * @return FfmpegCommand + */ + proto.withSize = + proto.setSize = + proto.size = function(size) { + var filters = createSizeFilters(this._currentOutput, 'size', size); + + this._currentOutput.sizeFilters.clear(); + this._currentOutput.sizeFilters(filters); + + return this; + }; + + + /** + * Set output aspect ratio + * + * @method FfmpegCommand#aspect + * @category Video size + * @aliases withAspect,withAspectRatio,setAspect,setAspectRatio,aspectRatio + * + * @param {String|Number} aspect aspect ratio (number or 'X:Y' string) + * @return FfmpegCommand + */ + proto.withAspect = + proto.withAspectRatio = + proto.setAspect = + proto.setAspectRatio = + proto.aspect = + proto.aspectRatio = function(aspect) { + var a = Number(aspect); + if (isNaN(a)) { + var match = aspect.match(/^(\d+):(\d+)$/); + if (match) { + a = Number(match[1]) / Number(match[2]); + } else { + throw new Error('Invalid aspect ratio: ' + aspect); + } + } + + var filters = createSizeFilters(this._currentOutput, 'aspect', a); + + this._currentOutput.sizeFilters.clear(); + this._currentOutput.sizeFilters(filters); + + return this; + }; + + + /** + * Enable auto-padding the output + * + * @method FfmpegCommand#autopad + * @category Video size + * @aliases applyAutopadding,applyAutoPadding,applyAutopad,applyAutoPad,withAutopadding,withAutoPadding,withAutopad,withAutoPad,autoPad + * + * @param {Boolean} [pad=true] enable/disable auto-padding + * @param {String} [color='black'] pad color + */ + proto.applyAutopadding = + proto.applyAutoPadding = + proto.applyAutopad = + proto.applyAutoPad = + proto.withAutopadding = + proto.withAutoPadding = + proto.withAutopad = + proto.withAutoPad = + proto.autoPad = + proto.autopad = function(pad, color) { + // Allow autopad(color) + if (typeof pad === 'string') { + color = pad; + pad = true; + } + + // Allow autopad() and autopad(undefined, color) + if (typeof pad === 'undefined') { + pad = true; + } + + var filters = createSizeFilters(this._currentOutput, 'pad', pad ? color || 'black' : false); + + this._currentOutput.sizeFilters.clear(); + this._currentOutput.sizeFilters(filters); + + return this; + }; +}; + + +/***/ }), + +/***/ 981: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +/*jshint node:true*/ + + +var spawn = (__nccwpck_require__(2081).spawn); +var path = __nccwpck_require__(1017); +var fs = __nccwpck_require__(7147); +var async = __nccwpck_require__(7888); +var utils = __nccwpck_require__(7166); + +var nlRegexp = /\r\n|\r|\n/g; + +/* + *! Processor methods + */ + + +/** + * Run ffprobe asynchronously and store data in command + * + * @param {FfmpegCommand} command + * @private + */ +function runFfprobe(command) { + const inputProbeIndex = 0; + if (command._inputs[inputProbeIndex].isStream) { + // Don't probe input streams as this will consume them + return; + } + command.ffprobe(inputProbeIndex, function(err, data) { + command._ffprobeData = data; + }); +} + + +module.exports = function(proto) { + /** + * Emitted just after ffmpeg has been spawned. + * + * @event FfmpegCommand#start + * @param {String} command ffmpeg command line + */ + + /** + * Emitted when ffmpeg reports progress information + * + * @event FfmpegCommand#progress + * @param {Object} progress progress object + * @param {Number} progress.frames number of frames transcoded + * @param {Number} progress.currentFps current processing speed in frames per second + * @param {Number} progress.currentKbps current output generation speed in kilobytes per second + * @param {Number} progress.targetSize current output file size + * @param {String} progress.timemark current video timemark + * @param {Number} [progress.percent] processing progress (may not be available depending on input) + */ + + /** + * Emitted when ffmpeg outputs to stderr + * + * @event FfmpegCommand#stderr + * @param {String} line stderr output line + */ + + /** + * Emitted when ffmpeg reports input codec data + * + * @event FfmpegCommand#codecData + * @param {Object} codecData codec data object + * @param {String} codecData.format input format name + * @param {String} codecData.audio input audio codec name + * @param {String} codecData.audio_details input audio codec parameters + * @param {String} codecData.video input video codec name + * @param {String} codecData.video_details input video codec parameters + */ + + /** + * Emitted when an error happens when preparing or running a command + * + * @event FfmpegCommand#error + * @param {Error} error error object, with optional properties 'inputStreamError' / 'outputStreamError' for errors on their respective streams + * @param {String|null} stdout ffmpeg stdout, unless outputting to a stream + * @param {String|null} stderr ffmpeg stderr + */ + + /** + * Emitted when a command finishes processing + * + * @event FfmpegCommand#end + * @param {Array|String|null} [filenames|stdout] generated filenames when taking screenshots, ffmpeg stdout when not outputting to a stream, null otherwise + * @param {String|null} stderr ffmpeg stderr + */ + + + /** + * Spawn an ffmpeg process + * + * The 'options' argument may contain the following keys: + * - 'niceness': specify process niceness, ignored on Windows (default: 0) + * - `cwd`: change working directory + * - 'captureStdout': capture stdout and pass it to 'endCB' as its 2nd argument (default: false) + * - 'stdoutLines': override command limit (default: use command limit) + * + * The 'processCB' callback, if present, is called as soon as the process is created and + * receives a nodejs ChildProcess object. It may not be called at all if an error happens + * before spawning the process. + * + * The 'endCB' callback is called either when an error occurs or when the ffmpeg process finishes. + * + * @method FfmpegCommand#_spawnFfmpeg + * @param {Array} args ffmpeg command line argument list + * @param {Object} [options] spawn options (see above) + * @param {Function} [processCB] callback called with process object and stdout/stderr ring buffers when process has been created + * @param {Function} endCB callback called with error (if applicable) and stdout/stderr ring buffers when process finished + * @private + */ + proto._spawnFfmpeg = function(args, options, processCB, endCB) { + // Enable omitting options + if (typeof options === 'function') { + endCB = processCB; + processCB = options; + options = {}; + } + + // Enable omitting processCB + if (typeof endCB === 'undefined') { + endCB = processCB; + processCB = function() {}; + } + + var maxLines = 'stdoutLines' in options ? options.stdoutLines : this.options.stdoutLines; + + // Find ffmpeg + this._getFfmpegPath(function(err, command) { + if (err) { + return endCB(err); + } else if (!command || command.length === 0) { + return endCB(new Error('Cannot find ffmpeg')); + } + + // Apply niceness + if (options.niceness && options.niceness !== 0 && !utils.isWindows) { + args.unshift('-n', options.niceness, command); + command = 'nice'; + } + + var stdoutRing = utils.linesRing(maxLines); + var stdoutClosed = false; + + var stderrRing = utils.linesRing(maxLines); + var stderrClosed = false; + + // Spawn process + var ffmpegProc = spawn(command, args, options); + + if (ffmpegProc.stderr) { + ffmpegProc.stderr.setEncoding('utf8'); + } + + ffmpegProc.on('error', function(err) { + endCB(err); + }); + + // Ensure we wait for captured streams to end before calling endCB + var exitError = null; + function handleExit(err) { + if (err) { + exitError = err; + } + + if (processExited && (stdoutClosed || !options.captureStdout) && stderrClosed) { + endCB(exitError, stdoutRing, stderrRing); + } + } + + // Handle process exit + var processExited = false; + ffmpegProc.on('exit', function(code, signal) { + processExited = true; + + if (signal) { + handleExit(new Error('ffmpeg was killed with signal ' + signal)); + } else if (code) { + handleExit(new Error('ffmpeg exited with code ' + code)); + } else { + handleExit(); + } + }); + + // Capture stdout if specified + if (options.captureStdout) { + ffmpegProc.stdout.on('data', function(data) { + stdoutRing.append(data); + }); + + ffmpegProc.stdout.on('close', function() { + stdoutRing.close(); + stdoutClosed = true; + handleExit(); + }); + } + + // Capture stderr if specified + ffmpegProc.stderr.on('data', function(data) { + stderrRing.append(data); + }); + + ffmpegProc.stderr.on('close', function() { + stderrRing.close(); + stderrClosed = true; + handleExit(); + }); + + // Call process callback + processCB(ffmpegProc, stdoutRing, stderrRing); + }); + }; + + + /** + * Build the argument list for an ffmpeg command + * + * @method FfmpegCommand#_getArguments + * @return argument list + * @private + */ + proto._getArguments = function() { + var complexFilters = this._complexFilters.get(); + + var fileOutput = this._outputs.some(function(output) { + return output.isFile; + }); + + return [].concat( + // Inputs and input options + this._inputs.reduce(function(args, input) { + var source = (typeof input.source === 'string') ? input.source : 'pipe:0'; + + // For each input, add input options, then '-i ' + return args.concat( + input.options.get(), + ['-i', source] + ); + }, []), + + // Global options + this._global.get(), + + // Overwrite if we have file outputs + fileOutput ? ['-y'] : [], + + // Complex filters + complexFilters, + + // Outputs, filters and output options + this._outputs.reduce(function(args, output) { + var sizeFilters = utils.makeFilterStrings(output.sizeFilters.get()); + var audioFilters = output.audioFilters.get(); + var videoFilters = output.videoFilters.get().concat(sizeFilters); + var outputArg; + + if (!output.target) { + outputArg = []; + } else if (typeof output.target === 'string') { + outputArg = [output.target]; + } else { + outputArg = ['pipe:1']; + } + + return args.concat( + output.audio.get(), + audioFilters.length ? ['-filter:a', audioFilters.join(',')] : [], + output.video.get(), + videoFilters.length ? ['-filter:v', videoFilters.join(',')] : [], + output.options.get(), + outputArg + ); + }, []) + ); + }; + + + /** + * Prepare execution of an ffmpeg command + * + * Checks prerequisites for the execution of the command (codec/format availability, flvtool...), + * then builds the argument list for ffmpeg and pass them to 'callback'. + * + * @method FfmpegCommand#_prepare + * @param {Function} callback callback with signature (err, args) + * @param {Boolean} [readMetadata=false] read metadata before processing + * @private + */ + proto._prepare = function(callback, readMetadata) { + var self = this; + + async.waterfall([ + // Check codecs and formats + function(cb) { + self._checkCapabilities(cb); + }, + + // Read metadata if required + function(cb) { + if (!readMetadata) { + return cb(); + } + + self.ffprobe(0, function(err, data) { + if (!err) { + self._ffprobeData = data; + } + + cb(); + }); + }, + + // Check for flvtool2/flvmeta if necessary + function(cb) { + var flvmeta = self._outputs.some(function(output) { + // Remove flvmeta flag on non-file output + if (output.flags.flvmeta && !output.isFile) { + self.logger.warn('Updating flv metadata is only supported for files'); + output.flags.flvmeta = false; + } + + return output.flags.flvmeta; + }); + + if (flvmeta) { + self._getFlvtoolPath(function(err) { + cb(err); + }); + } else { + cb(); + } + }, + + // Build argument list + function(cb) { + var args; + try { + args = self._getArguments(); + } catch(e) { + return cb(e); + } + + cb(null, args); + }, + + // Add "-strict experimental" option where needed + function(args, cb) { + self.availableEncoders(function(err, encoders) { + for (var i = 0; i < args.length; i++) { + if (args[i] === '-acodec' || args[i] === '-vcodec') { + i++; + + if ((args[i] in encoders) && encoders[args[i]].experimental) { + args.splice(i + 1, 0, '-strict', 'experimental'); + i += 2; + } + } + } + + cb(null, args); + }); + } + ], callback); + + if (!readMetadata) { + // Read metadata as soon as 'progress' listeners are added + + if (this.listeners('progress').length > 0) { + // Read metadata in parallel + runFfprobe(this); + } else { + // Read metadata as soon as the first 'progress' listener is added + this.once('newListener', function(event) { + if (event === 'progress') { + runFfprobe(this); + } + }); + } + } + }; + + + /** + * Run ffmpeg command + * + * @method FfmpegCommand#run + * @category Processing + * @aliases exec,execute + */ + proto.exec = + proto.execute = + proto.run = function() { + var self = this; + + // Check if at least one output is present + var outputPresent = this._outputs.some(function(output) { + return 'target' in output; + }); + + if (!outputPresent) { + throw new Error('No output specified'); + } + + // Get output stream if any + var outputStream = this._outputs.filter(function(output) { + return typeof output.target !== 'string'; + })[0]; + + // Get input stream if any + var inputStream = this._inputs.filter(function(input) { + return typeof input.source !== 'string'; + })[0]; + + // Ensure we send 'end' or 'error' only once + var ended = false; + function emitEnd(err, stdout, stderr) { + if (!ended) { + ended = true; + + if (err) { + self.emit('error', err, stdout, stderr); + } else { + self.emit('end', stdout, stderr); + } + } + } + + self._prepare(function(err, args) { + if (err) { + return emitEnd(err); + } + + // Run ffmpeg + self._spawnFfmpeg( + args, + { + captureStdout: !outputStream, + niceness: self.options.niceness, + cwd: self.options.cwd + }, + + function processCB(ffmpegProc, stdoutRing, stderrRing) { + self.ffmpegProc = ffmpegProc; + self.emit('start', 'ffmpeg ' + args.join(' ')); + + // Pipe input stream if any + if (inputStream) { + inputStream.source.on('error', function(err) { + var reportingErr = new Error('Input stream error: ' + err.message); + reportingErr.inputStreamError = err; + emitEnd(reportingErr); + ffmpegProc.kill(); + }); + + inputStream.source.resume(); + inputStream.source.pipe(ffmpegProc.stdin); + + // Set stdin error handler on ffmpeg (prevents nodejs catching the error, but + // ffmpeg will fail anyway, so no need to actually handle anything) + ffmpegProc.stdin.on('error', function() {}); + } + + // Setup timeout if requested + var processTimer; + if (self.options.timeout) { + processTimer = setTimeout(function() { + var msg = 'process ran into a timeout (' + self.options.timeout + 's)'; + + emitEnd(new Error(msg), stdoutRing.get(), stderrRing.get()); + ffmpegProc.kill(); + }, self.options.timeout * 1000); + } + + + if (outputStream) { + // Pipe ffmpeg stdout to output stream + ffmpegProc.stdout.pipe(outputStream.target, outputStream.pipeopts); + + // Handle output stream events + outputStream.target.on('close', function() { + self.logger.debug('Output stream closed, scheduling kill for ffmpeg process'); + + // Don't kill process yet, to give a chance to ffmpeg to + // terminate successfully first This is necessary because + // under load, the process 'exit' event sometimes happens + // after the output stream 'close' event. + setTimeout(function() { + emitEnd(new Error('Output stream closed')); + ffmpegProc.kill(); + }, 20); + }); + + outputStream.target.on('error', function(err) { + self.logger.debug('Output stream error, killing ffmpeg process'); + var reportingErr = new Error('Output stream error: ' + err.message); + reportingErr.outputStreamError = err; + emitEnd(reportingErr, stdoutRing.get(), stderrRing.get()); + ffmpegProc.kill('SIGKILL'); + }); + } + + // Setup stderr handling + if (stderrRing) { + + // 'stderr' event + if (self.listeners('stderr').length) { + stderrRing.callback(function(line) { + self.emit('stderr', line); + }); + } + + // 'codecData' event + if (self.listeners('codecData').length) { + var codecDataSent = false; + var codecObject = {}; + + stderrRing.callback(function(line) { + if (!codecDataSent) + codecDataSent = utils.extractCodecData(self, line, codecObject); + }); + } + + // 'progress' event + if (self.listeners('progress').length) { + stderrRing.callback(function(line) { + utils.extractProgress(self, line); + }); + } + } + }, + + function endCB(err, stdoutRing, stderrRing) { + delete self.ffmpegProc; + + if (err) { + if (err.message.match(/ffmpeg exited with code/)) { + // Add ffmpeg error message + err.message += ': ' + utils.extractError(stderrRing.get()); + } + + emitEnd(err, stdoutRing.get(), stderrRing.get()); + } else { + // Find out which outputs need flv metadata + var flvmeta = self._outputs.filter(function(output) { + return output.flags.flvmeta; + }); + + if (flvmeta.length) { + self._getFlvtoolPath(function(err, flvtool) { + if (err) { + return emitEnd(err); + } + + async.each( + flvmeta, + function(output, cb) { + spawn(flvtool, ['-U', output.target]) + .on('error', function(err) { + cb(new Error('Error running ' + flvtool + ' on ' + output.target + ': ' + err.message)); + }) + .on('exit', function(code, signal) { + if (code !== 0 || signal) { + cb( + new Error(flvtool + ' ' + + (signal ? 'received signal ' + signal + : 'exited with code ' + code)) + + ' when running on ' + output.target + ); + } else { + cb(); + } + }); + }, + function(err) { + if (err) { + emitEnd(err); + } else { + emitEnd(null, stdoutRing.get(), stderrRing.get()); + } + } + ); + }); + } else { + emitEnd(null, stdoutRing.get(), stderrRing.get()); + } + } + } + ); + }); + }; + + + /** + * Renice current and/or future ffmpeg processes + * + * Ignored on Windows platforms. + * + * @method FfmpegCommand#renice + * @category Processing + * + * @param {Number} [niceness=0] niceness value between -20 (highest priority) and 20 (lowest priority) + * @return FfmpegCommand + */ + proto.renice = function(niceness) { + if (!utils.isWindows) { + niceness = niceness || 0; + + if (niceness < -20 || niceness > 20) { + this.logger.warn('Invalid niceness value: ' + niceness + ', must be between -20 and 20'); + } + + niceness = Math.min(20, Math.max(-20, niceness)); + this.options.niceness = niceness; + + if (this.ffmpegProc) { + var logger = this.logger; + var pid = this.ffmpegProc.pid; + var renice = spawn('renice', [niceness, '-p', pid]); + + renice.on('error', function(err) { + logger.warn('could not renice process ' + pid + ': ' + err.message); + }); + + renice.on('exit', function(code, signal) { + if (signal) { + logger.warn('could not renice process ' + pid + ': renice was killed by signal ' + signal); + } else if (code) { + logger.warn('could not renice process ' + pid + ': renice exited with ' + code); + } else { + logger.info('successfully reniced process ' + pid + ' to ' + niceness + ' niceness'); + } + }); + } + } + + return this; + }; + + + /** + * Kill current ffmpeg process, if any + * + * @method FfmpegCommand#kill + * @category Processing + * + * @param {String} [signal=SIGKILL] signal name + * @return FfmpegCommand + */ + proto.kill = function(signal) { + if (!this.ffmpegProc) { + this.logger.warn('No running ffmpeg process, cannot send signal'); + } else { + this.ffmpegProc.kill(signal || 'SIGKILL'); + } + + return this; + }; +}; + + +/***/ }), + +/***/ 9341: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +/*jshint node:true*/ + + +var fs = __nccwpck_require__(7147); +var path = __nccwpck_require__(1017); +var PassThrough = (__nccwpck_require__(2781).PassThrough); +var async = __nccwpck_require__(7888); +var utils = __nccwpck_require__(7166); + + +/* + * Useful recipes for commands + */ + +module.exports = function recipes(proto) { + /** + * Execute ffmpeg command and save output to a file + * + * @method FfmpegCommand#save + * @category Processing + * @aliases saveToFile + * + * @param {String} output file path + * @return FfmpegCommand + */ + proto.saveToFile = + proto.save = function(output) { + this.output(output).run(); + return this; + }; + + + /** + * Execute ffmpeg command and save output to a stream + * + * If 'stream' is not specified, a PassThrough stream is created and returned. + * 'options' will be used when piping ffmpeg output to the output stream + * (@see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options) + * + * @method FfmpegCommand#pipe + * @category Processing + * @aliases stream,writeToStream + * + * @param {stream.Writable} [stream] output stream + * @param {Object} [options={}] pipe options + * @return Output stream + */ + proto.writeToStream = + proto.pipe = + proto.stream = function(stream, options) { + if (stream && !('writable' in stream)) { + options = stream; + stream = undefined; + } + + if (!stream) { + if (process.version.match(/v0\.8\./)) { + throw new Error('PassThrough stream is not supported on node v0.8'); + } + + stream = new PassThrough(); + } + + this.output(stream, options).run(); + return stream; + }; + + + /** + * Generate images from a video + * + * Note: this method makes the command emit a 'filenames' event with an array of + * the generated image filenames. + * + * @method FfmpegCommand#screenshots + * @category Processing + * @aliases takeScreenshots,thumbnail,thumbnails,screenshot + * + * @param {Number|Object} [config=1] screenshot count or configuration object with + * the following keys: + * @param {Number} [config.count] number of screenshots to take; using this option + * takes screenshots at regular intervals (eg. count=4 would take screens at 20%, 40%, + * 60% and 80% of the video length). + * @param {String} [config.folder='.'] output folder + * @param {String} [config.filename='tn.png'] output filename pattern, may contain the following + * tokens: + * - '%s': offset in seconds + * - '%w': screenshot width + * - '%h': screenshot height + * - '%r': screenshot resolution (same as '%wx%h') + * - '%f': input filename + * - '%b': input basename (filename w/o extension) + * - '%i': index of screenshot in timemark array (can be zero-padded by using it like `%000i`) + * @param {Number[]|String[]} [config.timemarks] array of timemarks to take screenshots + * at; each timemark may be a number of seconds, a '[[hh:]mm:]ss[.xxx]' string or a + * 'XX%' string. Overrides 'count' if present. + * @param {Number[]|String[]} [config.timestamps] alias for 'timemarks' + * @param {Boolean} [config.fastSeek] use fast seek (less accurate) + * @param {String} [config.size] screenshot size, with the same syntax as {@link FfmpegCommand#size} + * @param {String} [folder] output folder (legacy alias for 'config.folder') + * @return FfmpegCommand + */ + proto.takeScreenshots = + proto.thumbnail = + proto.thumbnails = + proto.screenshot = + proto.screenshots = function(config, folder) { + var self = this; + var source = this._currentInput.source; + config = config || { count: 1 }; + + // Accept a number of screenshots instead of a config object + if (typeof config === 'number') { + config = { + count: config + }; + } + + // Accept a second 'folder' parameter instead of config.folder + if (!('folder' in config)) { + config.folder = folder || '.'; + } + + // Accept 'timestamps' instead of 'timemarks' + if ('timestamps' in config) { + config.timemarks = config.timestamps; + } + + // Compute timemarks from count if not present + if (!('timemarks' in config)) { + if (!config.count) { + throw new Error('Cannot take screenshots: neither a count nor a timemark list are specified'); + } + + var interval = 100 / (1 + config.count); + config.timemarks = []; + for (var i = 0; i < config.count; i++) { + config.timemarks.push((interval * (i + 1)) + '%'); + } + } + + // Parse size option + if ('size' in config) { + var fixedSize = config.size.match(/^(\d+)x(\d+)$/); + var fixedWidth = config.size.match(/^(\d+)x\?$/); + var fixedHeight = config.size.match(/^\?x(\d+)$/); + var percentSize = config.size.match(/^(\d+)%$/); + + if (!fixedSize && !fixedWidth && !fixedHeight && !percentSize) { + throw new Error('Invalid size parameter: ' + config.size); + } + } + + // Metadata helper + var metadata; + function getMetadata(cb) { + if (metadata) { + cb(null, metadata); + } else { + self.ffprobe(function(err, meta) { + metadata = meta; + cb(err, meta); + }); + } + } + + async.waterfall([ + // Compute percent timemarks if any + function computeTimemarks(next) { + if (config.timemarks.some(function(t) { return ('' + t).match(/^[\d.]+%$/); })) { + if (typeof source !== 'string') { + return next(new Error('Cannot compute screenshot timemarks with an input stream, please specify fixed timemarks')); + } + + getMetadata(function(err, meta) { + if (err) { + next(err); + } else { + // Select video stream with the highest resolution + var vstream = meta.streams.reduce(function(biggest, stream) { + if (stream.codec_type === 'video' && stream.width * stream.height > biggest.width * biggest.height) { + return stream; + } else { + return biggest; + } + }, { width: 0, height: 0 }); + + if (vstream.width === 0) { + return next(new Error('No video stream in input, cannot take screenshots')); + } + + var duration = Number(vstream.duration); + if (isNaN(duration)) { + duration = Number(meta.format.duration); + } + + if (isNaN(duration)) { + return next(new Error('Could not get input duration, please specify fixed timemarks')); + } + + config.timemarks = config.timemarks.map(function(mark) { + if (('' + mark).match(/^([\d.]+)%$/)) { + return duration * parseFloat(mark) / 100; + } else { + return mark; + } + }); + + next(); + } + }); + } else { + next(); + } + }, + + // Turn all timemarks into numbers and sort them + function normalizeTimemarks(next) { + config.timemarks = config.timemarks.map(function(mark) { + return utils.timemarkToSeconds(mark); + }).sort(function(a, b) { return a - b; }); + + next(); + }, + + // Add '_%i' to pattern when requesting multiple screenshots and no variable token is present + function fixPattern(next) { + var pattern = config.filename || 'tn.png'; + + if (pattern.indexOf('.') === -1) { + pattern += '.png'; + } + + if (config.timemarks.length > 1 && !pattern.match(/%(s|0*i)/)) { + var ext = path.extname(pattern); + pattern = path.join(path.dirname(pattern), path.basename(pattern, ext) + '_%i' + ext); + } + + next(null, pattern); + }, + + // Replace filename tokens (%f, %b) in pattern + function replaceFilenameTokens(pattern, next) { + if (pattern.match(/%[bf]/)) { + if (typeof source !== 'string') { + return next(new Error('Cannot replace %f or %b when using an input stream')); + } + + pattern = pattern + .replace(/%f/g, path.basename(source)) + .replace(/%b/g, path.basename(source, path.extname(source))); + } + + next(null, pattern); + }, + + // Compute size if needed + function getSize(pattern, next) { + if (pattern.match(/%[whr]/)) { + if (fixedSize) { + return next(null, pattern, fixedSize[1], fixedSize[2]); + } + + getMetadata(function(err, meta) { + if (err) { + return next(new Error('Could not determine video resolution to replace %w, %h or %r')); + } + + var vstream = meta.streams.reduce(function(biggest, stream) { + if (stream.codec_type === 'video' && stream.width * stream.height > biggest.width * biggest.height) { + return stream; + } else { + return biggest; + } + }, { width: 0, height: 0 }); + + if (vstream.width === 0) { + return next(new Error('No video stream in input, cannot replace %w, %h or %r')); + } + + var width = vstream.width; + var height = vstream.height; + + if (fixedWidth) { + height = height * Number(fixedWidth[1]) / width; + width = Number(fixedWidth[1]); + } else if (fixedHeight) { + width = width * Number(fixedHeight[1]) / height; + height = Number(fixedHeight[1]); + } else if (percentSize) { + width = width * Number(percentSize[1]) / 100; + height = height * Number(percentSize[1]) / 100; + } + + next(null, pattern, Math.round(width / 2) * 2, Math.round(height / 2) * 2); + }); + } else { + next(null, pattern, -1, -1); + } + }, + + // Replace size tokens (%w, %h, %r) in pattern + function replaceSizeTokens(pattern, width, height, next) { + pattern = pattern + .replace(/%r/g, '%wx%h') + .replace(/%w/g, width) + .replace(/%h/g, height); + + next(null, pattern); + }, + + // Replace variable tokens in pattern (%s, %i) and generate filename list + function replaceVariableTokens(pattern, next) { + var filenames = config.timemarks.map(function(t, i) { + return pattern + .replace(/%s/g, utils.timemarkToSeconds(t)) + .replace(/%(0*)i/g, function(match, padding) { + var idx = '' + (i + 1); + return padding.substr(0, Math.max(0, padding.length + 1 - idx.length)) + idx; + }); + }); + + self.emit('filenames', filenames); + next(null, filenames); + }, + + // Create output directory + function createDirectory(filenames, next) { + fs.exists(config.folder, function(exists) { + if (!exists) { + fs.mkdir(config.folder, function(err) { + if (err) { + next(err); + } else { + next(null, filenames); + } + }); + } else { + next(null, filenames); + } + }); + } + ], function runCommand(err, filenames) { + if (err) { + return self.emit('error', err); + } + + var count = config.timemarks.length; + var split; + var filters = [split = { + filter: 'split', + options: count, + outputs: [] + }]; + + if ('size' in config) { + // Set size to generate size filters + self.size(config.size); + + // Get size filters and chain them with 'sizeN' stream names + var sizeFilters = self._currentOutput.sizeFilters.get().map(function(f, i) { + if (i > 0) { + f.inputs = 'size' + (i - 1); + } + + f.outputs = 'size' + i; + + return f; + }); + + // Input last size filter output into split filter + split.inputs = 'size' + (sizeFilters.length - 1); + + // Add size filters in front of split filter + filters = sizeFilters.concat(filters); + + // Remove size filters + self._currentOutput.sizeFilters.clear(); + } + + var first = 0; + for (var i = 0; i < count; i++) { + var stream = 'screen' + i; + split.outputs.push(stream); + + if (i === 0) { + first = config.timemarks[i]; + self.seekInput(first); + } + + self.output(path.join(config.folder, filenames[i])) + .frames(1) + .map(stream); + + if (i > 0) { + self.seek(config.timemarks[i] - first); + } + } + + self.complexFilter(filters); + self.run(); + }); + + return this; + }; + + + /** + * Merge (concatenate) inputs to a single file + * + * @method FfmpegCommand#concat + * @category Processing + * @aliases concatenate,mergeToFile + * + * @param {String|Writable} target output file or writable stream + * @param {Object} [options] pipe options (only used when outputting to a writable stream) + * @return FfmpegCommand + */ + proto.mergeToFile = + proto.concatenate = + proto.concat = function(target, options) { + // Find out which streams are present in the first non-stream input + var fileInput = this._inputs.filter(function(input) { + return !input.isStream; + })[0]; + + var self = this; + this.ffprobe(this._inputs.indexOf(fileInput), function(err, data) { + if (err) { + return self.emit('error', err); + } + + var hasAudioStreams = data.streams.some(function(stream) { + return stream.codec_type === 'audio'; + }); + + var hasVideoStreams = data.streams.some(function(stream) { + return stream.codec_type === 'video'; + }); + + // Setup concat filter and start processing + self.output(target, options) + .complexFilter({ + filter: 'concat', + options: { + n: self._inputs.length, + v: hasVideoStreams ? 1 : 0, + a: hasAudioStreams ? 1 : 0 + } + }) + .run(); + }); + + return this; + }; +}; + + +/***/ }), + +/***/ 7166: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +/*jshint node:true*/ + + +var exec = (__nccwpck_require__(2081).exec); +var isWindows = (__nccwpck_require__(2037).platform)().match(/win(32|64)/); +var which = __nccwpck_require__(4207); + +var nlRegexp = /\r\n|\r|\n/g; +var streamRegexp = /^\[?(.*?)\]?$/; +var filterEscapeRegexp = /[,]/; +var whichCache = {}; + +/** + * Parse progress line from ffmpeg stderr + * + * @param {String} line progress line + * @return progress object + * @private + */ +function parseProgressLine(line) { + var progress = {}; + + // Remove all spaces after = and trim + line = line.replace(/=\s+/g, '=').trim(); + var progressParts = line.split(' '); + + // Split every progress part by "=" to get key and value + for(var i = 0; i < progressParts.length; i++) { + var progressSplit = progressParts[i].split('=', 2); + var key = progressSplit[0]; + var value = progressSplit[1]; + + // This is not a progress line + if(typeof value === 'undefined') + return null; + + progress[key] = value; + } + + return progress; +} + + +var utils = module.exports = { + isWindows: isWindows, + streamRegexp: streamRegexp, + + + /** + * Copy an object keys into another one + * + * @param {Object} source source object + * @param {Object} dest destination object + * @private + */ + copy: function(source, dest) { + Object.keys(source).forEach(function(key) { + dest[key] = source[key]; + }); + }, + + + /** + * Create an argument list + * + * Returns a function that adds new arguments to the list. + * It also has the following methods: + * - clear() empties the argument list + * - get() returns the argument list + * - find(arg, count) finds 'arg' in the list and return the following 'count' items, or undefined if not found + * - remove(arg, count) remove 'arg' in the list as well as the following 'count' items + * + * @private + */ + args: function() { + var list = []; + + // Append argument(s) to the list + var argfunc = function() { + if (arguments.length === 1 && Array.isArray(arguments[0])) { + list = list.concat(arguments[0]); + } else { + list = list.concat([].slice.call(arguments)); + } + }; + + // Clear argument list + argfunc.clear = function() { + list = []; + }; + + // Return argument list + argfunc.get = function() { + return list; + }; + + // Find argument 'arg' in list, and if found, return an array of the 'count' items that follow it + argfunc.find = function(arg, count) { + var index = list.indexOf(arg); + if (index !== -1) { + return list.slice(index + 1, index + 1 + (count || 0)); + } + }; + + // Find argument 'arg' in list, and if found, remove it as well as the 'count' items that follow it + argfunc.remove = function(arg, count) { + var index = list.indexOf(arg); + if (index !== -1) { + list.splice(index, (count || 0) + 1); + } + }; + + // Clone argument list + argfunc.clone = function() { + var cloned = utils.args(); + cloned(list); + return cloned; + }; + + return argfunc; + }, + + + /** + * Generate filter strings + * + * @param {String[]|Object[]} filters filter specifications. When using objects, + * each must have the following properties: + * @param {String} filters.filter filter name + * @param {String|Array} [filters.inputs] (array of) input stream specifier(s) for the filter, + * defaults to ffmpeg automatically choosing the first unused matching streams + * @param {String|Array} [filters.outputs] (array of) output stream specifier(s) for the filter, + * defaults to ffmpeg automatically assigning the output to the output file + * @param {Object|String|Array} [filters.options] filter options, can be omitted to not set any options + * @return String[] + * @private + */ + makeFilterStrings: function(filters) { + return filters.map(function(filterSpec) { + if (typeof filterSpec === 'string') { + return filterSpec; + } + + var filterString = ''; + + // Filter string format is: + // [input1][input2]...filter[output1][output2]... + // The 'filter' part can optionaly have arguments: + // filter=arg1:arg2:arg3 + // filter=arg1=v1:arg2=v2:arg3=v3 + + // Add inputs + if (Array.isArray(filterSpec.inputs)) { + filterString += filterSpec.inputs.map(function(streamSpec) { + return streamSpec.replace(streamRegexp, '[$1]'); + }).join(''); + } else if (typeof filterSpec.inputs === 'string') { + filterString += filterSpec.inputs.replace(streamRegexp, '[$1]'); + } + + // Add filter + filterString += filterSpec.filter; + + // Add options + if (filterSpec.options) { + if (typeof filterSpec.options === 'string' || typeof filterSpec.options === 'number') { + // Option string + filterString += '=' + filterSpec.options; + } else if (Array.isArray(filterSpec.options)) { + // Option array (unnamed options) + filterString += '=' + filterSpec.options.map(function(option) { + if (typeof option === 'string' && option.match(filterEscapeRegexp)) { + return '\'' + option + '\''; + } else { + return option; + } + }).join(':'); + } else if (Object.keys(filterSpec.options).length) { + // Option object (named options) + filterString += '=' + Object.keys(filterSpec.options).map(function(option) { + var value = filterSpec.options[option]; + + if (typeof value === 'string' && value.match(filterEscapeRegexp)) { + value = '\'' + value + '\''; + } + + return option + '=' + value; + }).join(':'); + } + } + + // Add outputs + if (Array.isArray(filterSpec.outputs)) { + filterString += filterSpec.outputs.map(function(streamSpec) { + return streamSpec.replace(streamRegexp, '[$1]'); + }).join(''); + } else if (typeof filterSpec.outputs === 'string') { + filterString += filterSpec.outputs.replace(streamRegexp, '[$1]'); + } + + return filterString; + }); + }, + + + /** + * Search for an executable + * + * Uses 'which' or 'where' depending on platform + * + * @param {String} name executable name + * @param {Function} callback callback with signature (err, path) + * @private + */ + which: function(name, callback) { + if (name in whichCache) { + return callback(null, whichCache[name]); + } + + which(name, function(err, result){ + if (err) { + // Treat errors as not found + return callback(null, whichCache[name] = ''); + } + callback(null, whichCache[name] = result); + }); + }, + + + /** + * Convert a [[hh:]mm:]ss[.xxx] timemark into seconds + * + * @param {String} timemark timemark string + * @return Number + * @private + */ + timemarkToSeconds: function(timemark) { + if (typeof timemark === 'number') { + return timemark; + } + + if (timemark.indexOf(':') === -1 && timemark.indexOf('.') >= 0) { + return Number(timemark); + } + + var parts = timemark.split(':'); + + // add seconds + var secs = Number(parts.pop()); + + if (parts.length) { + // add minutes + secs += Number(parts.pop()) * 60; + } + + if (parts.length) { + // add hours + secs += Number(parts.pop()) * 3600; + } + + return secs; + }, + + + /** + * Extract codec data from ffmpeg stderr and emit 'codecData' event if appropriate + * Call it with an initially empty codec object once with each line of stderr output until it returns true + * + * @param {FfmpegCommand} command event emitter + * @param {String} stderrLine ffmpeg stderr output line + * @param {Object} codecObject object used to accumulate codec data between calls + * @return {Boolean} true if codec data is complete (and event was emitted), false otherwise + * @private + */ + extractCodecData: function(command, stderrLine, codecsObject) { + var inputPattern = /Input #[0-9]+, ([^ ]+),/; + var durPattern = /Duration\: ([^,]+)/; + var audioPattern = /Audio\: (.*)/; + var videoPattern = /Video\: (.*)/; + + if (!('inputStack' in codecsObject)) { + codecsObject.inputStack = []; + codecsObject.inputIndex = -1; + codecsObject.inInput = false; + } + + var inputStack = codecsObject.inputStack; + var inputIndex = codecsObject.inputIndex; + var inInput = codecsObject.inInput; + + var format, dur, audio, video; + + if (format = stderrLine.match(inputPattern)) { + inInput = codecsObject.inInput = true; + inputIndex = codecsObject.inputIndex = codecsObject.inputIndex + 1; + + inputStack[inputIndex] = { format: format[1], audio: '', video: '', duration: '' }; + } else if (inInput && (dur = stderrLine.match(durPattern))) { + inputStack[inputIndex].duration = dur[1]; + } else if (inInput && (audio = stderrLine.match(audioPattern))) { + audio = audio[1].split(', '); + inputStack[inputIndex].audio = audio[0]; + inputStack[inputIndex].audio_details = audio; + } else if (inInput && (video = stderrLine.match(videoPattern))) { + video = video[1].split(', '); + inputStack[inputIndex].video = video[0]; + inputStack[inputIndex].video_details = video; + } else if (/Output #\d+/.test(stderrLine)) { + inInput = codecsObject.inInput = false; + } else if (/Stream mapping:|Press (\[q\]|ctrl-c) to stop/.test(stderrLine)) { + command.emit.apply(command, ['codecData'].concat(inputStack)); + return true; + } + + return false; + }, + + + /** + * Extract progress data from ffmpeg stderr and emit 'progress' event if appropriate + * + * @param {FfmpegCommand} command event emitter + * @param {String} stderrLine ffmpeg stderr data + * @private + */ + extractProgress: function(command, stderrLine) { + var progress = parseProgressLine(stderrLine); + + if (progress) { + // build progress report object + var ret = { + frames: parseInt(progress.frame, 10), + currentFps: parseInt(progress.fps, 10), + currentKbps: progress.bitrate ? parseFloat(progress.bitrate.replace('kbits/s', '')) : 0, + targetSize: parseInt(progress.size || progress.Lsize, 10), + timemark: progress.time + }; + + // calculate percent progress using duration + if (command._ffprobeData && command._ffprobeData.format && command._ffprobeData.format.duration) { + var duration = Number(command._ffprobeData.format.duration); + if (!isNaN(duration)) + ret.percent = (utils.timemarkToSeconds(ret.timemark) / duration) * 100; + } + command.emit('progress', ret); + } + }, + + + /** + * Extract error message(s) from ffmpeg stderr + * + * @param {String} stderr ffmpeg stderr data + * @return {String} + * @private + */ + extractError: function(stderr) { + // Only return the last stderr lines that don't start with a space or a square bracket + return stderr.split(nlRegexp).reduce(function(messages, message) { + if (message.charAt(0) === ' ' || message.charAt(0) === '[') { + return []; + } else { + messages.push(message); + return messages; + } + }, []).join('\n'); + }, + + + /** + * Creates a line ring buffer object with the following methods: + * - append(str) : appends a string or buffer + * - get() : returns the whole string + * - close() : prevents further append() calls and does a last call to callbacks + * - callback(cb) : calls cb for each line (incl. those already in the ring) + * + * @param {Numebr} maxLines maximum number of lines to store (<= 0 for unlimited) + */ + linesRing: function(maxLines) { + var cbs = []; + var lines = []; + var current = null; + var closed = false + var max = maxLines - 1; + + function emit(line) { + cbs.forEach(function(cb) { cb(line); }); + } + + return { + callback: function(cb) { + lines.forEach(function(l) { cb(l); }); + cbs.push(cb); + }, + + append: function(str) { + if (closed) return; + if (str instanceof Buffer) str = '' + str; + if (!str || str.length === 0) return; + + var newLines = str.split(nlRegexp); + + if (newLines.length === 1) { + if (current !== null) { + current = current + newLines.shift(); + } else { + current = newLines.shift(); + } + } else { + if (current !== null) { + current = current + newLines.shift(); + emit(current); + lines.push(current); + } + + current = newLines.pop(); + + newLines.forEach(function(l) { + emit(l); + lines.push(l); + }); + + if (max > -1 && lines.length > max) { + lines.splice(0, lines.length - max); + } + } + }, + + get: function() { + if (current !== null) { + return lines.concat([current]).join('\n'); + } else { + return lines.join('\n'); + } + }, + + close: function() { + if (closed) return; + + if (current !== null) { + emit(current); + lines.push(current); + + if (max > -1 && lines.length > max) { + lines.shift(); + } + + current = null; + } + + closed = true; + } + }; + } +}; + + +/***/ }), + +/***/ 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 +}; + + +/***/ }), + +/***/ 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 + + +/***/ }), + +/***/ 7126: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var fs = __nccwpck_require__(7147) +var core +if (process.platform === 'win32' || global.TESTING_WINDOWS) { + core = __nccwpck_require__(2001) +} else { + core = __nccwpck_require__(9728) +} + +module.exports = isexe +isexe.sync = sync + +function isexe (path, options, cb) { + if (typeof options === 'function') { + cb = options + options = {} + } + + if (!cb) { + if (typeof Promise !== 'function') { + throw new TypeError('callback not provided') + } + + return new Promise(function (resolve, reject) { + isexe(path, options || {}, function (er, is) { + if (er) { + reject(er) + } else { + resolve(is) + } + }) + }) + } + + core(path, options || {}, function (er, is) { + // ignore EACCES because that just means we aren't allowed to run it + if (er) { + if (er.code === 'EACCES' || options && options.ignoreErrors) { + er = null + is = false + } + } + cb(er, is) + }) +} + +function sync (path, options) { + // my kingdom for a filtered catch + try { + return core.sync(path, options || {}) + } catch (er) { + if (options && options.ignoreErrors || er.code === 'EACCES') { + return false + } else { + throw er + } + } +} + + +/***/ }), + +/***/ 9728: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +module.exports = isexe +isexe.sync = sync + +var fs = __nccwpck_require__(7147) + +function isexe (path, options, cb) { + fs.stat(path, function (er, stat) { + cb(er, er ? false : checkStat(stat, options)) + }) +} + +function sync (path, options) { + return checkStat(fs.statSync(path), options) +} + +function checkStat (stat, options) { + return stat.isFile() && checkMode(stat, options) +} + +function checkMode (stat, options) { + var mod = stat.mode + var uid = stat.uid + var gid = stat.gid + + var myUid = options.uid !== undefined ? + options.uid : process.getuid && process.getuid() + var myGid = options.gid !== undefined ? + options.gid : process.getgid && process.getgid() + + var u = parseInt('100', 8) + var g = parseInt('010', 8) + var o = parseInt('001', 8) + var ug = u | g + + var ret = (mod & o) || + (mod & g) && gid === myGid || + (mod & u) && uid === myUid || + (mod & ug) && myUid === 0 + + return ret +} + + +/***/ }), + +/***/ 2001: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +module.exports = isexe +isexe.sync = sync + +var fs = __nccwpck_require__(7147) + +function checkPathExt (path, options) { + var pathext = options.pathExt !== undefined ? + options.pathExt : process.env.PATHEXT + + if (!pathext) { + return true + } + + pathext = pathext.split(';') + if (pathext.indexOf('') !== -1) { + return true + } + for (var i = 0; i < pathext.length; i++) { + var p = pathext[i].toLowerCase() + if (p && path.substr(-p.length).toLowerCase() === p) { + return true + } + } + return false +} + +function checkStat (stat, path, options) { + if (!stat.isSymbolicLink() && !stat.isFile()) { + return false + } + return checkPathExt(path, options) +} + +function isexe (path, options, cb) { + fs.stat(path, function (er, stat) { + cb(er, er ? false : checkStat(stat, path, options)) + }) +} + +function sync (path, options) { + return checkStat(fs.statSync(path), path, options) +} + + +/***/ }), + +/***/ 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) +} + +/***/ }), + +/***/ 6247: +/***/ ((module, exports, __nccwpck_require__) => { + +/* module decorator */ module = __nccwpck_require__.nmd(module); +/** + * Lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ + +/** Used as the size to enable large array optimizations. */ +var LARGE_ARRAY_SIZE = 200; + +/** Used to stand-in for `undefined` hash values. */ +var HASH_UNDEFINED = '__lodash_hash_undefined__'; + +/** Used to detect hot functions by number of calls within a span of milliseconds. */ +var HOT_COUNT = 800, + HOT_SPAN = 16; + +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; + +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]', + arrayTag = '[object Array]', + asyncTag = '[object AsyncFunction]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + errorTag = '[object Error]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + mapTag = '[object Map]', + numberTag = '[object Number]', + nullTag = '[object Null]', + objectTag = '[object Object]', + proxyTag = '[object Proxy]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + undefinedTag = '[object Undefined]', + weakMapTag = '[object WeakMap]'; + +var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; + +/** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ +var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; + +/** Used to detect host constructors (Safari). */ +var reIsHostCtor = /^\[object .+?Constructor\]$/; + +/** Used to detect unsigned integer values. */ +var reIsUint = /^(?:0|[1-9]\d*)$/; + +/** Used to identify `toStringTag` values of typed arrays. */ +var typedArrayTags = {}; +typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = +typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = +typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = +typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = +typedArrayTags[uint32Tag] = true; +typedArrayTags[argsTag] = typedArrayTags[arrayTag] = +typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = +typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = +typedArrayTags[errorTag] = typedArrayTags[funcTag] = +typedArrayTags[mapTag] = typedArrayTags[numberTag] = +typedArrayTags[objectTag] = typedArrayTags[regexpTag] = +typedArrayTags[setTag] = typedArrayTags[stringTag] = +typedArrayTags[weakMapTag] = false; + +/** Detect free variable `global` from Node.js. */ +var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; + +/** Detect free variable `self`. */ +var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + +/** Used as a reference to the global object. */ +var root = freeGlobal || freeSelf || Function('return this')(); + +/** Detect free variable `exports`. */ +var freeExports = true && exports && !exports.nodeType && exports; + +/** Detect free variable `module`. */ +var freeModule = freeExports && "object" == 'object' && module && !module.nodeType && module; + +/** Detect the popular CommonJS extension `module.exports`. */ +var moduleExports = freeModule && freeModule.exports === freeExports; + +/** Detect free variable `process` from Node.js. */ +var freeProcess = moduleExports && freeGlobal.process; + +/** Used to access faster Node.js helpers. */ +var nodeUtil = (function() { + try { + // Use `util.types` for Node.js 10+. + var types = freeModule && freeModule.require && freeModule.require('util').types; + + if (types) { + return types; + } + + // Legacy `process.binding('util')` for Node.js < 10. + return freeProcess && freeProcess.binding && freeProcess.binding('util'); + } catch (e) {} +}()); + +/* Node.js helper references. */ +var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; + +/** + * A faster alternative to `Function#apply`, this function invokes `func` + * with the `this` binding of `thisArg` and the arguments of `args`. + * + * @private + * @param {Function} func The function to invoke. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} args The arguments to invoke `func` with. + * @returns {*} Returns the result of `func`. + */ +function apply(func, thisArg, args) { + switch (args.length) { + case 0: return func.call(thisArg); + case 1: return func.call(thisArg, args[0]); + case 2: return func.call(thisArg, args[0], args[1]); + case 3: return func.call(thisArg, args[0], args[1], args[2]); + } + return func.apply(thisArg, args); +} + +/** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ +function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); + + while (++index < n) { + result[index] = iteratee(index); + } + return result; +} + +/** + * The base implementation of `_.unary` without support for storing metadata. + * + * @private + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + */ +function baseUnary(func) { + return function(value) { + return func(value); + }; +} + +/** + * Gets the value at `key` of `object`. + * + * @private + * @param {Object} [object] The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ +function getValue(object, key) { + return object == null ? undefined : object[key]; +} + +/** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ +function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; +} + +/** Used for built-in method references. */ +var arrayProto = Array.prototype, + funcProto = Function.prototype, + objectProto = Object.prototype; + +/** Used to detect overreaching core-js shims. */ +var coreJsData = root['__core-js_shared__']; + +/** Used to resolve the decompiled source of functions. */ +var funcToString = funcProto.toString; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** Used to detect methods masquerading as native. */ +var maskSrcKey = (function() { + var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); + return uid ? ('Symbol(src)_1.' + uid) : ''; +}()); + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var nativeObjectToString = objectProto.toString; + +/** Used to infer the `Object` constructor. */ +var objectCtorString = funcToString.call(Object); + +/** Used to detect if a method is native. */ +var reIsNative = RegExp('^' + + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' +); + +/** Built-in value references. */ +var Buffer = moduleExports ? root.Buffer : undefined, + Symbol = root.Symbol, + Uint8Array = root.Uint8Array, + allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined, + getPrototype = overArg(Object.getPrototypeOf, Object), + objectCreate = Object.create, + propertyIsEnumerable = objectProto.propertyIsEnumerable, + splice = arrayProto.splice, + symToStringTag = Symbol ? Symbol.toStringTag : undefined; + +var defineProperty = (function() { + try { + var func = getNative(Object, 'defineProperty'); + func({}, '', {}); + return func; + } catch (e) {} +}()); + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, + nativeMax = Math.max, + nativeNow = Date.now; + +/* Built-in method references that are verified to be native. */ +var Map = getNative(root, 'Map'), + nativeCreate = getNative(Object, 'create'); + +/** + * The base implementation of `_.create` without support for assigning + * properties to the created object. + * + * @private + * @param {Object} proto The object to inherit from. + * @returns {Object} Returns the new object. + */ +var baseCreate = (function() { + function object() {} + return function(proto) { + if (!isObject(proto)) { + return {}; + } + if (objectCreate) { + return objectCreate(proto); + } + object.prototype = proto; + var result = new object; + object.prototype = undefined; + return result; + }; +}()); + +/** + * Creates a hash object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function Hash(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} + +/** + * Removes all key-value entries from the hash. + * + * @private + * @name clear + * @memberOf Hash + */ +function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; + this.size = 0; +} + +/** + * Removes `key` and its value from the hash. + * + * @private + * @name delete + * @memberOf Hash + * @param {Object} hash The hash to modify. + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function hashDelete(key) { + var result = this.has(key) && delete this.__data__[key]; + this.size -= result ? 1 : 0; + return result; +} + +/** + * Gets the hash value for `key`. + * + * @private + * @name get + * @memberOf Hash + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? undefined : result; + } + return hasOwnProperty.call(data, key) ? data[key] : undefined; +} + +/** + * Checks if a hash value for `key` exists. + * + * @private + * @name has + * @memberOf Hash + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function hashHas(key) { + var data = this.__data__; + return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); +} + +/** + * Sets the hash `key` to `value`. + * + * @private + * @name set + * @memberOf Hash + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the hash instance. + */ +function hashSet(key, value) { + var data = this.__data__; + this.size += this.has(key) ? 0 : 1; + data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; + return this; +} + +// Add methods to `Hash`. +Hash.prototype.clear = hashClear; +Hash.prototype['delete'] = hashDelete; +Hash.prototype.get = hashGet; +Hash.prototype.has = hashHas; +Hash.prototype.set = hashSet; + +/** + * Creates an list cache object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function ListCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} + +/** + * Removes all key-value entries from the list cache. + * + * @private + * @name clear + * @memberOf ListCache + */ +function listCacheClear() { + this.__data__ = []; + this.size = 0; +} + +/** + * Removes `key` and its value from the list cache. + * + * @private + * @name delete + * @memberOf ListCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function listCacheDelete(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + return false; + } + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); + } + --this.size; + return true; +} + +/** + * Gets the list cache value for `key`. + * + * @private + * @name get + * @memberOf ListCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function listCacheGet(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + return index < 0 ? undefined : data[index][1]; +} + +/** + * Checks if a list cache value for `key` exists. + * + * @private + * @name has + * @memberOf ListCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; +} + +/** + * Sets the list cache `key` to `value`. + * + * @private + * @name set + * @memberOf ListCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the list cache instance. + */ +function listCacheSet(key, value) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + ++this.size; + data.push([key, value]); + } else { + data[index][1] = value; + } + return this; +} + +// Add methods to `ListCache`. +ListCache.prototype.clear = listCacheClear; +ListCache.prototype['delete'] = listCacheDelete; +ListCache.prototype.get = listCacheGet; +ListCache.prototype.has = listCacheHas; +ListCache.prototype.set = listCacheSet; + +/** + * Creates a map cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function MapCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} + +/** + * Removes all key-value entries from the map. + * + * @private + * @name clear + * @memberOf MapCache + */ +function mapCacheClear() { + this.size = 0; + this.__data__ = { + 'hash': new Hash, + 'map': new (Map || ListCache), + 'string': new Hash + }; +} + +/** + * Removes `key` and its value from the map. + * + * @private + * @name delete + * @memberOf MapCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function mapCacheDelete(key) { + var result = getMapData(this, key)['delete'](key); + this.size -= result ? 1 : 0; + return result; +} + +/** + * Gets the map value for `key`. + * + * @private + * @name get + * @memberOf MapCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function mapCacheGet(key) { + return getMapData(this, key).get(key); +} + +/** + * Checks if a map value for `key` exists. + * + * @private + * @name has + * @memberOf MapCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function mapCacheHas(key) { + return getMapData(this, key).has(key); +} + +/** + * Sets the map `key` to `value`. + * + * @private + * @name set + * @memberOf MapCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the map cache instance. + */ +function mapCacheSet(key, value) { + var data = getMapData(this, key), + size = data.size; + + data.set(key, value); + this.size += data.size == size ? 0 : 1; + return this; +} + +// Add methods to `MapCache`. +MapCache.prototype.clear = mapCacheClear; +MapCache.prototype['delete'] = mapCacheDelete; +MapCache.prototype.get = mapCacheGet; +MapCache.prototype.has = mapCacheHas; +MapCache.prototype.set = mapCacheSet; + +/** + * Creates a stack cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function Stack(entries) { + var data = this.__data__ = new ListCache(entries); + this.size = data.size; +} + +/** + * Removes all key-value entries from the stack. + * + * @private + * @name clear + * @memberOf Stack + */ +function stackClear() { + this.__data__ = new ListCache; + this.size = 0; +} + +/** + * Removes `key` and its value from the stack. + * + * @private + * @name delete + * @memberOf Stack + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function stackDelete(key) { + var data = this.__data__, + result = data['delete'](key); + + this.size = data.size; + return result; +} + +/** + * Gets the stack value for `key`. + * + * @private + * @name get + * @memberOf Stack + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function stackGet(key) { + return this.__data__.get(key); +} + +/** + * Checks if a stack value for `key` exists. + * + * @private + * @name has + * @memberOf Stack + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function stackHas(key) { + return this.__data__.has(key); +} + +/** + * Sets the stack `key` to `value`. + * + * @private + * @name set + * @memberOf Stack + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the stack cache instance. + */ +function stackSet(key, value) { + var data = this.__data__; + if (data instanceof ListCache) { + var pairs = data.__data__; + if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { + pairs.push([key, value]); + this.size = ++data.size; + return this; + } + data = this.__data__ = new MapCache(pairs); + } + data.set(key, value); + this.size = data.size; + return this; +} + +// Add methods to `Stack`. +Stack.prototype.clear = stackClear; +Stack.prototype['delete'] = stackDelete; +Stack.prototype.get = stackGet; +Stack.prototype.has = stackHas; +Stack.prototype.set = stackSet; + +/** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ +function arrayLikeKeys(value, inherited) { + var isArr = isArray(value), + isArg = !isArr && isArguments(value), + isBuff = !isArr && !isArg && isBuffer(value), + isType = !isArr && !isArg && !isBuff && isTypedArray(value), + skipIndexes = isArr || isArg || isBuff || isType, + result = skipIndexes ? baseTimes(value.length, String) : [], + length = result.length; + + for (var key in value) { + if ((inherited || hasOwnProperty.call(value, key)) && + !(skipIndexes && ( + // Safari 9 has enumerable `arguments.length` in strict mode. + key == 'length' || + // Node.js 0.10 has enumerable non-index properties on buffers. + (isBuff && (key == 'offset' || key == 'parent')) || + // PhantomJS 2 has enumerable non-index properties on typed arrays. + (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || + // Skip index properties. + isIndex(key, length) + ))) { + result.push(key); + } + } + return result; +} + +/** + * This function is like `assignValue` except that it doesn't assign + * `undefined` values. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ +function assignMergeValue(object, key, value) { + if ((value !== undefined && !eq(object[key], value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); + } +} + +/** + * Assigns `value` to `key` of `object` if the existing value is not equivalent + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ +function assignValue(object, key, value) { + var objValue = object[key]; + if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); + } +} + +/** + * Gets the index at which the `key` is found in `array` of key-value pairs. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} key The key to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq(array[length][0], key)) { + return length; + } + } + return -1; +} + +/** + * The base implementation of `assignValue` and `assignMergeValue` without + * value checks. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ +function baseAssignValue(object, key, value) { + if (key == '__proto__' && defineProperty) { + defineProperty(object, key, { + 'configurable': true, + 'enumerable': true, + 'value': value, + 'writable': true + }); + } else { + object[key] = value; + } +} + +/** + * The base implementation of `baseForOwn` which iterates over `object` + * properties returned by `keysFunc` and invokes `iteratee` for each property. + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ +var baseFor = createBaseFor(); + +/** + * The base implementation of `getTag` without fallbacks for buggy environments. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ +function baseGetTag(value) { + if (value == null) { + return value === undefined ? undefinedTag : nullTag; + } + return (symToStringTag && symToStringTag in Object(value)) + ? getRawTag(value) + : objectToString(value); +} + +/** + * The base implementation of `_.isArguments`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + */ +function baseIsArguments(value) { + return isObjectLike(value) && baseGetTag(value) == argsTag; +} + +/** + * The base implementation of `_.isNative` without bad shim checks. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + */ +function baseIsNative(value) { + if (!isObject(value) || isMasked(value)) { + return false; + } + var pattern = isFunction(value) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value)); +} + +/** + * The base implementation of `_.isTypedArray` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + */ +function baseIsTypedArray(value) { + return isObjectLike(value) && + isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; +} + +/** + * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ +function baseKeysIn(object) { + if (!isObject(object)) { + return nativeKeysIn(object); + } + var isProto = isPrototype(object), + result = []; + + for (var key in object) { + if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { + result.push(key); + } + } + return result; +} + +/** + * The base implementation of `_.merge` without support for multiple sources. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {number} srcIndex The index of `source`. + * @param {Function} [customizer] The function to customize merged values. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + */ +function baseMerge(object, source, srcIndex, customizer, stack) { + if (object === source) { + return; + } + baseFor(source, function(srcValue, key) { + stack || (stack = new Stack); + if (isObject(srcValue)) { + baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); + } + else { + var newValue = customizer + ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack) + : undefined; + + if (newValue === undefined) { + newValue = srcValue; + } + assignMergeValue(object, key, newValue); + } + }, keysIn); +} + +/** + * A specialized version of `baseMerge` for arrays and objects which performs + * deep merges and tracks traversed objects enabling objects with circular + * references to be merged. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {string} key The key of the value to merge. + * @param {number} srcIndex The index of `source`. + * @param {Function} mergeFunc The function to merge values. + * @param {Function} [customizer] The function to customize assigned values. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + */ +function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { + var objValue = safeGet(object, key), + srcValue = safeGet(source, key), + stacked = stack.get(srcValue); + + if (stacked) { + assignMergeValue(object, key, stacked); + return; + } + var newValue = customizer + ? customizer(objValue, srcValue, (key + ''), object, source, stack) + : undefined; + + var isCommon = newValue === undefined; + + if (isCommon) { + var isArr = isArray(srcValue), + isBuff = !isArr && isBuffer(srcValue), + isTyped = !isArr && !isBuff && isTypedArray(srcValue); + + newValue = srcValue; + if (isArr || isBuff || isTyped) { + if (isArray(objValue)) { + newValue = objValue; + } + else if (isArrayLikeObject(objValue)) { + newValue = copyArray(objValue); + } + else if (isBuff) { + isCommon = false; + newValue = cloneBuffer(srcValue, true); + } + else if (isTyped) { + isCommon = false; + newValue = cloneTypedArray(srcValue, true); + } + else { + newValue = []; + } + } + else if (isPlainObject(srcValue) || isArguments(srcValue)) { + newValue = objValue; + if (isArguments(objValue)) { + newValue = toPlainObject(objValue); + } + else if (!isObject(objValue) || isFunction(objValue)) { + newValue = initCloneObject(srcValue); + } + } + else { + isCommon = false; + } + } + if (isCommon) { + // Recursively merge objects and arrays (susceptible to call stack limits). + stack.set(srcValue, newValue); + mergeFunc(newValue, srcValue, srcIndex, customizer, stack); + stack['delete'](srcValue); + } + assignMergeValue(object, key, newValue); +} + +/** + * The base implementation of `_.rest` which doesn't validate or coerce arguments. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + */ +function baseRest(func, start) { + return setToString(overRest(func, start, identity), func + ''); +} + +/** + * The base implementation of `setToString` without support for hot loop shorting. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ +var baseSetToString = !defineProperty ? identity : function(func, string) { + return defineProperty(func, 'toString', { + 'configurable': true, + 'enumerable': false, + 'value': constant(string), + 'writable': true + }); +}; + +/** + * Creates a clone of `buffer`. + * + * @private + * @param {Buffer} buffer The buffer to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Buffer} Returns the cloned buffer. + */ +function cloneBuffer(buffer, isDeep) { + if (isDeep) { + return buffer.slice(); + } + var length = buffer.length, + result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); + + buffer.copy(result); + return result; +} + +/** + * Creates a clone of `arrayBuffer`. + * + * @private + * @param {ArrayBuffer} arrayBuffer The array buffer to clone. + * @returns {ArrayBuffer} Returns the cloned array buffer. + */ +function cloneArrayBuffer(arrayBuffer) { + var result = new arrayBuffer.constructor(arrayBuffer.byteLength); + new Uint8Array(result).set(new Uint8Array(arrayBuffer)); + return result; +} + +/** + * Creates a clone of `typedArray`. + * + * @private + * @param {Object} typedArray The typed array to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned typed array. + */ +function cloneTypedArray(typedArray, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; + return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); +} + +/** + * Copies the values of `source` to `array`. + * + * @private + * @param {Array} source The array to copy values from. + * @param {Array} [array=[]] The array to copy values to. + * @returns {Array} Returns `array`. + */ +function copyArray(source, array) { + var index = -1, + length = source.length; + + array || (array = Array(length)); + while (++index < length) { + array[index] = source[index]; + } + return array; +} + +/** + * Copies properties of `source` to `object`. + * + * @private + * @param {Object} source The object to copy properties from. + * @param {Array} props The property identifiers to copy. + * @param {Object} [object={}] The object to copy properties to. + * @param {Function} [customizer] The function to customize copied values. + * @returns {Object} Returns `object`. + */ +function copyObject(source, props, object, customizer) { + var isNew = !object; + object || (object = {}); + + var index = -1, + length = props.length; + + while (++index < length) { + var key = props[index]; + + var newValue = customizer + ? customizer(object[key], source[key], key, object, source) + : undefined; + + if (newValue === undefined) { + newValue = source[key]; + } + if (isNew) { + baseAssignValue(object, key, newValue); + } else { + assignValue(object, key, newValue); + } + } + return object; +} + +/** + * Creates a function like `_.assign`. + * + * @private + * @param {Function} assigner The function to assign values. + * @returns {Function} Returns the new assigner function. + */ +function createAssigner(assigner) { + return baseRest(function(object, sources) { + var index = -1, + length = sources.length, + customizer = length > 1 ? sources[length - 1] : undefined, + guard = length > 2 ? sources[2] : undefined; + + customizer = (assigner.length > 3 && typeof customizer == 'function') + ? (length--, customizer) + : undefined; + + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + customizer = length < 3 ? undefined : customizer; + length = 1; + } + object = Object(object); + while (++index < length) { + var source = sources[index]; + if (source) { + assigner(object, source, index, customizer); + } + } + return object; + }); +} + +/** + * Creates a base function for methods like `_.forIn` and `_.forOwn`. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ +function createBaseFor(fromRight) { + return function(object, iteratee, keysFunc) { + var index = -1, + iterable = Object(object), + props = keysFunc(object), + length = props.length; + + while (length--) { + var key = props[fromRight ? length : ++index]; + if (iteratee(iterable[key], key, iterable) === false) { + break; + } + } + return object; + }; +} + +/** + * Gets the data for `map`. + * + * @private + * @param {Object} map The map to query. + * @param {string} key The reference key. + * @returns {*} Returns the map data. + */ +function getMapData(map, key) { + var data = map.__data__; + return isKeyable(key) + ? data[typeof key == 'string' ? 'string' : 'hash'] + : data.map; +} + +/** + * Gets the native function at `key` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. + */ +function getNative(object, key) { + var value = getValue(object, key); + return baseIsNative(value) ? value : undefined; +} + +/** + * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the raw `toStringTag`. + */ +function getRawTag(value) { + var isOwn = hasOwnProperty.call(value, symToStringTag), + tag = value[symToStringTag]; + + try { + value[symToStringTag] = undefined; + var unmasked = true; + } catch (e) {} + + var result = nativeObjectToString.call(value); + if (unmasked) { + if (isOwn) { + value[symToStringTag] = tag; + } else { + delete value[symToStringTag]; + } + } + return result; +} + +/** + * Initializes an object clone. + * + * @private + * @param {Object} object The object to clone. + * @returns {Object} Returns the initialized clone. + */ +function initCloneObject(object) { + return (typeof object.constructor == 'function' && !isPrototype(object)) + ? baseCreate(getPrototype(object)) + : {}; +} + +/** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ +function isIndex(value, length) { + var type = typeof value; + length = length == null ? MAX_SAFE_INTEGER : length; + + return !!length && + (type == 'number' || + (type != 'symbol' && reIsUint.test(value))) && + (value > -1 && value % 1 == 0 && value < length); +} + +/** + * Checks if the given arguments are from an iteratee call. + * + * @private + * @param {*} value The potential iteratee value argument. + * @param {*} index The potential iteratee index or key argument. + * @param {*} object The potential iteratee object argument. + * @returns {boolean} Returns `true` if the arguments are from an iteratee call, + * else `false`. + */ +function isIterateeCall(value, index, object) { + if (!isObject(object)) { + return false; + } + var type = typeof index; + if (type == 'number' + ? (isArrayLike(object) && isIndex(index, object.length)) + : (type == 'string' && index in object) + ) { + return eq(object[index], value); + } + return false; +} + +/** + * Checks if `value` is suitable for use as unique object key. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + */ +function isKeyable(value) { + var type = typeof value; + return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') + ? (value !== '__proto__') + : (value === null); +} + +/** + * Checks if `func` has its source masked. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. + */ +function isMasked(func) { + return !!maskSrcKey && (maskSrcKey in func); +} + +/** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ +function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; + + return value === proto; +} + +/** + * This function is like + * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * except that it includes inherited enumerable properties. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ +function nativeKeysIn(object) { + var result = []; + if (object != null) { + for (var key in Object(object)) { + result.push(key); + } + } + return result; +} + +/** + * Converts `value` to a string using `Object.prototype.toString`. + * + * @private + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + */ +function objectToString(value) { + return nativeObjectToString.call(value); +} + +/** + * A specialized version of `baseRest` which transforms the rest array. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @param {Function} transform The rest array transform. + * @returns {Function} Returns the new function. + */ +function overRest(func, start, transform) { + start = nativeMax(start === undefined ? (func.length - 1) : start, 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + array = Array(length); + + while (++index < length) { + array[index] = args[start + index]; + } + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = transform(array); + return apply(func, this, otherArgs); + }; +} + +/** + * Gets the value at `key`, unless `key` is "__proto__" or "constructor". + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ +function safeGet(object, key) { + if (key === 'constructor' && typeof object[key] === 'function') { + return; + } + + if (key == '__proto__') { + return; + } + + return object[key]; +} + +/** + * Sets the `toString` method of `func` to return `string`. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ +var setToString = shortOut(baseSetToString); + +/** + * Creates a function that'll short out and invoke `identity` instead + * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` + * milliseconds. + * + * @private + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new shortable function. + */ +function shortOut(func) { + var count = 0, + lastCalled = 0; + + return function() { + var stamp = nativeNow(), + remaining = HOT_SPAN - (stamp - lastCalled); + + lastCalled = stamp; + if (remaining > 0) { + if (++count >= HOT_COUNT) { + return arguments[0]; + } + } else { + count = 0; + } + return func.apply(undefined, arguments); + }; +} + +/** + * Converts `func` to its source code. + * + * @private + * @param {Function} func The function to convert. + * @returns {string} Returns the source code. + */ +function toSource(func) { + if (func != null) { + try { + return funcToString.call(func); + } catch (e) {} + try { + return (func + ''); + } catch (e) {} + } + return ''; +} + +/** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ +function eq(value, other) { + return value === other || (value !== value && other !== other); +} + +/** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ +var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { + return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && + !propertyIsEnumerable.call(value, 'callee'); +}; + +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; + +/** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ +function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); +} + +/** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ +function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); +} + +/** + * Checks if `value` is a buffer. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. + * @example + * + * _.isBuffer(new Buffer(2)); + * // => true + * + * _.isBuffer(new Uint8Array(2)); + * // => false + */ +var isBuffer = nativeIsBuffer || stubFalse; + +/** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ +function isFunction(value) { + if (!isObject(value)) { + return false; + } + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 9 which returns 'object' for typed arrays and other constructors. + var tag = baseGetTag(value); + return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; +} + +/** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ +function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; +} + +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return value != null && (type == 'object' || type == 'function'); +} + +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return value != null && typeof value == 'object'; +} + +/** + * Checks if `value` is a plain object, that is, an object created by the + * `Object` constructor or one with a `[[Prototype]]` of `null`. + * + * @static + * @memberOf _ + * @since 0.8.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * _.isPlainObject(new Foo); + * // => false + * + * _.isPlainObject([1, 2, 3]); + * // => false + * + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true + * + * _.isPlainObject(Object.create(null)); + * // => true + */ +function isPlainObject(value) { + if (!isObjectLike(value) || baseGetTag(value) != objectTag) { + return false; + } + var proto = getPrototype(value); + if (proto === null) { + return true; + } + var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; + return typeof Ctor == 'function' && Ctor instanceof Ctor && + funcToString.call(Ctor) == objectCtorString; +} + +/** + * Checks if `value` is classified as a typed array. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + * @example + * + * _.isTypedArray(new Uint8Array); + * // => true + * + * _.isTypedArray([]); + * // => false + */ +var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; + +/** + * Converts `value` to a plain object flattening inherited enumerable string + * keyed properties of `value` to own properties of the plain object. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {Object} Returns the converted plain object. + * @example + * + * function Foo() { + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.assign({ 'a': 1 }, new Foo); + * // => { 'a': 1, 'b': 2 } + * + * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); + * // => { 'a': 1, 'b': 2, 'c': 3 } + */ +function toPlainObject(value) { + return copyObject(value, keysIn(value)); +} + +/** + * Creates an array of the own and inherited enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keysIn(new Foo); + * // => ['a', 'b', 'c'] (iteration order is not guaranteed) + */ +function keysIn(object) { + return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); +} + +/** + * This method is like `_.assign` except that it recursively merges own and + * inherited enumerable string keyed properties of source objects into the + * destination object. Source properties that resolve to `undefined` are + * skipped if a destination value exists. Array and plain object properties + * are merged recursively. Other objects and value types are overridden by + * assignment. Source objects are applied from left to right. Subsequent + * sources overwrite property assignments of previous sources. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @example + * + * var object = { + * 'a': [{ 'b': 2 }, { 'd': 4 }] + * }; + * + * var other = { + * 'a': [{ 'c': 3 }, { 'e': 5 }] + * }; + * + * _.merge(object, other); + * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } + */ +var merge = createAssigner(function(object, source, srcIndex) { + baseMerge(object, source, srcIndex); +}); + +/** + * Creates a function that returns `value`. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Util + * @param {*} value The value to return from the new function. + * @returns {Function} Returns the new constant function. + * @example + * + * var objects = _.times(2, _.constant({ 'a': 1 })); + * + * console.log(objects); + * // => [{ 'a': 1 }, { 'a': 1 }] + * + * console.log(objects[0] === objects[1]); + * // => true + */ +function constant(value) { + return function() { + return value; + }; +} + +/** + * This method returns the first argument it receives. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @param {*} value Any value. + * @returns {*} Returns `value`. + * @example + * + * var object = { 'a': 1 }; + * + * console.log(_.identity(object) === object); + * // => true + */ +function identity(value) { + return value; +} + +/** + * This method returns `false`. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {boolean} Returns `false`. + * @example + * + * _.times(2, _.stubFalse); + * // => [false, false] + */ +function stubFalse() { + return false; +} + +module.exports = merge; + + +/***/ }), + +/***/ 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; +}; + + +/***/ }), + +/***/ 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++, //