diff --git a/README.md b/README.md index 438629e..40e7988 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ You can use the generated QR Code anywhere - upload to slack, commit to git, etc ## Usage ```yaml -uses: snow-actions/qrcode@v1.0.0 +uses: snow-actions/qrcode@v1.1.0 with: text: 'https://github.com/snow-actions/qrcode' path: 'qrcode.png' @@ -30,7 +30,7 @@ jobs: - uses: actions/checkout@v4 with: ref: qrcode - - uses: snow-actions/qrcode@v1.0.0 + - uses: snow-actions/qrcode@v1.1.0 with: text: https://github.com/snow-actions/qrcode path: qrcode.png diff --git a/dist/index.js b/dist/index.js index c917f63..b17c5b2 100644 --- a/dist/index.js +++ b/dist/index.js @@ -1,548 +1,473 @@ -module.exports = -/******/ (function(modules, runtime) { // webpackBootstrap -/******/ "use strict"; -/******/ // The module cache -/******/ var installedModules = {}; -/******/ -/******/ // The require function -/******/ function __webpack_require__(moduleId) { -/******/ -/******/ // Check if module is in cache -/******/ if(installedModules[moduleId]) { -/******/ return installedModules[moduleId].exports; -/******/ } -/******/ // Create a new module (and put it into the cache) -/******/ var module = installedModules[moduleId] = { -/******/ i: moduleId, -/******/ l: false, -/******/ exports: {} -/******/ }; -/******/ -/******/ // Execute the module function -/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); -/******/ -/******/ // Flag the module as loaded -/******/ module.l = true; -/******/ -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } -/******/ -/******/ -/******/ __webpack_require__.ab = __dirname + "/"; -/******/ -/******/ // the startup function -/******/ function startup() { -/******/ // Load entry module and return exports -/******/ return __webpack_require__(104); -/******/ }; -/******/ -/******/ // run startup -/******/ return startup(); -/******/ }) -/************************************************************************/ -/******/ ({ +/******/ (() => { // webpackBootstrap +/******/ var __webpack_modules__ = ({ -/***/ 4: -/***/ (function(__unusedmodule, exports) { +/***/ 4914: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true +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; }); -exports.default = void 0; -var _default = '00000000-0000-0000-0000-000000000000'; -exports.default = _default; - -/***/ }), - -/***/ 16: -/***/ (function(module) { - -module.exports = require("tls"); - -/***/ }), - -/***/ 24: -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - - - -var parse = __webpack_require__(657); -var pack = __webpack_require__(129); - - -exports.read = function(buffer, options) { - - return parse(buffer, options || {}); -}; - -exports.write = function(png, options) { - - return pack(png, options); +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; }; - - -/***/ }), - -/***/ 25: -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -Object.defineProperty(exports, "v1", { - enumerable: true, - get: function () { - return _v.default; - } -}); -Object.defineProperty(exports, "v3", { - enumerable: true, - get: function () { - return _v2.default; - } -}); -Object.defineProperty(exports, "v4", { - enumerable: true, - get: function () { - return _v3.default; - } -}); -Object.defineProperty(exports, "v5", { - enumerable: true, - get: function () { - return _v4.default; - } -}); -Object.defineProperty(exports, "NIL", { - enumerable: true, - get: function () { - return _nil.default; - } -}); -Object.defineProperty(exports, "version", { - enumerable: true, - get: function () { - return _version.default; - } -}); -Object.defineProperty(exports, "validate", { - enumerable: true, - get: function () { - return _validate.default; - } -}); -Object.defineProperty(exports, "stringify", { - enumerable: true, - get: function () { - return _stringify.default; - } -}); -Object.defineProperty(exports, "parse", { - enumerable: true, - get: function () { - return _parse.default; - } -}); - -var _v = _interopRequireDefault(__webpack_require__(810)); - -var _v2 = _interopRequireDefault(__webpack_require__(572)); - -var _v3 = _interopRequireDefault(__webpack_require__(293)); - -var _v4 = _interopRequireDefault(__webpack_require__(638)); - -var _nil = _interopRequireDefault(__webpack_require__(4)); - -var _version = _interopRequireDefault(__webpack_require__(135)); - -var _validate = _interopRequireDefault(__webpack_require__(634)); - -var _stringify = _interopRequireDefault(__webpack_require__(960)); - -var _parse = _interopRequireDefault(__webpack_require__(204)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/***/ }), - -/***/ 50: -/***/ (function(__unusedmodule, exports) { - -exports.L = { bit: 1 } -exports.M = { bit: 0 } -exports.Q = { bit: 3 } -exports.H = { bit: 2 } - -function fromString (string) { - if (typeof string !== 'string') { - throw new Error('Param is not a string') - } - - var lcStr = string.toLowerCase() - - switch (lcStr) { - case 'l': - case 'low': - return exports.L - - case 'm': - case 'medium': - return exports.M - - case 'q': - case 'quartile': - return exports.Q - - case 'h': - case 'high': - return exports.H - - default: - throw new Error('Unknown EC Level: ' + string) - } -} - -exports.isValid = function isValid (level) { - return level && typeof level.bit !== 'undefined' && - level.bit >= 0 && level.bit < 4 -} - -exports.from = function from (value, defaultValue) { - if (exports.isValid(value)) { - return value - } - - try { - return fromString(value) - } catch (e) { - return defaultValue - } -} - - -/***/ }), - -/***/ 54: -/***/ (function(__unusedmodule, exports) { - +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.issue = exports.issueCommand = void 0; +const os = __importStar(__nccwpck_require__(857)); +const utils_1 = __nccwpck_require__(302); /** - * Check if QR Code version is valid + * Commands * - * @param {Number} version QR Code version - * @return {Boolean} true if valid version, false otherwise + * Command Format: + * ::name key=value,key=value::message + * + * Examples: + * ::warning::This is the message + * ::set-env name=MY_VAR::some value */ -exports.isValid = function isValid (version) { - return !isNaN(version) && version >= 1 && version <= 40 +function issueCommand(command, properties, message) { + const cmd = new Command(command, properties, message); + process.stdout.write(cmd.toString() + os.EOL); } - +exports.issueCommand = issueCommand; +function issue(name, message = '') { + issueCommand(name, {}, message); +} +exports.issue = issue; +const CMD_STRING = '::'; +class Command { + constructor(command, properties, message) { + if (!command) { + command = 'missing.command'; + } + this.command = command; + this.properties = properties; + this.message = message; + } + toString() { + let cmdStr = CMD_STRING + this.command; + if (this.properties && Object.keys(this.properties).length > 0) { + cmdStr += ' '; + let first = true; + for (const key in this.properties) { + if (this.properties.hasOwnProperty(key)) { + const val = this.properties[key]; + if (val) { + if (first) { + first = false; + } + else { + cmdStr += ','; + } + cmdStr += `${key}=${escapeProperty(val)}`; + } + } + } + } + cmdStr += `${CMD_STRING}${escapeData(this.message)}`; + return cmdStr; + } +} +function escapeData(s) { + return (0, utils_1.toCommandValue)(s) + .replace(/%/g, '%25') + .replace(/\r/g, '%0D') + .replace(/\n/g, '%0A'); +} +function escapeProperty(s) { + return (0, utils_1.toCommandValue)(s) + .replace(/%/g, '%25') + .replace(/\r/g, '%0D') + .replace(/\n/g, '%0A') + .replace(/:/g, '%3A') + .replace(/,/g, '%2C'); +} +//# sourceMappingURL=command.js.map /***/ }), -/***/ 80: -/***/ (function(module) { +/***/ 7484: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var SyncReader = module.exports = function(buffer) { - - this._buffer = buffer; - this._reads = []; +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; }; - -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 - }); +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; - -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)); - +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.platform = exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = exports.markdownSummary = exports.summary = 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__(4914); +const file_command_1 = __nccwpck_require__(4753); +const utils_1 = __nccwpck_require__(302); +const os = __importStar(__nccwpck_require__(857)); +const path = __importStar(__nccwpck_require__(6928)); +const oidc_utils_1 = __nccwpck_require__(5306); +/** + * The code to exit an action + */ +var ExitCode; +(function (ExitCode) { + /** + * A code indicating that the action was successful + */ + ExitCode[ExitCode["Success"] = 0] = "Success"; + /** + * A code indicating that the action was a failure + */ + ExitCode[ExitCode["Failure"] = 1] = "Failure"; +})(ExitCode || (exports.ExitCode = ExitCode = {})); +//----------------------------------------------------------------------- +// Variables +//----------------------------------------------------------------------- +/** + * Sets env variable for this action and future actions in the job + * @param name the name of the variable to set + * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function exportVariable(name, val) { + const convertedVal = (0, utils_1.toCommandValue)(val); + process.env[name] = convertedVal; + const filePath = process.env['GITHUB_ENV'] || ''; + if (filePath) { + return (0, file_command_1.issueFileCommand)('ENV', (0, file_command_1.prepareKeyValueMessage)(name, val)); + } + (0, command_1.issueCommand)('set-env', { name }, convertedVal); +} +exports.exportVariable = exportVariable; +/** + * Registers a secret which will get masked from logs + * @param secret value of the secret + */ +function setSecret(secret) { + (0, command_1.issueCommand)('add-mask', {}, secret); +} +exports.setSecret = setSecret; +/** + * Prepends inputPath to the PATH (for this action and future actions) + * @param inputPath + */ +function addPath(inputPath) { + const filePath = process.env['GITHUB_PATH'] || ''; + if (filePath) { + (0, file_command_1.issueFileCommand)('PATH', inputPath); } else { - break; + (0, command_1.issueCommand)('add-path', {}, inputPath); } - - } - - 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'); - } - -}; - - -/***/ }), - -/***/ 82: -/***/ (function(__unusedmodule, exports) { - -"use strict"; - -// We use any as a valid input type -/* eslint-disable @typescript-eslint/no-explicit-any */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.toCommandProperties = exports.toCommandValue = void 0; + process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; +} +exports.addPath = addPath; /** - * Sanitizes an input into a string so it can be passed into issueCommand safely - * @param input input to sanitize into a string + * Gets the value of an input. + * Unless trimWhitespace is set to false in InputOptions, the value is also trimmed. + * Returns an empty string if the value is not defined. + * + * @param name name of the input to get + * @param options optional. See InputOptions. + * @returns string */ -function toCommandValue(input) { - if (input === null || input === undefined) { - return ''; +function getInput(name, options) { + const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || ''; + if (options && options.required && !val) { + throw new Error(`Input required and not supplied: ${name}`); } - else if (typeof input === 'string' || input instanceof String) { - return input; + if (options && options.trimWhitespace === false) { + return val; } - return JSON.stringify(input); + return val.trim(); } -exports.toCommandValue = toCommandValue; +exports.getInput = getInput; /** + * Gets the values of an multiline input. Each value is also trimmed. + * + * @param name name of the input to get + * @param options optional. See InputOptions. + * @returns string[] * - * @param annotationProperties - * @returns The command properties to send with the actual annotation command - * See IssueCommandProperties: https://github.com/actions/runner/blob/main/src/Runner.Worker/ActionCommandManager.cs#L646 */ -function toCommandProperties(annotationProperties) { - if (!Object.keys(annotationProperties).length) { - return {}; +function getMultilineInput(name, options) { + const inputs = getInput(name, options) + .split('\n') + .filter(x => x !== ''); + if (options && options.trimWhitespace === false) { + return inputs; } - return { - title: annotationProperties.title, - file: annotationProperties.file, - line: annotationProperties.startLine, - endLine: annotationProperties.endLine, - col: annotationProperties.startColumn, - endColumn: annotationProperties.endColumn - }; + return inputs.map(input => input.trim()); } -exports.toCommandProperties = toCommandProperties; -//# sourceMappingURL=utils.js.map - -/***/ }), - -/***/ 83: -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; - - -var util = __webpack_require__(669); -var Stream = __webpack_require__(794); -var constants = __webpack_require__(268); -var Packer = __webpack_require__(116); - -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); -}; - - -/***/ }), - -/***/ 87: -/***/ (function(module) { - -module.exports = require("os"); - -/***/ }), - -/***/ 93: -/***/ (function(module) { - -/* Node.js 6.4.0 and up has full support */ -var hasFullSupport = (function () { - try { - if (!Buffer.isEncoding('latin1')) { - return false +exports.getMultilineInput = getMultilineInput; +/** + * Gets the input value of the boolean type in the YAML 1.2 "core schema" specification. + * Support boolean input list: `true | True | TRUE | false | False | FALSE` . + * The return value is also in boolean type. + * ref: https://yaml.org/spec/1.2/spec.html#id2804923 + * + * @param name name of the input to get + * @param options optional. See InputOptions. + * @returns boolean + */ +function getBooleanInput(name, options) { + const trueValue = ['true', 'True', 'TRUE']; + const falseValue = ['false', 'False', 'FALSE']; + const val = getInput(name, options); + if (trueValue.includes(val)) + return true; + if (falseValue.includes(val)) + return false; + throw new TypeError(`Input does not meet YAML 1.2 "Core Schema" specification: ${name}\n` + + `Support boolean input list: \`true | True | TRUE | false | False | FALSE\``); +} +exports.getBooleanInput = getBooleanInput; +/** + * Sets the value of an output. + * + * @param name name of the output to set + * @param value value to store. Non-string values will be converted to a string via JSON.stringify + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function setOutput(name, value) { + const filePath = process.env['GITHUB_OUTPUT'] || ''; + if (filePath) { + return (0, file_command_1.issueFileCommand)('OUTPUT', (0, file_command_1.prepareKeyValueMessage)(name, value)); } - - var buf = Buffer.alloc ? Buffer.alloc(4) : new Buffer(4) - - buf.fill('ab', 'ucs2') - - return (buf.toString('hex') === '61006200') - } catch (_) { - return false - } -}()) - -function isSingleByte (val) { - return (val.length === 1 && val.charCodeAt(0) < 256) + process.stdout.write(os.EOL); + (0, command_1.issueCommand)('set-output', { name }, (0, utils_1.toCommandValue)(value)); } - -function fillWithNumber (buffer, val, start, end) { - if (start < 0 || end > buffer.length) { - throw new RangeError('Out of range index') - } - - start = start >>> 0 - end = end === undefined ? buffer.length : end >>> 0 - - if (end > start) { - buffer.fill(val, start, end) - } - - return buffer +exports.setOutput = setOutput; +/** + * Enables or disables the echoing of commands into stdout for the rest of the step. + * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set. + * + */ +function setCommandEcho(enabled) { + (0, command_1.issue)('echo', enabled ? 'on' : 'off'); } - -function fillWithBuffer (buffer, val, start, end) { - if (start < 0 || end > buffer.length) { - throw new RangeError('Out of range index') - } - - if (end <= start) { - return buffer - } - - start = start >>> 0 - end = end === undefined ? buffer.length : end >>> 0 - - var pos = start - var len = val.length - while (pos <= (end - len)) { - val.copy(buffer, pos) - pos += len - } - - if (pos !== end) { - val.copy(buffer, pos, 0, end - pos) - } - - return buffer +exports.setCommandEcho = setCommandEcho; +//----------------------------------------------------------------------- +// Results +//----------------------------------------------------------------------- +/** + * Sets the action status to failed. + * When the action exits it will be with an exit code of 1 + * @param message add error issue message + */ +function setFailed(message) { + process.exitCode = ExitCode.Failure; + error(message); } - -function fill (buffer, val, start, end, encoding) { - if (hasFullSupport) { - return buffer.fill(val, start, end, encoding) - } - - if (typeof val === 'number') { - return fillWithNumber(buffer, val, start, end) - } - - if (typeof val === 'string') { - if (typeof start === 'string') { - encoding = start - start = 0 - end = buffer.length - } else if (typeof end === 'string') { - encoding = end - end = buffer.length - } - - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string') - } - - if (encoding === 'latin1') { - encoding = 'binary' - } - - if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - - if (val === '') { - return fillWithNumber(buffer, 0, start, end) - } - - if (isSingleByte(val)) { - return fillWithNumber(buffer, val.charCodeAt(0), start, end) +exports.setFailed = setFailed; +//----------------------------------------------------------------------- +// Logging Commands +//----------------------------------------------------------------------- +/** + * Gets whether Actions Step Debug is on or not + */ +function isDebug() { + return process.env['RUNNER_DEBUG'] === '1'; +} +exports.isDebug = isDebug; +/** + * Writes debug message to user log + * @param message debug message + */ +function debug(message) { + (0, command_1.issueCommand)('debug', {}, message); +} +exports.debug = debug; +/** + * Adds an error issue + * @param message error issue message. Errors will be converted to string via toString() + * @param properties optional properties to add to the annotation. + */ +function error(message, properties = {}) { + (0, command_1.issueCommand)('error', (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); +} +exports.error = error; +/** + * Adds a warning issue + * @param message warning issue message. Errors will be converted to string via toString() + * @param properties optional properties to add to the annotation. + */ +function warning(message, properties = {}) { + (0, command_1.issueCommand)('warning', (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); +} +exports.warning = warning; +/** + * Adds a notice issue + * @param message notice issue message. Errors will be converted to string via toString() + * @param properties optional properties to add to the annotation. + */ +function notice(message, properties = {}) { + (0, command_1.issueCommand)('notice', (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); +} +exports.notice = notice; +/** + * Writes info to log with console.log. + * @param message info message + */ +function info(message) { + process.stdout.write(message + os.EOL); +} +exports.info = info; +/** + * Begin an output group. + * + * Output until the next `groupEnd` will be foldable in this group + * + * @param name The name of the output group + */ +function startGroup(name) { + (0, command_1.issue)('group', name); +} +exports.startGroup = startGroup; +/** + * End an output group. + */ +function endGroup() { + (0, command_1.issue)('endgroup'); +} +exports.endGroup = endGroup; +/** + * Wrap an asynchronous function call in a group. + * + * Returns the same type as the function itself. + * + * @param name The name of the group + * @param fn The function to wrap in the group + */ +function group(name, fn) { + return __awaiter(this, void 0, void 0, function* () { + startGroup(name); + let result; + try { + result = yield fn(); + } + finally { + endGroup(); + } + return result; + }); +} +exports.group = group; +//----------------------------------------------------------------------- +// Wrapper action state +//----------------------------------------------------------------------- +/** + * Saves state for current action, the state can only be retrieved by this action's post job execution. + * + * @param name name of the state to store + * @param value value to store. Non-string values will be converted to a string via JSON.stringify + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function saveState(name, value) { + const filePath = process.env['GITHUB_STATE'] || ''; + if (filePath) { + return (0, file_command_1.issueFileCommand)('STATE', (0, file_command_1.prepareKeyValueMessage)(name, value)); } - - val = new Buffer(val, encoding) - } - - if (Buffer.isBuffer(val)) { - return fillWithBuffer(buffer, val, start, end) - } - - // Other values (e.g. undefined, boolean, object) results in zero-fill - return fillWithNumber(buffer, 0, start, end) + (0, command_1.issueCommand)('save-state', { name }, (0, utils_1.toCommandValue)(value)); } - -module.exports = fill - +exports.saveState = saveState; +/** + * Gets the value of an state set by this action's main execution. + * + * @param name name of the state to get + * @returns string + */ +function getState(name) { + return process.env[`STATE_${name}`] || ''; +} +exports.getState = getState; +function getIDToken(aud) { + return __awaiter(this, void 0, void 0, function* () { + return yield oidc_utils_1.OidcClient.getIDToken(aud); + }); +} +exports.getIDToken = getIDToken; +/** + * Summary exports + */ +var summary_1 = __nccwpck_require__(1847); +Object.defineProperty(exports, "summary", ({ enumerable: true, get: function () { return summary_1.summary; } })); +/** + * @deprecated use core.summary + */ +var summary_2 = __nccwpck_require__(1847); +Object.defineProperty(exports, "markdownSummary", ({ enumerable: true, get: function () { return summary_2.markdownSummary; } })); +/** + * Path exports + */ +var path_utils_1 = __nccwpck_require__(1976); +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; } })); +/** + * Platform utilities exports + */ +exports.platform = __importStar(__nccwpck_require__(8968)); +//# sourceMappingURL=core.js.map /***/ }), -/***/ 102: -/***/ (function(__unusedmodule, exports, __webpack_require__) { +/***/ 4753: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; // For internal use, subject to change. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[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]; @@ -555,18 +480,18 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( 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.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + 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 }); +Object.defineProperty(exports, "__esModule", ({ value: true })); exports.prepareKeyValueMessage = exports.issueFileCommand = void 0; // We use any as a valid input type /* eslint-disable @typescript-eslint/no-explicit-any */ -const fs = __importStar(__webpack_require__(747)); -const os = __importStar(__webpack_require__(87)); -const uuid_1 = __webpack_require__(25); -const utils_1 = __webpack_require__(82); +const crypto = __importStar(__nccwpck_require__(6982)); +const fs = __importStar(__nccwpck_require__(9896)); +const os = __importStar(__nccwpck_require__(857)); +const utils_1 = __nccwpck_require__(302); function issueFileCommand(command, message) { const filePath = process.env[`GITHUB_${command}`]; if (!filePath) { @@ -575,14 +500,14 @@ function issueFileCommand(command, message) { if (!fs.existsSync(filePath)) { throw new Error(`Missing file at path: ${filePath}`); } - fs.appendFileSync(filePath, `${utils_1.toCommandValue(message)}${os.EOL}`, { + fs.appendFileSync(filePath, `${(0, utils_1.toCommandValue)(message)}${os.EOL}`, { encoding: 'utf8' }); } exports.issueFileCommand = issueFileCommand; function prepareKeyValueMessage(key, value) { - const delimiter = `ghadelimiter_${uuid_1.v4()}`; - const convertedValue = utils_1.toCommandValue(value); + const delimiter = `ghadelimiter_${crypto.randomUUID()}`; + const convertedValue = (0, utils_1.toCommandValue)(value); // These should realistically never happen, but just in case someone finds a // way to exploit uuid generation let's not allow keys or values that contain // the delimiter. @@ -599,3012 +524,2295 @@ exports.prepareKeyValueMessage = prepareKeyValueMessage; /***/ }), -/***/ 104: -/***/ (function(__unusedmodule, __unusedexports, __webpack_require__) { - -const core = __webpack_require__(470); -const QRCode = __webpack_require__(939); +/***/ 5306: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +"use strict"; -async function run() { - try { - const text = core.getInput('text'); - const path = core.getInput('path'); - QRCode.toString(text, { type: 'terminal' }, function (err, string) { - if (err) throw err - console.log(string) - }) - QRCode.toFile( - path, - text - ) - } - catch (error) { - core.setFailed(error.message); - } +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.OidcClient = void 0; +const http_client_1 = __nccwpck_require__(4844); +const auth_1 = __nccwpck_require__(4552); +const core_1 = __nccwpck_require__(7484); +class OidcClient { + static createHttpClient(allowRetry = true, maxRetry = 10) { + const requestOptions = { + allowRetries: allowRetry, + maxRetries: maxRetry + }; + return new http_client_1.HttpClient('actions/oidc-client', [new auth_1.BearerCredentialHandler(OidcClient.getRequestToken())], requestOptions); + } + static getRequestToken() { + const token = process.env['ACTIONS_ID_TOKEN_REQUEST_TOKEN']; + if (!token) { + throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_TOKEN env variable'); + } + return token; + } + static getIDTokenUrl() { + const runtimeUrl = process.env['ACTIONS_ID_TOKEN_REQUEST_URL']; + if (!runtimeUrl) { + throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable'); + } + return runtimeUrl; + } + static getCall(id_token_url) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + const httpclient = OidcClient.createHttpClient(); + const res = yield httpclient + .getJson(id_token_url) + .catch(error => { + throw new Error(`Failed to get ID Token. \n + Error Code : ${error.statusCode}\n + Error Message: ${error.message}`); + }); + const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value; + if (!id_token) { + throw new Error('Response json body do not have ID Token field'); + } + return id_token; + }); + } + static getIDToken(audience) { + return __awaiter(this, void 0, void 0, function* () { + try { + // New ID Token is requested from action service + let id_token_url = OidcClient.getIDTokenUrl(); + if (audience) { + const encodedAudience = encodeURIComponent(audience); + id_token_url = `${id_token_url}&audience=${encodedAudience}`; + } + (0, core_1.debug)(`ID token url is ${id_token_url}`); + const id_token = yield OidcClient.getCall(id_token_url); + (0, core_1.setSecret)(id_token); + return id_token; + } + catch (error) { + throw new Error(`Error message: ${error.message}`); + } + }); + } } - -run() - +exports.OidcClient = OidcClient; +//# sourceMappingURL=oidc-utils.js.map /***/ }), -/***/ 107: -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -var svgTagRenderer = __webpack_require__(673) - -exports.render = svgTagRenderer.render - -exports.renderToFile = function renderToFile (path, qrData, options, cb) { - if (typeof cb === 'undefined') { - cb = options - options = undefined - } - - var fs = __webpack_require__(747) - var svgTag = exports.render(qrData, options) - - var xmlStr = '' + - '' + - svgTag - - fs.writeFile(path, xmlStr, cb) -} - - -/***/ }), +/***/ 1976: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -/***/ 114: -/***/ (function(__unusedmodule, exports) { - -var toSJISFunction -var CODEWORDS_COUNT = [ - 0, // Not used - 26, 44, 70, 100, 134, 172, 196, 242, 292, 346, - 404, 466, 532, 581, 655, 733, 815, 901, 991, 1085, - 1156, 1258, 1364, 1474, 1588, 1706, 1828, 1921, 2051, 2185, - 2323, 2465, 2611, 2761, 2876, 3034, 3196, 3362, 3532, 3706 -] +"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 })); +exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = void 0; +const path = __importStar(__nccwpck_require__(6928)); /** - * Returns the QR Code size for the specified version + * toPosixPath converts the given path to the posix form. On Windows, \\ will be + * replaced with /. * - * @param {Number} version QR Code version - * @return {Number} size of QR code + * @param pth. Path to transform. + * @return string Posix path. */ -exports.getSymbolSize = function getSymbolSize (version) { - if (!version) throw new Error('"version" cannot be null or undefined') - if (version < 1 || version > 40) throw new Error('"version" should be in range from 1 to 40') - return version * 4 + 17 +function toPosixPath(pth) { + return pth.replace(/[\\]/g, '/'); } - +exports.toPosixPath = toPosixPath; /** - * Returns the total number of codewords used to store data and EC information. + * toWin32Path converts the given path to the win32 form. On Linux, / will be + * replaced with \\. * - * @param {Number} version QR Code version - * @return {Number} Data length in bits + * @param pth. Path to transform. + * @return string Win32 path. */ -exports.getSymbolTotalCodewords = function getSymbolTotalCodewords (version) { - return CODEWORDS_COUNT[version] +function toWin32Path(pth) { + return pth.replace(/[/]/g, '\\'); } - +exports.toWin32Path = toWin32Path; /** - * Encode data with Bose-Chaudhuri-Hocquenghem + * toPlatformPath converts the given path to a platform-specific path. It does + * this by replacing instances of / and \ with the platform-specific path + * separator. * - * @param {Number} data Value to encode - * @return {Number} Encoded value + * @param pth The path to platformize. + * @return string The platform-specific path. */ -exports.getBCHDigit = function (data) { - var digit = 0 - - while (data !== 0) { - digit++ - data >>>= 1 - } - - return digit -} - -exports.setToSJISFunction = function setToSJISFunction (f) { - if (typeof f !== 'function') { - throw new Error('"toSJISFunc" is not a valid function.') - } - - toSJISFunction = f -} - -exports.isKanjiModeEnabled = function () { - return typeof toSJISFunction !== 'undefined' -} - -exports.toSJIS = function toSJIS (kanji) { - return toSJISFunction(kanji) +function toPlatformPath(pth) { + return pth.replace(/[/\\]/g, path.sep); } - +exports.toPlatformPath = toPlatformPath; +//# sourceMappingURL=path-utils.js.map /***/ }), -/***/ 116: -/***/ (function(module, __unusedexports, __webpack_require__) { +/***/ 8968: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -var constants = __webpack_require__(268); -var CrcStream = __webpack_require__(228); -var bitPacker = __webpack_require__(667); -var filter = __webpack_require__(140); -var zlib = __webpack_require__(761); - -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); +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; }; - -Packer.prototype.packIEND = function() { - return this._packChunk(constants.TYPE_IEND, null); +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; - - -/***/ }), - -/***/ 129: -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; - - -var hasSyncZlib = true; -var zlib = __webpack_require__(761); -if (!zlib.deflateSync) { - hasSyncZlib = false; -} -var constants = __webpack_require__(268); -var Packer = __webpack_require__(116); - -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); +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; }; - - -/***/ }), - -/***/ 135: -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", { - value: true +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getDetails = exports.isLinux = exports.isMacOS = exports.isWindows = exports.arch = exports.platform = void 0; +const os_1 = __importDefault(__nccwpck_require__(857)); +const exec = __importStar(__nccwpck_require__(5236)); +const getWindowsInfo = () => __awaiter(void 0, void 0, void 0, function* () { + const { stdout: version } = yield exec.getExecOutput('powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Version"', undefined, { + silent: true + }); + const { stdout: name } = yield exec.getExecOutput('powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Caption"', undefined, { + silent: true + }); + return { + name: name.trim(), + version: version.trim() + }; }); -exports.default = void 0; - -var _validate = _interopRequireDefault(__webpack_require__(634)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function version(uuid) { - if (!(0, _validate.default)(uuid)) { - throw TypeError('Invalid UUID'); - } - - return parseInt(uuid.substr(14, 1), 16); +const getMacOsInfo = () => __awaiter(void 0, void 0, void 0, function* () { + var _a, _b, _c, _d; + const { stdout } = yield exec.getExecOutput('sw_vers', undefined, { + silent: true + }); + const version = (_b = (_a = stdout.match(/ProductVersion:\s*(.+)/)) === null || _a === void 0 ? void 0 : _a[1]) !== null && _b !== void 0 ? _b : ''; + const name = (_d = (_c = stdout.match(/ProductName:\s*(.+)/)) === null || _c === void 0 ? void 0 : _c[1]) !== null && _d !== void 0 ? _d : ''; + return { + name, + version + }; +}); +const getLinuxInfo = () => __awaiter(void 0, void 0, void 0, function* () { + const { stdout } = yield exec.getExecOutput('lsb_release', ['-i', '-r', '-s'], { + silent: true + }); + const [name, version] = stdout.trim().split('\n'); + return { + name, + version + }; +}); +exports.platform = os_1.default.platform(); +exports.arch = os_1.default.arch(); +exports.isWindows = exports.platform === 'win32'; +exports.isMacOS = exports.platform === 'darwin'; +exports.isLinux = exports.platform === 'linux'; +function getDetails() { + return __awaiter(this, void 0, void 0, function* () { + return Object.assign(Object.assign({}, (yield (exports.isWindows + ? getWindowsInfo() + : exports.isMacOS + ? getMacOsInfo() + : getLinuxInfo()))), { platform: exports.platform, + arch: exports.arch, + isWindows: exports.isWindows, + isMacOS: exports.isMacOS, + isLinux: exports.isLinux }); + }); } - -var _default = version; -exports.default = _default; +exports.getDetails = getDetails; +//# sourceMappingURL=platform.js.map /***/ }), -/***/ 136: -/***/ (function(__unusedmodule, exports, __webpack_require__) { +/***/ 1847: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = _default; -exports.URL = exports.DNS = void 0; - -var _stringify = _interopRequireDefault(__webpack_require__(960)); - -var _parse = _interopRequireDefault(__webpack_require__(204)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function stringToBytes(str) { - str = unescape(encodeURIComponent(str)); // UTF8 escape - - const bytes = []; - - for (let i = 0; i < str.length; ++i) { - bytes.push(str.charCodeAt(i)); - } - - return bytes; -} - -const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; -exports.DNS = DNS; -const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; -exports.URL = URL; - -function _default(name, version, hashfunc) { - function generateUUID(value, namespace, buf, offset) { - if (typeof value === 'string') { - value = stringToBytes(value); - } - - if (typeof namespace === 'string') { - namespace = (0, _parse.default)(namespace); - } - - if (namespace.length !== 16) { - throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); - } // Compute hash of namespace and value, Per 4.3 - // Future: Use spread syntax when supported on all platforms, e.g. `bytes = - // hashfunc([...namespace, ... value])` - - - let bytes = new Uint8Array(16 + value.length); - bytes.set(namespace); - bytes.set(value, namespace.length); - bytes = hashfunc(bytes); - bytes[6] = bytes[6] & 0x0f | version; - bytes[8] = bytes[8] & 0x3f | 0x80; - - if (buf) { - offset = offset || 0; - - for (let i = 0; i < 16; ++i) { - buf[offset + i] = bytes[i]; - } - - return buf; - } - - return (0, _stringify.default)(bytes); - } // Function#name is not settable on some platforms (#270) - - - try { - generateUUID.name = name; // eslint-disable-next-line no-empty - } catch (err) {} // For CommonJS default export support - - - generateUUID.DNS = DNS; - generateUUID.URL = URL; - return generateUUID; -} - -/***/ }), - -/***/ 140: -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; - - -var paethPredictor = __webpack_require__(594); - -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 +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; - -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; - } - } +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__(857); +const fs_1 = __nccwpck_require__(9896); +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'; +class Summary { + constructor() { + this._buffer = ''; } - - rawData[rawPos] = sel; - rawPos++; - filters[sel](pxData, pxPos, byteWidth, rawData, rawPos, bpp); - rawPos += byteWidth; - pxPos += byteWidth; - } - return rawData; -}; - - -/***/ }), - -/***/ 141: -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - - -var net = __webpack_require__(631); -var tls = __webpack_require__(16); -var http = __webpack_require__(605); -var https = __webpack_require__(211); -var events = __webpack_require__(614); -var assert = __webpack_require__(357); -var util = __webpack_require__(669); - - -exports.httpOverHttp = httpOverHttp; -exports.httpsOverHttp = httpsOverHttp; -exports.httpOverHttps = httpOverHttps; -exports.httpsOverHttps = httpsOverHttps; - - -function httpOverHttp(options) { - var agent = new TunnelingAgent(options); - agent.request = http.request; - return agent; -} - -function httpsOverHttp(options) { - var agent = new TunnelingAgent(options); - agent.request = http.request; - agent.createSocket = createSecureSocket; - agent.defaultPort = 443; - return agent; -} - -function httpOverHttps(options) { - var agent = new TunnelingAgent(options); - agent.request = https.request; - return agent; -} - -function httpsOverHttps(options) { - var agent = new TunnelingAgent(options); - agent.request = https.request; - agent.createSocket = createSecureSocket; - agent.defaultPort = 443; - return agent; -} - - -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 = []; - - 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; - } + /** + * Finds the summary file path from the environment, rejects if env var is not found or file does not exist + * Also checks r/w permissions. + * + * @returns step summary file path + */ + filePath() { + return __awaiter(this, void 0, void 0, function* () { + if (this._filePath) { + return this._filePath; + } + const pathFromEnv = process.env[exports.SUMMARY_ENV_VAR]; + if (!pathFromEnv) { + throw new Error(`Unable to find environment variable for $${exports.SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`); + } + try { + yield access(pathFromEnv, fs_1.constants.R_OK | fs_1.constants.W_OK); + } + catch (_a) { + throw new Error(`Unable to access summary file: '${pathFromEnv}'. Check if the file has correct read/write permissions.`); + } + this._filePath = pathFromEnv; + return this._filePath; + }); } - socket.destroy(); - self.removeSocket(socket); - }); -} -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)); - - if (self.sockets.length >= this.maxSockets) { - // We are over limit so we'll add it to the queue. - self.requests.push(options); - return; - } - - // 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); - - function onFree() { - self.emit('free', socket, options); + /** + * Wraps content in an HTML tag, adding any HTML attributes + * + * @param {string} tag HTML tag to wrap + * @param {string | null} content content within the tag + * @param {[attribute: string]: string} attrs key-value list of HTML attributes to add + * + * @returns {string} content wrapped in HTML element + */ + wrap(tag, content, attrs = {}) { + const htmlAttrs = Object.entries(attrs) + .map(([key, value]) => ` ${key}="${value}"`) + .join(''); + if (!content) { + return `<${tag}${htmlAttrs}>`; + } + return `<${tag}${htmlAttrs}>${content}`; } - - function onCloseOrRemove(err) { - self.removeSocket(socket); - socket.removeListener('free', onFree); - socket.removeListener('close', onCloseOrRemove); - socket.removeListener('agentRemove', onCloseOrRemove); + /** + * Writes text in the buffer to the summary buffer file and empties buffer. Will append by default. + * + * @param {SummaryWriteOptions} [options] (optional) options for write operation + * + * @returns {Promise} summary instance + */ + write(options) { + return __awaiter(this, void 0, void 0, function* () { + const overwrite = !!(options === null || options === void 0 ? void 0 : options.overwrite); + const filePath = yield this.filePath(); + const writeFunc = overwrite ? writeFile : appendFile; + yield writeFunc(filePath, this._buffer, { encoding: 'utf8' }); + return this.emptyBuffer(); + }); } - }); -}; - -TunnelingAgent.prototype.createSocket = function createSocket(options, cb) { - var self = this; - var placeholder = {}; - self.sockets.push(placeholder); - - var connectOptions = mergeOptions({}, self.proxyOptions, { - method: 'CONNECT', - path: options.host + ':' + options.port, - agent: false, - headers: { - host: options.host + ':' + options.port + /** + * Clears the summary buffer and wipes the summary file + * + * @returns {Summary} summary instance + */ + clear() { + return __awaiter(this, void 0, void 0, function* () { + return this.emptyBuffer().write({ overwrite: true }); + }); } - }); - 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'); - } - - 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 onResponse(res) { - // Very hacky. This is necessary to avoid http-parser leaks. - res.upgrade = true; - } - - function onUpgrade(res, socket, head) { - // Hacky. - process.nextTick(function() { - onConnect(res, socket, head); - }); - } - - function onConnect(res, socket, head) { - connectReq.removeAllListeners(); - socket.removeAllListeners(); - - 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; + /** + * Returns the current summary buffer as a string + * + * @returns {string} string of summary buffer + */ + stringify() { + return this._buffer; } - 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; + /** + * If the summary buffer is empty + * + * @returns {boolen} true if the buffer is empty + */ + isEmptyBuffer() { + return this._buffer.length === 0; } - debug('tunneling connection has established'); - self.sockets[self.sockets.indexOf(placeholder)] = socket; - return cb(socket); - } - - function onError(cause) { - connectReq.removeAllListeners(); - - debug('tunneling socket could not be established, cause=%s\n', - cause.message, cause.stack); - var error = new Error('tunneling socket could not be established, ' + - 'cause=' + cause.message); - error.code = 'ECONNRESET'; - options.request.emit('error', error); - self.removeSocket(placeholder); - } -}; - -TunnelingAgent.prototype.removeSocket = function removeSocket(socket) { - var pos = this.sockets.indexOf(socket) - if (pos === -1) { - return; - } - this.sockets.splice(pos, 1); - - var pending = this.requests.shift(); - if (pending) { - // If we have pending requests and a socket gets closed a new one - // needs to be created to take over in the pool for the one that closed. - this.createSocket(pending, function(socket) { - pending.request.onSocket(socket); - }); - } -}; - -function createSecureSocket(options, cb) { - var self = this; - TunnelingAgent.prototype.createSocket.call(self, options, function(socket) { - var hostHeader = options.request.getHeader('host'); - var tlsOptions = mergeOptions({}, self.options, { - socket: socket, - servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host - }); - - // 0 is dummy port for v0.6 - var secureSocket = tls.connect(0, tlsOptions); - self.sockets[self.sockets.indexOf(socket)] = secureSocket; - cb(secureSocket); - }); -} - - -function toOptions(host, port, localAddress) { - if (typeof host === 'string') { // since v0.10 - return { - host: host, - port: port, - localAddress: localAddress - }; - } - return host; // for v0.11 or later -} - -function mergeOptions(target) { - for (var i = 1, len = arguments.length; i < len; ++i) { - var overrides = arguments[i]; - if (typeof overrides === 'object') { - var keys = Object.keys(overrides); - for (var j = 0, keyLen = keys.length; j < keyLen; ++j) { - var k = keys[j]; - if (overrides[k] !== undefined) { - target[k] = overrides[k]; - } - } + /** + * Resets the summary buffer without writing to summary file + * + * @returns {Summary} summary instance + */ + emptyBuffer() { + this._buffer = ''; + return this; } - } - return target; -} - - -var debug; -if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) { - debug = function() { - var args = Array.prototype.slice.call(arguments); - if (typeof args[0] === 'string') { - args[0] = 'TUNNEL: ' + args[0]; - } else { - args.unshift('TUNNEL:'); + /** + * Adds raw text to the summary buffer + * + * @param {string} text content to add + * @param {boolean} [addEOL=false] (optional) append an EOL to the raw text (default: false) + * + * @returns {Summary} summary instance + */ + addRaw(text, addEOL = false) { + this._buffer += text; + return addEOL ? this.addEOL() : this; } - console.error.apply(console, args); - } -} else { - debug = function() {}; -} -exports.debug = debug; // for test - - -/***/ }), - -/***/ 160: -/***/ (function(__unusedmodule, exports) { - -// var Utils = require('./utils') - -exports.render = function (qrData, options, cb) { - var size = qrData.modules.size - var data = qrData.modules.data - - // var opts = Utils.getOptions(options) - - // use same scheme as https://github.com/gtanner/qrcode-terminal because it actually works! =) - var black = '\x1b[40m \x1b[0m' - var white = '\x1b[47m \x1b[0m' - - var output = '' - var hMargin = Array(size + 3).join(white) - var vMargin = Array(2).join(white) - - output += hMargin + '\n' - for (var i = 0; i < size; ++i) { - output += white - for (var j = 0; j < size; j++) { - // var topModule = data[i * size + j] - // var bottomModule = data[(i + 1) * size + j] - - output += data[i * size + j] ? black : white// getBlockChar(topModule, bottomModule) + /** + * Adds the operating system-specific end-of-line marker to the buffer + * + * @returns {Summary} summary instance + */ + addEOL() { + return this.addRaw(os_1.EOL); } - // output += white+'\n' - output += vMargin + '\n' - } - - output += hMargin + '\n' - - if (typeof cb === 'function') { - cb(null, output) - } - - return output -} -/* -exports.renderToFile = function renderToFile (path, qrData, options, cb) { - if (typeof cb === 'undefined') { - cb = options - options = undefined - } - - var fs = require('fs') - var utf8 = exports.render(qrData, options) - fs.writeFile(path, utf8, cb) -} -*/ - - -/***/ }), - -/***/ 177: -/***/ (function(__unusedmodule, exports) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.checkBypass = exports.getProxyUrl = void 0; -function getProxyUrl(reqUrl) { - const usingSsl = reqUrl.protocol === 'https:'; - if (checkBypass(reqUrl)) { - return undefined; + /** + * Adds an HTML codeblock to the summary buffer + * + * @param {string} code content to render within fenced code block + * @param {string} lang (optional) language to syntax highlight code + * + * @returns {Summary} summary instance + */ + addCodeBlock(code, lang) { + const attrs = Object.assign({}, (lang && { lang })); + const element = this.wrap('pre', this.wrap('code', code), attrs); + return this.addRaw(element).addEOL(); } - const proxyVar = (() => { - if (usingSsl) { - return process.env['https_proxy'] || process.env['HTTPS_PROXY']; - } - else { - return process.env['http_proxy'] || process.env['HTTP_PROXY']; - } - })(); - if (proxyVar) { - return new URL(proxyVar); + /** + * Adds an HTML list to the summary buffer + * + * @param {string[]} items list of items to render + * @param {boolean} [ordered=false] (optional) if the rendered list should be ordered or not (default: false) + * + * @returns {Summary} summary instance + */ + addList(items, ordered = false) { + const tag = ordered ? 'ol' : 'ul'; + const listItems = items.map(item => this.wrap('li', item)).join(''); + const element = this.wrap(tag, listItems); + return this.addRaw(element).addEOL(); } - else { - return undefined; + /** + * Adds an HTML table to the summary buffer + * + * @param {SummaryTableCell[]} rows table rows + * + * @returns {Summary} summary instance + */ + addTable(rows) { + const tableBody = rows + .map(row => { + const cells = row + .map(cell => { + if (typeof cell === 'string') { + return this.wrap('td', cell); + } + const { header, data, colspan, rowspan } = cell; + const tag = header ? 'th' : 'td'; + const attrs = Object.assign(Object.assign({}, (colspan && { colspan })), (rowspan && { rowspan })); + return this.wrap(tag, data, attrs); + }) + .join(''); + return this.wrap('tr', cells); + }) + .join(''); + const element = this.wrap('table', tableBody); + return this.addRaw(element).addEOL(); } -} -exports.getProxyUrl = getProxyUrl; -function checkBypass(reqUrl) { - if (!reqUrl.hostname) { - return false; + /** + * Adds a collapsable HTML details element to the summary buffer + * + * @param {string} label text for the closed state + * @param {string} content collapsable content + * + * @returns {Summary} summary instance + */ + addDetails(label, content) { + const element = this.wrap('details', this.wrap('summary', label) + content); + return this.addRaw(element).addEOL(); } - const noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || ''; - if (!noProxy) { - return false; + /** + * Adds an HTML image tag to the summary buffer + * + * @param {string} src path to the image you to embed + * @param {string} alt text description of the image + * @param {SummaryImageOptions} options (optional) addition image attributes + * + * @returns {Summary} summary instance + */ + addImage(src, alt, options) { + const { width, height } = options || {}; + const attrs = Object.assign(Object.assign({}, (width && { width })), (height && { height })); + const element = this.wrap('img', null, Object.assign({ src, alt }, attrs)); + return this.addRaw(element).addEOL(); } - // Determine the request port - let reqPort; - if (reqUrl.port) { - reqPort = Number(reqUrl.port); + /** + * Adds an HTML section heading element + * + * @param {string} text heading text + * @param {number | string} [level=1] (optional) the heading level, default: 1 + * + * @returns {Summary} summary instance + */ + addHeading(text, level) { + const tag = `h${level}`; + const allowedTag = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(tag) + ? tag + : 'h1'; + const element = this.wrap(allowedTag, text); + return this.addRaw(element).addEOL(); } - else if (reqUrl.protocol === 'http:') { - reqPort = 80; + /** + * Adds an HTML thematic break (
) to the summary buffer + * + * @returns {Summary} summary instance + */ + addSeparator() { + const element = this.wrap('hr', null); + return this.addRaw(element).addEOL(); } - else if (reqUrl.protocol === 'https:') { - reqPort = 443; + /** + * Adds an HTML line break (
) to the summary buffer + * + * @returns {Summary} summary instance + */ + addBreak() { + const element = this.wrap('br', null); + return this.addRaw(element).addEOL(); } - // Format the request hostname and hostname with port - const upperReqHosts = [reqUrl.hostname.toUpperCase()]; - if (typeof reqPort === 'number') { - upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + /** + * Adds an HTML blockquote to the summary buffer + * + * @param {string} text quote text + * @param {string} cite (optional) citation url + * + * @returns {Summary} summary instance + */ + addQuote(text, cite) { + const attrs = Object.assign({}, (cite && { cite })); + const element = this.wrap('blockquote', text, attrs); + return this.addRaw(element).addEOL(); } - // Compare request host against noproxy - for (const upperNoProxyItem of noProxy - .split(',') - .map(x => x.trim().toUpperCase()) - .filter(x => x)) { - if (upperReqHosts.some(x => x === upperNoProxyItem)) { - return true; - } + /** + * Adds an HTML anchor tag to the summary buffer + * + * @param {string} text link text/content + * @param {string} href hyperlink + * + * @returns {Summary} summary instance + */ + addLink(text, href) { + const element = this.wrap('a', text, { href }); + return this.addRaw(element).addEOL(); } - return false; } -exports.checkBypass = checkBypass; -//# sourceMappingURL=proxy.js.map +const _summary = new Summary(); +/** + * @deprecated use `core.summary` + */ +exports.markdownSummary = _summary; +exports.summary = _summary; +//# sourceMappingURL=summary.js.map /***/ }), -/***/ 185: -/***/ (function(module, __unusedexports, __webpack_require__) { - -var BufferUtil = __webpack_require__(628) -var Polynomial = __webpack_require__(847) -var Buffer = __webpack_require__(407).Buffer - -function ReedSolomonEncoder (degree) { - this.genPoly = undefined - this.degree = degree +/***/ 302: +/***/ ((__unused_webpack_module, exports) => { - if (this.degree) this.initialize(this.degree) -} +"use strict"; +// We use any as a valid input type +/* eslint-disable @typescript-eslint/no-explicit-any */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.toCommandProperties = exports.toCommandValue = void 0; /** - * Initialize the encoder. - * The input param should correspond to the number of error correction codewords. - * - * @param {Number} degree + * Sanitizes an input into a string so it can be passed into issueCommand safely + * @param input input to sanitize into a string */ -ReedSolomonEncoder.prototype.initialize = function initialize (degree) { - // create an irreducible generator polynomial - this.degree = degree - this.genPoly = Polynomial.generateECPolynomial(this.degree) +function toCommandValue(input) { + if (input === null || input === undefined) { + return ''; + } + else if (typeof input === 'string' || input instanceof String) { + return input; + } + return JSON.stringify(input); } - +exports.toCommandValue = toCommandValue; /** - * Encodes a chunk of data * - * @param {Buffer} data Buffer containing input data - * @return {Buffer} Buffer containing encoded data + * @param annotationProperties + * @returns The command properties to send with the actual annotation command + * See IssueCommandProperties: https://github.com/actions/runner/blob/main/src/Runner.Worker/ActionCommandManager.cs#L646 */ -ReedSolomonEncoder.prototype.encode = function encode (data) { - if (!this.genPoly) { - throw new Error('Encoder not initialized') - } - - // Calculate EC for this data block - // extends data size to data+genPoly size - var pad = BufferUtil.alloc(this.degree) - var paddedData = Buffer.concat([data, pad], data.length + this.degree) - - // The error correction codewords are the remainder after dividing the data codewords - // by a generator polynomial - var remainder = Polynomial.mod(paddedData, this.genPoly) - - // return EC data blocks (last n byte, where n is the degree of genPoly) - // If coefficients number in remainder are less than genPoly degree, - // pad with 0s to the left to reach the needed number of coefficients - var start = this.degree - remainder.length - if (start > 0) { - var buff = BufferUtil.alloc(this.degree) - remainder.copy(buff, start) - - return buff - } - - return remainder +function toCommandProperties(annotationProperties) { + if (!Object.keys(annotationProperties).length) { + return {}; + } + return { + title: annotationProperties.title, + file: annotationProperties.file, + line: annotationProperties.startLine, + endLine: annotationProperties.endLine, + col: annotationProperties.startColumn, + endColumn: annotationProperties.endColumn + }; } - -module.exports = ReedSolomonEncoder - - -/***/ }), - -/***/ 189: -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -var ECLevel = __webpack_require__(50) - -var EC_BLOCKS_TABLE = [ -// L M Q H - 1, 1, 1, 1, - 1, 1, 1, 1, - 1, 1, 2, 2, - 1, 2, 2, 4, - 1, 2, 4, 4, - 2, 4, 4, 4, - 2, 4, 6, 5, - 2, 4, 6, 6, - 2, 5, 8, 8, - 4, 5, 8, 8, - 4, 5, 8, 11, - 4, 8, 10, 11, - 4, 9, 12, 16, - 4, 9, 16, 16, - 6, 10, 12, 18, - 6, 10, 17, 16, - 6, 11, 16, 19, - 6, 13, 18, 21, - 7, 14, 21, 25, - 8, 16, 20, 25, - 8, 17, 23, 25, - 9, 17, 23, 34, - 9, 18, 25, 30, - 10, 20, 27, 32, - 12, 21, 29, 35, - 12, 23, 34, 37, - 12, 25, 34, 40, - 13, 26, 35, 42, - 14, 28, 38, 45, - 15, 29, 40, 48, - 16, 31, 43, 51, - 17, 33, 45, 54, - 18, 35, 48, 57, - 19, 37, 51, 60, - 19, 38, 53, 63, - 20, 40, 56, 66, - 21, 43, 59, 70, - 22, 45, 62, 74, - 24, 47, 65, 77, - 25, 49, 68, 81 -] - -var EC_CODEWORDS_TABLE = [ -// L M Q H - 7, 10, 13, 17, - 10, 16, 22, 28, - 15, 26, 36, 44, - 20, 36, 52, 64, - 26, 48, 72, 88, - 36, 64, 96, 112, - 40, 72, 108, 130, - 48, 88, 132, 156, - 60, 110, 160, 192, - 72, 130, 192, 224, - 80, 150, 224, 264, - 96, 176, 260, 308, - 104, 198, 288, 352, - 120, 216, 320, 384, - 132, 240, 360, 432, - 144, 280, 408, 480, - 168, 308, 448, 532, - 180, 338, 504, 588, - 196, 364, 546, 650, - 224, 416, 600, 700, - 224, 442, 644, 750, - 252, 476, 690, 816, - 270, 504, 750, 900, - 300, 560, 810, 960, - 312, 588, 870, 1050, - 336, 644, 952, 1110, - 360, 700, 1020, 1200, - 390, 728, 1050, 1260, - 420, 784, 1140, 1350, - 450, 812, 1200, 1440, - 480, 868, 1290, 1530, - 510, 924, 1350, 1620, - 540, 980, 1440, 1710, - 570, 1036, 1530, 1800, - 570, 1064, 1590, 1890, - 600, 1120, 1680, 1980, - 630, 1204, 1770, 2100, - 660, 1260, 1860, 2220, - 720, 1316, 1950, 2310, - 750, 1372, 2040, 2430 -] - -/** - * Returns the number of error correction block that the QR Code should contain - * for the specified version and error correction level. - * - * @param {Number} version QR Code version - * @param {Number} errorCorrectionLevel Error correction level - * @return {Number} Number of error correction blocks - */ -exports.getBlocksCount = function getBlocksCount (version, errorCorrectionLevel) { - switch (errorCorrectionLevel) { - case ECLevel.L: - return EC_BLOCKS_TABLE[(version - 1) * 4 + 0] - case ECLevel.M: - return EC_BLOCKS_TABLE[(version - 1) * 4 + 1] - case ECLevel.Q: - return EC_BLOCKS_TABLE[(version - 1) * 4 + 2] - case ECLevel.H: - return EC_BLOCKS_TABLE[(version - 1) * 4 + 3] - default: - return undefined - } -} - -/** - * Returns the number of error correction codewords to use for the specified - * version and error correction level. - * - * @param {Number} version QR Code version - * @param {Number} errorCorrectionLevel Error correction level - * @return {Number} Number of error correction codewords - */ -exports.getTotalCodewordsCount = function getTotalCodewordsCount (version, errorCorrectionLevel) { - switch (errorCorrectionLevel) { - case ECLevel.L: - return EC_CODEWORDS_TABLE[(version - 1) * 4 + 0] - case ECLevel.M: - return EC_CODEWORDS_TABLE[(version - 1) * 4 + 1] - case ECLevel.Q: - return EC_CODEWORDS_TABLE[(version - 1) * 4 + 2] - case ECLevel.H: - return EC_CODEWORDS_TABLE[(version - 1) * 4 + 3] - default: - return undefined - } -} - +exports.toCommandProperties = toCommandProperties; +//# sourceMappingURL=utils.js.map /***/ }), -/***/ 204: -/***/ (function(__unusedmodule, exports, __webpack_require__) { +/***/ 5236: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (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; }); -exports.default = void 0; - -var _validate = _interopRequireDefault(__webpack_require__(634)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function parse(uuid) { - if (!(0, _validate.default)(uuid)) { - throw TypeError('Invalid UUID'); - } - - let v; - const arr = new Uint8Array(16); // Parse ########-....-....-....-............ - - arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; - arr[1] = v >>> 16 & 0xff; - arr[2] = v >>> 8 & 0xff; - arr[3] = v & 0xff; // Parse ........-####-....-....-............ - - arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; - arr[5] = v & 0xff; // Parse ........-....-####-....-............ - - arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; - arr[7] = v & 0xff; // Parse ........-....-....-####-............ - - arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; - arr[9] = v & 0xff; // Parse ........-....-....-....-############ - // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) - - arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; - arr[11] = v / 0x100000000 & 0xff; - arr[12] = v >>> 24 & 0xff; - arr[13] = v >>> 16 & 0xff; - arr[14] = v >>> 8 & 0xff; - arr[15] = v & 0xff; - return arr; +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.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getExecOutput = exports.exec = void 0; +const string_decoder_1 = __nccwpck_require__(3193); +const tr = __importStar(__nccwpck_require__(6665)); +/** + * Exec a command. + * Output will be streamed to the live console. + * Returns promise with return code + * + * @param commandLine command to execute (can include additional args). Must be correctly escaped. + * @param args optional arguments for tool. Escaping is handled by the lib. + * @param options optional exec options. See ExecOptions + * @returns Promise exit code + */ +function exec(commandLine, args, options) { + return __awaiter(this, void 0, void 0, function* () { + const commandArgs = tr.argStringToArray(commandLine); + if (commandArgs.length === 0) { + throw new Error(`Parameter 'commandLine' cannot be null or empty.`); + } + // Path to tool to execute should be first arg + const toolPath = commandArgs[0]; + args = commandArgs.slice(1).concat(args || []); + const runner = new tr.ToolRunner(toolPath, args, options); + return runner.exec(); + }); } - -var _default = parse; -exports.default = _default; +exports.exec = exec; +/** + * Exec a command and get the output. + * Output will be streamed to the live console. + * Returns promise with the exit code and collected stdout and stderr + * + * @param commandLine command to execute (can include additional args). Must be correctly escaped. + * @param args optional arguments for tool. Escaping is handled by the lib. + * @param options optional exec options. See ExecOptions + * @returns Promise exit code, stdout, and stderr + */ +function getExecOutput(commandLine, args, options) { + var _a, _b; + return __awaiter(this, void 0, void 0, function* () { + let stdout = ''; + let stderr = ''; + //Using string decoder covers the case where a mult-byte character is split + const stdoutDecoder = new string_decoder_1.StringDecoder('utf8'); + const stderrDecoder = new string_decoder_1.StringDecoder('utf8'); + const originalStdoutListener = (_a = options === null || options === void 0 ? void 0 : options.listeners) === null || _a === void 0 ? void 0 : _a.stdout; + const originalStdErrListener = (_b = options === null || options === void 0 ? void 0 : options.listeners) === null || _b === void 0 ? void 0 : _b.stderr; + const stdErrListener = (data) => { + stderr += stderrDecoder.write(data); + if (originalStdErrListener) { + originalStdErrListener(data); + } + }; + const stdOutListener = (data) => { + stdout += stdoutDecoder.write(data); + if (originalStdoutListener) { + originalStdoutListener(data); + } + }; + const listeners = Object.assign(Object.assign({}, options === null || options === void 0 ? void 0 : options.listeners), { stdout: stdOutListener, stderr: stdErrListener }); + const exitCode = yield exec(commandLine, args, Object.assign(Object.assign({}, options), { listeners })); + //flush any remaining characters + stdout += stdoutDecoder.end(); + stderr += stderrDecoder.end(); + return { + exitCode, + stdout, + stderr + }; + }); +} +exports.getExecOutput = getExecOutput; +//# sourceMappingURL=exec.js.map /***/ }), -/***/ 210: -/***/ (function(module, __unusedexports, __webpack_require__) { +/***/ 6665: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - - -var util = __webpack_require__(669); -var Stream = __webpack_require__(794); - - -var ChunkStream = module.exports = function() { - Stream.call(this); - - this._buffers = []; - this._buffered = 0; - - this._reads = []; - this._paused = false; - - this._encoding = 'utf8'; - this.writable = true; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (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.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; }; -util.inherits(ChunkStream, Stream); - - -ChunkStream.prototype.read = function(length, callback) { +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.argStringToArray = exports.ToolRunner = void 0; +const os = __importStar(__nccwpck_require__(857)); +const events = __importStar(__nccwpck_require__(4434)); +const child = __importStar(__nccwpck_require__(5317)); +const path = __importStar(__nccwpck_require__(6928)); +const io = __importStar(__nccwpck_require__(4994)); +const ioUtil = __importStar(__nccwpck_require__(5207)); +const timers_1 = __nccwpck_require__(3557); +/* eslint-disable @typescript-eslint/unbound-method */ +const IS_WINDOWS = process.platform === 'win32'; +/* + * Class for running command line tools. Handles quoting and arg parsing in a platform agnostic way. + */ +class ToolRunner extends events.EventEmitter { + constructor(toolPath, args, options) { + super(); + if (!toolPath) { + throw new Error("Parameter 'toolPath' cannot be null or empty."); + } + this.toolPath = toolPath; + this.args = args || []; + this.options = options || {}; + } + _debug(message) { + if (this.options.listeners && this.options.listeners.debug) { + this.options.listeners.debug(message); + } + } + _getCommandString(options, noPrefix) { + const toolPath = this._getSpawnFileName(); + const args = this._getSpawnArgs(options); + let cmd = noPrefix ? '' : '[command]'; // omit prefix when piped to a second tool + if (IS_WINDOWS) { + // Windows + cmd file + if (this._isCmdFile()) { + cmd += toolPath; + for (const a of args) { + cmd += ` ${a}`; + } + } + // Windows + verbatim + else if (options.windowsVerbatimArguments) { + cmd += `"${toolPath}"`; + for (const a of args) { + cmd += ` ${a}`; + } + } + // Windows (regular) + else { + cmd += this._windowsQuoteCmdArg(toolPath); + for (const a of args) { + cmd += ` ${this._windowsQuoteCmdArg(a)}`; + } + } + } + else { + // OSX/Linux - this can likely be improved with some form of quoting. + // creating processes on Unix is fundamentally different than Windows. + // on Unix, execvp() takes an arg array. + cmd += toolPath; + for (const a of args) { + cmd += ` ${a}`; + } + } + return cmd; + } + _processLineBuffer(data, strBuffer, onLine) { + try { + let s = strBuffer + data.toString(); + let n = s.indexOf(os.EOL); + while (n > -1) { + const line = s.substring(0, n); + onLine(line); + // the rest of the string ... + s = s.substring(n + os.EOL.length); + n = s.indexOf(os.EOL); + } + return s; + } + catch (err) { + // streaming lines to console is best effort. Don't fail a build. + this._debug(`error processing line. Failed with error ${err}`); + return ''; + } + } + _getSpawnFileName() { + if (IS_WINDOWS) { + if (this._isCmdFile()) { + return process.env['COMSPEC'] || 'cmd.exe'; + } + } + return this.toolPath; + } + _getSpawnArgs(options) { + if (IS_WINDOWS) { + if (this._isCmdFile()) { + let argline = `/D /S /C "${this._windowsQuoteCmdArg(this.toolPath)}`; + for (const a of this.args) { + argline += ' '; + argline += options.windowsVerbatimArguments + ? a + : this._windowsQuoteCmdArg(a); + } + argline += '"'; + return [argline]; + } + } + return this.args; + } + _endsWith(str, end) { + return str.endsWith(end); + } + _isCmdFile() { + const upperToolPath = this.toolPath.toUpperCase(); + return (this._endsWith(upperToolPath, '.CMD') || + this._endsWith(upperToolPath, '.BAT')); + } + _windowsQuoteCmdArg(arg) { + // for .exe, apply the normal quoting rules that libuv applies + if (!this._isCmdFile()) { + return this._uvQuoteCmdArg(arg); + } + // otherwise apply quoting rules specific to the cmd.exe command line parser. + // the libuv rules are generic and are not designed specifically for cmd.exe + // command line parser. + // + // for a detailed description of the cmd.exe command line parser, refer to + // http://stackoverflow.com/questions/4094699/how-does-the-windows-command-interpreter-cmd-exe-parse-scripts/7970912#7970912 + // need quotes for empty arg + if (!arg) { + return '""'; + } + // determine whether the arg needs to be quoted + const cmdSpecialChars = [ + ' ', + '\t', + '&', + '(', + ')', + '[', + ']', + '{', + '}', + '^', + '=', + ';', + '!', + "'", + '+', + ',', + '`', + '~', + '|', + '<', + '>', + '"' + ]; + let needsQuotes = false; + for (const char of arg) { + if (cmdSpecialChars.some(x => x === char)) { + needsQuotes = true; + break; + } + } + // short-circuit if quotes not needed + if (!needsQuotes) { + return arg; + } + // the following quoting rules are very similar to the rules that by libuv applies. + // + // 1) wrap the string in quotes + // + // 2) double-up quotes - i.e. " => "" + // + // this is different from the libuv quoting rules. libuv replaces " with \", which unfortunately + // doesn't work well with a cmd.exe command line. + // + // note, replacing " with "" also works well if the arg is passed to a downstream .NET console app. + // for example, the command line: + // foo.exe "myarg:""my val""" + // is parsed by a .NET console app into an arg array: + // [ "myarg:\"my val\"" ] + // which is the same end result when applying libuv quoting rules. although the actual + // command line from libuv quoting rules would look like: + // foo.exe "myarg:\"my val\"" + // + // 3) double-up slashes that precede a quote, + // e.g. hello \world => "hello \world" + // hello\"world => "hello\\""world" + // hello\\"world => "hello\\\\""world" + // hello world\ => "hello world\\" + // + // technically this is not required for a cmd.exe command line, or the batch argument parser. + // the reasons for including this as a .cmd quoting rule are: + // + // a) this is optimized for the scenario where the argument is passed from the .cmd file to an + // external program. many programs (e.g. .NET console apps) rely on the slash-doubling rule. + // + // b) it's what we've been doing previously (by deferring to node default behavior) and we + // haven't heard any complaints about that aspect. + // + // note, a weakness of the quoting rules chosen here, is that % is not escaped. in fact, % cannot be + // escaped when used on the command line directly - even though within a .cmd file % can be escaped + // by using %%. + // + // the saving grace is, on the command line, %var% is left as-is if var is not defined. this contrasts + // the line parsing rules within a .cmd file, where if var is not defined it is replaced with nothing. + // + // one option that was explored was replacing % with ^% - i.e. %var% => ^%var^%. this hack would + // often work, since it is unlikely that var^ would exist, and the ^ character is removed when the + // variable is used. the problem, however, is that ^ is not removed when %* is used to pass the args + // to an external program. + // + // an unexplored potential solution for the % escaping problem, is to create a wrapper .cmd file. + // % can be escaped within a .cmd file. + let reverse = '"'; + let quoteHit = true; + for (let i = arg.length; i > 0; i--) { + // walk the string in reverse + reverse += arg[i - 1]; + if (quoteHit && arg[i - 1] === '\\') { + reverse += '\\'; // double the slash + } + else if (arg[i - 1] === '"') { + quoteHit = true; + reverse += '"'; // double the quote + } + else { + quoteHit = false; + } + } + reverse += '"'; + return reverse + .split('') + .reverse() + .join(''); + } + _uvQuoteCmdArg(arg) { + // Tool runner wraps child_process.spawn() and needs to apply the same quoting as + // Node in certain cases where the undocumented spawn option windowsVerbatimArguments + // is used. + // + // Since this function is a port of quote_cmd_arg from Node 4.x (technically, lib UV, + // see https://github.com/nodejs/node/blob/v4.x/deps/uv/src/win/process.c for details), + // pasting copyright notice from Node within this function: + // + // Copyright Joyent, Inc. and other Node contributors. All rights reserved. + // + // 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. + if (!arg) { + // Need double quotation for empty argument + return '""'; + } + if (!arg.includes(' ') && !arg.includes('\t') && !arg.includes('"')) { + // No quotation needed + return arg; + } + if (!arg.includes('"') && !arg.includes('\\')) { + // No embedded double quotes or backslashes, so I can just wrap + // quote marks around the whole thing. + return `"${arg}"`; + } + // Expected input/output: + // input : hello"world + // output: "hello\"world" + // input : hello""world + // output: "hello\"\"world" + // input : hello\world + // output: hello\world + // input : hello\\world + // output: hello\\world + // input : hello\"world + // output: "hello\\\"world" + // input : hello\\"world + // output: "hello\\\\\"world" + // input : hello world\ + // output: "hello world\\" - note the comment in libuv actually reads "hello world\" + // but it appears the comment is wrong, it should be "hello world\\" + let reverse = '"'; + let quoteHit = true; + for (let i = arg.length; i > 0; i--) { + // walk the string in reverse + reverse += arg[i - 1]; + if (quoteHit && arg[i - 1] === '\\') { + reverse += '\\'; + } + else if (arg[i - 1] === '"') { + quoteHit = true; + reverse += '\\'; + } + else { + quoteHit = false; + } + } + reverse += '"'; + return reverse + .split('') + .reverse() + .join(''); + } + _cloneExecOptions(options) { + options = options || {}; + const result = { + cwd: options.cwd || process.cwd(), + env: options.env || process.env, + silent: options.silent || false, + windowsVerbatimArguments: options.windowsVerbatimArguments || false, + failOnStdErr: options.failOnStdErr || false, + ignoreReturnCode: options.ignoreReturnCode || false, + delay: options.delay || 10000 + }; + result.outStream = options.outStream || process.stdout; + result.errStream = options.errStream || process.stderr; + return result; + } + _getSpawnOptions(options, toolPath) { + options = options || {}; + const result = {}; + result.cwd = options.cwd; + result.env = options.env; + result['windowsVerbatimArguments'] = + options.windowsVerbatimArguments || this._isCmdFile(); + if (options.windowsVerbatimArguments) { + result.argv0 = `"${toolPath}"`; + } + return result; + } + /** + * Exec a tool. + * Output will be streamed to the live console. + * Returns promise with return code + * + * @param tool path to tool to exec + * @param options optional exec options. See ExecOptions + * @returns number + */ + exec() { + return __awaiter(this, void 0, void 0, function* () { + // root the tool path if it is unrooted and contains relative pathing + if (!ioUtil.isRooted(this.toolPath) && + (this.toolPath.includes('/') || + (IS_WINDOWS && this.toolPath.includes('\\')))) { + // prefer options.cwd if it is specified, however options.cwd may also need to be rooted + this.toolPath = path.resolve(process.cwd(), this.options.cwd || process.cwd(), this.toolPath); + } + // if the tool is only a file name, then resolve it from the PATH + // otherwise verify it exists (add extension on Windows if necessary) + this.toolPath = yield io.which(this.toolPath, true); + return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { + this._debug(`exec tool: ${this.toolPath}`); + this._debug('arguments:'); + for (const arg of this.args) { + this._debug(` ${arg}`); + } + const optionsNonNull = this._cloneExecOptions(this.options); + if (!optionsNonNull.silent && optionsNonNull.outStream) { + optionsNonNull.outStream.write(this._getCommandString(optionsNonNull) + os.EOL); + } + const state = new ExecState(optionsNonNull, this.toolPath); + state.on('debug', (message) => { + this._debug(message); + }); + if (this.options.cwd && !(yield ioUtil.exists(this.options.cwd))) { + return reject(new Error(`The cwd: ${this.options.cwd} does not exist!`)); + } + const fileName = this._getSpawnFileName(); + const cp = child.spawn(fileName, this._getSpawnArgs(optionsNonNull), this._getSpawnOptions(this.options, fileName)); + let stdbuffer = ''; + if (cp.stdout) { + cp.stdout.on('data', (data) => { + if (this.options.listeners && this.options.listeners.stdout) { + this.options.listeners.stdout(data); + } + if (!optionsNonNull.silent && optionsNonNull.outStream) { + optionsNonNull.outStream.write(data); + } + stdbuffer = this._processLineBuffer(data, stdbuffer, (line) => { + if (this.options.listeners && this.options.listeners.stdline) { + this.options.listeners.stdline(line); + } + }); + }); + } + let errbuffer = ''; + if (cp.stderr) { + cp.stderr.on('data', (data) => { + state.processStderr = true; + if (this.options.listeners && this.options.listeners.stderr) { + this.options.listeners.stderr(data); + } + if (!optionsNonNull.silent && + optionsNonNull.errStream && + optionsNonNull.outStream) { + const s = optionsNonNull.failOnStdErr + ? optionsNonNull.errStream + : optionsNonNull.outStream; + s.write(data); + } + errbuffer = this._processLineBuffer(data, errbuffer, (line) => { + if (this.options.listeners && this.options.listeners.errline) { + this.options.listeners.errline(line); + } + }); + }); + } + cp.on('error', (err) => { + state.processError = err.message; + state.processExited = true; + state.processClosed = true; + state.CheckComplete(); + }); + cp.on('exit', (code) => { + state.processExitCode = code; + state.processExited = true; + this._debug(`Exit code ${code} received from tool '${this.toolPath}'`); + state.CheckComplete(); + }); + cp.on('close', (code) => { + state.processExitCode = code; + state.processExited = true; + state.processClosed = true; + this._debug(`STDIO streams have closed for tool '${this.toolPath}'`); + state.CheckComplete(); + }); + state.on('done', (error, exitCode) => { + if (stdbuffer.length > 0) { + this.emit('stdline', stdbuffer); + } + if (errbuffer.length > 0) { + this.emit('errline', errbuffer); + } + cp.removeAllListeners(); + if (error) { + reject(error); + } + else { + resolve(exitCode); + } + }); + if (this.options.input) { + if (!cp.stdin) { + throw new Error('child process missing stdin'); + } + cp.stdin.end(this.options.input); + } + })); + }); + } +} +exports.ToolRunner = ToolRunner; +/** + * Convert an arg string to an array of args. Handles escaping + * + * @param argString string of arguments + * @returns string[] array of arguments + */ +function argStringToArray(argString) { + const args = []; + let inQuotes = false; + let escaped = false; + let arg = ''; + function append(c) { + // we only escape double quotes. + if (escaped && c !== '"') { + arg += '\\'; + } + arg += c; + escaped = false; + } + for (let i = 0; i < argString.length; i++) { + const c = argString.charAt(i); + if (c === '"') { + if (!escaped) { + inQuotes = !inQuotes; + } + else { + append(c); + } + continue; + } + if (c === '\\' && escaped) { + append(c); + continue; + } + if (c === '\\' && inQuotes) { + escaped = true; + continue; + } + if (c === ' ' && !inQuotes) { + if (arg.length > 0) { + args.push(arg); + arg = ''; + } + continue; + } + append(c); + } + if (arg.length > 0) { + args.push(arg.trim()); + } + return args; +} +exports.argStringToArray = argStringToArray; +class ExecState extends events.EventEmitter { + constructor(options, toolPath) { + super(); + this.processClosed = false; // tracks whether the process has exited and stdio is closed + this.processError = ''; + this.processExitCode = 0; + this.processExited = false; // tracks whether the process has exited + this.processStderr = false; // tracks whether stderr was written to + this.delay = 10000; // 10 seconds + this.done = false; + this.timeout = null; + if (!toolPath) { + throw new Error('toolPath must not be empty'); + } + this.options = options; + this.toolPath = toolPath; + if (options.delay) { + this.delay = options.delay; + } + } + CheckComplete() { + if (this.done) { + return; + } + if (this.processClosed) { + this._setResult(); + } + else if (this.processExited) { + this.timeout = timers_1.setTimeout(ExecState.HandleTimeout, this.delay, this); + } + } + _debug(message) { + this.emit('debug', message); + } + _setResult() { + // determine whether there is an error + let error; + if (this.processExited) { + if (this.processError) { + error = new Error(`There was an error when attempting to execute the process '${this.toolPath}'. This may indicate the process failed to start. Error: ${this.processError}`); + } + else if (this.processExitCode !== 0 && !this.options.ignoreReturnCode) { + error = new Error(`The process '${this.toolPath}' failed with exit code ${this.processExitCode}`); + } + else if (this.processStderr && this.options.failOnStdErr) { + error = new Error(`The process '${this.toolPath}' failed because one or more lines were written to the STDERR stream`); + } + } + // clear the timeout + if (this.timeout) { + clearTimeout(this.timeout); + this.timeout = null; + } + this.done = true; + this.emit('done', error, this.processExitCode); + } + static HandleTimeout(state) { + if (state.done) { + return; + } + if (!state.processClosed && state.processExited) { + const message = `The STDIO streams did not close within ${state.delay / + 1000} seconds of the exit event from process '${state.toolPath}'. This may indicate a child process inherited the STDIO streams and has not yet exited.`; + state._debug(message); + } + state._setResult(); + } +} +//# sourceMappingURL=toolrunner.js.map - 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(); +/***/ 4552: +/***/ (function(__unused_webpack_module, exports) { - // its paused and there is not enought data then ask for more - if (this._paused && this._reads.length > 0) { - this._paused = false; +"use strict"; - this.emit('drain'); - } - }.bind(this)); +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.PersonalAccessTokenCredentialHandler = exports.BearerCredentialHandler = exports.BasicCredentialHandler = void 0; +class BasicCredentialHandler { + constructor(username, password) { + this.username = username; + this.password = password; + } + prepareRequest(options) { + if (!options.headers) { + throw Error('The request has no headers'); + } + options.headers['Authorization'] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString('base64')}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter(this, void 0, void 0, function* () { + throw new Error('not implemented'); + }); + } +} +exports.BasicCredentialHandler = BasicCredentialHandler; +class BearerCredentialHandler { + constructor(token) { + this.token = token; + } + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error('The request has no headers'); + } + options.headers['Authorization'] = `Bearer ${this.token}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter(this, void 0, void 0, function* () { + throw new Error('not implemented'); + }); + } +} +exports.BearerCredentialHandler = BearerCredentialHandler; +class PersonalAccessTokenCredentialHandler { + constructor(token) { + this.token = token; + } + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error('The request has no headers'); + } + options.headers['Authorization'] = `Basic ${Buffer.from(`PAT:${this.token}`).toString('base64')}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter(this, void 0, void 0, function* () { + throw new Error('not implemented'); + }); + } +} +exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; +//# sourceMappingURL=auth.js.map -ChunkStream.prototype.write = function(data, encoding) { +/***/ }), - if (!this.writable) { - this.emit('error', new Error('Stream not writable')); - return false; - } +/***/ 4844: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - var dataBuffer; - if (Buffer.isBuffer(data)) { - dataBuffer = data; - } - else { - dataBuffer = new Buffer(data, encoding || this._encoding); - } +"use strict"; - 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); +/* eslint-disable @typescript-eslint/no-explicit-any */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (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.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; }; - -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); - } +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; - - -/***/ }), - -/***/ 211: -/***/ (function(module) { - -module.exports = require("https"); - -/***/ }), - -/***/ 227: -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -var getSymbolSize = __webpack_require__(114).getSymbolSize -var FINDER_PATTERN_SIZE = 7 - +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__(8611)); +const https = __importStar(__nccwpck_require__(5692)); +const pm = __importStar(__nccwpck_require__(4988)); +const tunnel = __importStar(__nccwpck_require__(770)); +var HttpCodes; +(function (HttpCodes) { + HttpCodes[HttpCodes["OK"] = 200] = "OK"; + HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther"; + HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified"; + HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy"; + HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest"; + HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden"; + HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound"; + HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict"; + HttpCodes[HttpCodes["Gone"] = 410] = "Gone"; + HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; + HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; +})(HttpCodes = exports.HttpCodes || (exports.HttpCodes = {})); +var Headers; +(function (Headers) { + Headers["Accept"] = "accept"; + Headers["ContentType"] = "content-type"; +})(Headers = exports.Headers || (exports.Headers = {})); +var MediaTypes; +(function (MediaTypes) { + MediaTypes["ApplicationJson"] = "application/json"; +})(MediaTypes = exports.MediaTypes || (exports.MediaTypes = {})); /** - * Returns an array containing the positions of each finder pattern. - * Each array's element represent the top-left point of the pattern as (x, y) coordinates - * - * @param {Number} version QR Code version - * @return {Array} Array of coordinates + * Returns the proxy URL, depending upon the supplied url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com */ -exports.getPositions = function getPositions (version) { - var size = getSymbolSize(version) - - return [ - // top-left - [0, 0], - // top-right - [size - FINDER_PATTERN_SIZE, 0], - // bottom-left - [0, size - FINDER_PATTERN_SIZE] - ] +function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ''; } - - -/***/ }), - -/***/ 228: -/***/ (function(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; -}; - - -/***/ }), - -/***/ 254: -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -/** - * Alignment pattern are fixed reference pattern in defined positions - * in a matrix symbology, which enables the decode software to re-synchronise - * the coordinate mapping of the image modules in the event of moderate amounts - * of distortion of the image. - * - * Alignment patterns are present only in QR Code symbols of version 2 or larger - * and their number depends on the symbol version. - */ - -var getSymbolSize = __webpack_require__(114).getSymbolSize - -/** - * Calculate the row/column coordinates of the center module of each alignment pattern - * for the specified QR Code version. - * - * The alignment patterns are positioned symmetrically on either side of the diagonal - * running from the top left corner of the symbol to the bottom right corner. - * - * Since positions are simmetrical only half of the coordinates are returned. - * Each item of the array will represent in turn the x and y coordinate. - * @see {@link getPositions} - * - * @param {Number} version QR Code version - * @return {Array} Array of coordinate - */ -exports.getRowColCoords = function getRowColCoords (version) { - if (version === 1) return [] - - var posCount = Math.floor(version / 7) + 2 - var size = getSymbolSize(version) - var intervals = size === 145 ? 26 : Math.ceil((size - 13) / (2 * posCount - 2)) * 2 - var positions = [size - 7] // Last coord is always (size - 7) - - for (var i = 1; i < posCount - 1; i++) { - positions[i] = positions[i - 1] - intervals - } - - positions.push(6) // First coord is always 6 - - return positions.reverse() -} - -/** - * Returns an array containing the positions of each alignment pattern. - * Each array's element represent the center point of the pattern as (x, y) coordinates - * - * Coordinates are calculated expanding the row/column coordinates returned by {@link getRowColCoords} - * and filtering out the items that overlaps with finder pattern - * - * @example - * For a Version 7 symbol {@link getRowColCoords} returns values 6, 22 and 38. - * The alignment patterns, therefore, are to be centered on (row, column) - * positions (6,22), (22,6), (22,22), (22,38), (38,22), (38,38). - * Note that the coordinates (6,6), (6,38), (38,6) are occupied by finder patterns - * and are not therefore used for alignment patterns. - * - * var pos = getPositions(7) - * // [[6,22], [22,6], [22,22], [22,38], [38,22], [38,38]] - * - * @param {Number} version QR Code version - * @return {Array} Array of coordinates - */ -exports.getPositions = function getPositions (version) { - var coords = [] - var pos = exports.getRowColCoords(version) - var posLength = pos.length - - for (var i = 0; i < posLength; i++) { - for (var j = 0; j < posLength; j++) { - // Skip if position is occupied by finder patterns - if ((i === 0 && j === 0) || // top-left - (i === 0 && j === posLength - 1) || // bottom-left - (i === posLength - 1 && j === 0)) { // top-right - continue - } - - coords.push([pos[i], pos[j]]) +exports.getProxyUrl = getProxyUrl; +const HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect +]; +const HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout +]; +const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD']; +const ExponentialBackoffCeiling = 10; +const ExponentialBackoffTimeSlice = 5; +class HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = 'HttpClientError'; + this.statusCode = statusCode; + Object.setPrototypeOf(this, HttpClientError.prototype); } - } - - return coords -} - - -/***/ }), - -/***/ 261: -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -var Utils = __webpack_require__(621) - -function clearCanvas (ctx, canvas, size) { - ctx.clearRect(0, 0, canvas.width, canvas.height) - - if (!canvas.style) canvas.style = {} - canvas.height = size - canvas.width = size - canvas.style.height = size + 'px' - canvas.style.width = size + 'px' -} - -function getCanvasElement () { - try { - return document.createElement('canvas') - } catch (e) { - throw new Error('You need to specify a canvas element') - } } - -exports.render = function render (qrData, canvas, options) { - var opts = options - var canvasEl = canvas - - if (typeof opts === 'undefined' && (!canvas || !canvas.getContext)) { - opts = canvas - canvas = undefined - } - - if (!canvas) { - canvasEl = getCanvasElement() - } - - opts = Utils.getOptions(opts) - var size = Utils.getImageWidth(qrData.modules.size, opts) - - var ctx = canvasEl.getContext('2d') - var image = ctx.createImageData(size, size) - Utils.qrToImageData(image.data, qrData, opts) - - clearCanvas(ctx, canvasEl, size) - ctx.putImageData(image, 0, 0) - - return canvasEl +exports.HttpClientError = HttpClientError; +class HttpClientResponse { + constructor(message) { + this.message = message; + } + readBody() { + return __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on('data', (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on('end', () => { + resolve(output.toString()); + }); + })); + }); + } } - -exports.renderToDataURL = function renderToDataURL (qrData, canvas, options) { - var opts = options - - if (typeof opts === 'undefined' && (!canvas || !canvas.getContext)) { - opts = canvas - canvas = undefined - } - - if (!opts) opts = {} - - var canvasEl = exports.render(qrData, canvas, opts) - - var type = opts.type || 'image/png' - var rendererOpts = opts.rendererOpts || {} - - return canvasEl.toDataURL(type, rendererOpts.quality) +exports.HttpClientResponse = HttpClientResponse; +function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === 'https:'; } - - -/***/ }), - -/***/ 268: -/***/ (function(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 -}; - - -/***/ }), - -/***/ 275: -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - - -var util = __webpack_require__(669); -var Stream = __webpack_require__(794); -var Parser = __webpack_require__(507); -var Packer = __webpack_require__(83); -var PNGSync = __webpack_require__(24); - - -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); +exports.isHttps = isHttps; +class HttpClient { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; + } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; + } + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; + } } - } } - src.gamma = 0; - } -}; - -PNG.prototype.adjustGamma = function() { - PNG.adjustGamma(this); -}; - - -/***/ }), - -/***/ 287: -/***/ (function(module, __unusedexports, __webpack_require__) { - -var BufferUtil = __webpack_require__(628) - -/** - * Helper class to handle QR Code symbol modules - * - * @param {Number} size Symbol size - */ -function BitMatrix (size) { - if (!size || size < 1) { - throw new Error('BitMatrix size must be defined and greater than 0') - } - - this.size = size - this.data = BufferUtil.alloc(size * size) - this.reservedBit = BufferUtil.alloc(size * size) -} - -/** - * Set bit value at specified location - * If reserved flag is set, this bit will be ignored during masking process - * - * @param {Number} row - * @param {Number} col - * @param {Boolean} value - * @param {Boolean} reserved - */ -BitMatrix.prototype.set = function (row, col, value, reserved) { - var index = row * this.size + col - this.data[index] = value - if (reserved) this.reservedBit[index] = true -} - -/** - * Returns bit value at specified location - * - * @param {Number} row - * @param {Number} col - * @return {Boolean} - */ -BitMatrix.prototype.get = function (row, col) { - return this.data[row * this.size + col] -} - -/** - * Applies xor operator at specified location - * (used during masking process) - * - * @param {Number} row - * @param {Number} col - * @param {Boolean} value - */ -BitMatrix.prototype.xor = function (row, col, value) { - this.data[row * this.size + col] ^= value -} - -/** - * Check if bit at specified location is reserved - * - * @param {Number} row - * @param {Number} col - * @return {Boolean} - */ -BitMatrix.prototype.isReserved = function (row, col) { - return this.reservedBit[row * this.size + col] -} - -module.exports = BitMatrix - - -/***/ }), - -/***/ 290: -/***/ (function(__unusedmodule, exports) { - -var numeric = '[0-9]+' -var alphanumeric = '[A-Z $%*+\\-./:]+' -var kanji = '(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|' + - '[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|' + - '[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|' + - '[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+' -kanji = kanji.replace(/u/g, '\\u') - -var byte = '(?:(?![A-Z0-9 $%*+\\-./:]|' + kanji + ')(?:.|[\r\n]))+' - -exports.KANJI = new RegExp(kanji, 'g') -exports.BYTE_KANJI = new RegExp('[^A-Z0-9 $%*+\\-./:]+', 'g') -exports.BYTE = new RegExp(byte, 'g') -exports.NUMERIC = new RegExp(numeric, 'g') -exports.ALPHANUMERIC = new RegExp(alphanumeric, 'g') - -var TEST_KANJI = new RegExp('^' + kanji + '$') -var TEST_NUMERIC = new RegExp('^' + numeric + '$') -var TEST_ALPHANUMERIC = new RegExp('^[A-Z0-9 $%*+\\-./:]+$') - -exports.testKanji = function testKanji (str) { - return TEST_KANJI.test(str) -} - -exports.testNumeric = function testNumeric (str) { - return TEST_NUMERIC.test(str) -} - -exports.testAlphanumeric = function testAlphanumeric (str) { - return TEST_ALPHANUMERIC.test(str) -} - - -/***/ }), - -/***/ 293: -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = void 0; - -var _rng = _interopRequireDefault(__webpack_require__(506)); - -var _stringify = _interopRequireDefault(__webpack_require__(960)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function v4(options, buf, offset) { - options = options || {}; - - const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` - - - rnds[6] = rnds[6] & 0x0f | 0x40; - rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided - - if (buf) { - offset = offset || 0; - - for (let i = 0; i < 16; ++i) { - buf[offset + i] = rnds[i]; + options(requestUrl, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); + }); } - - return buf; - } - - return (0, _stringify.default)(rnds); -} - -var _default = v4; -exports.default = _default; - -/***/ }), - -/***/ 296: -/***/ (function(module, __unusedexports, __webpack_require__) { - -var BufferUtil = __webpack_require__(628) -var Mode = __webpack_require__(364) - -function ByteData (data) { - this.mode = Mode.BYTE - this.data = BufferUtil.from(data) -} - -ByteData.getBitsLength = function getBitsLength (length) { - return length * 8 -} - -ByteData.prototype.getLength = function getLength () { - return this.data.length -} - -ByteData.prototype.getBitsLength = function getBitsLength () { - return ByteData.getBitsLength(this.data.length) -} - -ByteData.prototype.write = function (bitBuffer) { - for (var i = 0, l = this.data.length; i < l; i++) { - bitBuffer.put(this.data[i], 8) - } -} - -module.exports = ByteData - - -/***/ }), - -/***/ 319: -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - - -var interlaceUtils = __webpack_require__(724); - -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'); + get(requestUrl, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('GET', requestUrl, null, additionalHeaders || {}); + }); } - - 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'); + del(requestUrl, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('DELETE', requestUrl, null, additionalHeaders || {}); + }); } - - 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'); + post(requestUrl, data, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('POST', requestUrl, data, additionalHeaders || {}); + }); } - - 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'); + patch(requestUrl, data, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('PATCH', requestUrl, data, additionalHeaders || {}); + }); } - 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; + put(requestUrl, data, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('PUT', requestUrl, data, additionalHeaders || {}); + }); } - } - - 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'); - } + head(requestUrl, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('HEAD', requestUrl, null, additionalHeaders || {}); + }); } - }; -} - -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 + sendStream(verb, requestUrl, stream, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream, additionalHeaders); + }); } - } - 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); + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl, additionalHeaders = {}) { + return __awaiter(this, void 0, void 0, function* () { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - 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); + postJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - else { - mapImageCustomBit(images[imageIndex], pxData, getPxPos, bpp, bits, maxBit); + putJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - } - if (depth === 8) { - if (rawPos !== data.length) { - throw new Error('extra data found'); + patchJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); } - } - else { - bits.end(); - } - - return pxData; -}; - - -/***/ }), - -/***/ 329: -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = void 0; - -var _crypto = _interopRequireDefault(__webpack_require__(417)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function sha1(bytes) { - if (Array.isArray(bytes)) { - bytes = Buffer.from(bytes); - } else if (typeof bytes === 'string') { - bytes = Buffer.from(bytes, 'utf8'); - } - - return _crypto.default.createHash('sha1').update(bytes).digest(); -} - -var _default = sha1; -exports.default = _default; - -/***/ }), - -/***/ 335: -/***/ (function(module) { - -function allocUnsafe (size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be a number') - } - - if (size < 0) { - throw new RangeError('"size" argument must not be negative') - } - - if (Buffer.allocUnsafe) { - return Buffer.allocUnsafe(size) - } else { - return new Buffer(size) - } -} - -module.exports = allocUnsafe - - -/***/ }), - -/***/ 345: -/***/ (function(module, __unusedexports, __webpack_require__) { - -var bufferFill = __webpack_require__(93) -var allocUnsafe = __webpack_require__(335) - -module.exports = function alloc (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be a number') - } - - if (size < 0) { - throw new RangeError('"size" argument must not be negative') - } - - if (Buffer.alloc) { - return Buffer.alloc(size, fill, encoding) - } - - var buffer = allocUnsafe(size) - - if (size === 0) { - return buffer - } - - if (fill === undefined) { - return bufferFill(buffer, 0) - } - - if (typeof encoding !== 'string') { - encoding = undefined - } - - return bufferFill(buffer, fill, encoding) -} - - -/***/ }), - -/***/ 355: -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -var Utils = __webpack_require__(621) - -var BLOCK_CHAR = { - WW: ' ', - WB: '▄', - BB: '█', - BW: '▀' -} - -var INVERTED_BLOCK_CHAR = { - BB: ' ', - BW: '▄', - WW: '█', - WB: '▀' -} - -function getBlockChar (top, bottom, blocks) { - if (top && bottom) return blocks.BB - if (top && !bottom) return blocks.BW - if (!top && bottom) return blocks.WB - return blocks.WW -} - -exports.render = function (qrData, options, cb) { - var opts = Utils.getOptions(options) - var blocks = BLOCK_CHAR - if (opts.color.dark.hex === '#ffffff' || opts.color.light.hex === '#000000') { - blocks = INVERTED_BLOCK_CHAR - } - - var size = qrData.modules.size - var data = qrData.modules.data - - var output = '' - var hMargin = Array(size + (opts.margin * 2) + 1).join(blocks.WW) - hMargin = Array((opts.margin / 2) + 1).join(hMargin + '\n') - - var vMargin = Array(opts.margin + 1).join(blocks.WW) - - output += hMargin - for (var i = 0; i < size; i += 2) { - output += vMargin - for (var j = 0; j < size; j++) { - var topModule = data[i * size + j] - var bottomModule = data[(i + 1) * size + j] - - output += getBlockChar(topModule, bottomModule, blocks) + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error('Client has already been disposed.'); + } + const parsedUrl = new URL(requestUrl); + let info = this._prepareRequest(verb, parsedUrl, headers); + // Only perform retries on reads since writes may not be idempotent. + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) + ? this._maxRetries + 1 + : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info, data); + // Check if it's an authentication challenge + if (response && + response.message && + response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info, data); + } + else { + // We have received an unauthorized response but have no handlers to handle it. + // Let the response return to the caller. + return response; + } + } + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && + HttpRedirectCodes.includes(response.message.statusCode) && + this._allowRedirects && + redirectsRemaining > 0) { + const redirectUrl = response.message.headers['location']; + if (!redirectUrl) { + // if there's no location to redirect to, we won't + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === 'https:' && + parsedUrl.protocol !== parsedRedirectUrl.protocol && + !this._allowRedirectDowngrade) { + throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.'); + } + // we need to finish reading the response before reassigning response + // which will leak the open socket. + yield response.readBody(); + // strip authorization header if redirected to a different hostname + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + // header names are case insensitive + if (header.toLowerCase() === 'authorization') { + delete headers[header]; + } + } + } + // let's make the request with the new redirectUrl + info = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info, data); + redirectsRemaining--; + } + if (!response.message.statusCode || + !HttpResponseRetryCodes.includes(response.message.statusCode)) { + // If not a retry code, return immediately instead of retrying + return response; + } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; + }); + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); + } + this._disposed = true; + } + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info, data) { + return __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } + else if (!res) { + // If `err` is not passed, then `res` must be passed. + reject(new Error('Unknown error')); + } + else { + resolve(res); + } + } + this.requestRawWithCallback(info, data, callbackForResult); + }); + }); + } + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info, data, onResult) { + if (typeof data === 'string') { + if (!info.options.headers) { + info.options.headers = {}; + } + info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8'); + } + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } + } + const req = info.httpModule.request(info.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(undefined, res); + }); + let socket; + req.on('socket', sock => { + socket = sock; + }); + // If we ever get disconnected, we want the socket to timeout eventually + req.setTimeout(this._socketTimeout || 3 * 60000, () => { + if (socket) { + socket.end(); + } + handleResult(new Error(`Request timeout: ${info.options.path}`)); + }); + req.on('error', function (err) { + // err has statusCode property + // res should have headers + handleResult(err); + }); + if (data && typeof data === 'string') { + req.write(data, 'utf8'); + } + if (data && typeof data !== 'string') { + data.on('close', function () { + req.end(); + }); + data.pipe(req); + } + else { + req.end(); + } + } + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); + } + _prepareRequest(method, requestUrl, headers) { + const info = {}; + info.parsedUrl = requestUrl; + const usingSsl = info.parsedUrl.protocol === 'https:'; + info.httpModule = usingSsl ? https : http; + const defaultPort = usingSsl ? 443 : 80; + info.options = {}; + info.options.host = info.parsedUrl.hostname; + info.options.port = info.parsedUrl.port + ? parseInt(info.parsedUrl.port) + : defaultPort; + info.options.path = + (info.parsedUrl.pathname || '') + (info.parsedUrl.search || ''); + info.options.method = method; + info.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info.options.headers['user-agent'] = this.userAgent; + } + info.options.agent = this._getAgent(info.parsedUrl); + // gives handlers an opportunity to participate + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info.options); + } + } + return info; + } + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); + } + return lowercaseKeys(headers || {}); + } + _getExistingOrDefaultHeader(additionalHeaders, header, _default) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; + } + return additionalHeaders[header] || clientHeader || _default; + } + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; + } + if (this._keepAlive && !useProxy) { + agent = this._agent; + } + // if agent is already assigned use that agent. + if (agent) { + return agent; + } + const usingSsl = parsedUrl.protocol === 'https:'; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + // This is `useProxy` again, but we need to check `proxyURl` directly for TypeScripts's flow analysis. + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, ((proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + })), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === 'https:'; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; + } + else { + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; + } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; + } + // if reusing agent across request and tunneling agent isn't assigned create a new agent + if (this._keepAlive && !agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https.Agent(options) : new http.Agent(options); + this._agent = agent; + } + // if not using private agent and tunnel agent isn't setup then use global agent + if (!agent) { + agent = usingSsl ? https.globalAgent : http.globalAgent; + } + if (usingSsl && this._ignoreSslError) { + // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process + // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options + // we have to cast it to any and change it directly + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); + } + return agent; + } + _performExponentialBackoff(retryNumber) { + return __awaiter(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise(resolve => setTimeout(() => resolve(), ms)); + }); + } + _processResponse(res, options) { + return __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + // not found leads to null obj returned + if (statusCode === HttpCodes.NotFound) { + resolve(response); + } + // get the result from the body + function dateTimeDeserializer(key, value) { + if (typeof value === 'string') { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } + else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } + catch (err) { + // Invalid resource (contents not json); leaving result obj null + } + // note that 3xx redirects are handled by the http layer. + if (statusCode > 299) { + let msg; + // if exception/error in body, attempt to get better error + if (obj && obj.message) { + msg = obj.message; + } + else if (contents && contents.length > 0) { + // it may be the case that the exception is in the body message as string + msg = contents; + } + else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } + else { + resolve(response); + } + })); + }); } - - output += vMargin + '\n' - } - - output += hMargin.slice(0, -1) - - if (typeof cb === 'function') { - cb(null, output) - } - - return output -} - -exports.renderToFile = function renderToFile (path, qrData, options, cb) { - if (typeof cb === 'undefined') { - cb = options - options = undefined - } - - var fs = __webpack_require__(747) - var utf8 = exports.render(qrData, options) - fs.writeFile(path, utf8, cb) -} - - -/***/ }), - -/***/ 357: -/***/ (function(module) { - -module.exports = require("assert"); - -/***/ }), - -/***/ 363: -/***/ (function(module, __unusedexports, __webpack_require__) { - -var Mode = __webpack_require__(364) - -function NumericData (data) { - this.mode = Mode.NUMERIC - this.data = data.toString() -} - -NumericData.getBitsLength = function getBitsLength (length) { - return 10 * Math.floor(length / 3) + ((length % 3) ? ((length % 3) * 3 + 1) : 0) -} - -NumericData.prototype.getLength = function getLength () { - return this.data.length -} - -NumericData.prototype.getBitsLength = function getBitsLength () { - return NumericData.getBitsLength(this.data.length) -} - -NumericData.prototype.write = function write (bitBuffer) { - var i, group, value - - // The input data string is divided into groups of three digits, - // and each group is converted to its 10-bit binary equivalent. - for (i = 0; i + 3 <= this.data.length; i += 3) { - group = this.data.substr(i, 3) - value = parseInt(group, 10) - - bitBuffer.put(value, 10) - } - - // If the number of input digits is not an exact multiple of three, - // the final one or two digits are converted to 4 or 7 bits respectively. - var remainingNum = this.data.length - i - if (remainingNum > 0) { - group = this.data.substr(i) - value = parseInt(group, 10) - - bitBuffer.put(value, remainingNum * 3 + 1) - } -} - -module.exports = NumericData - - -/***/ }), - -/***/ 364: -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -var VersionCheck = __webpack_require__(54) -var Regex = __webpack_require__(290) - -/** - * Numeric mode encodes data from the decimal digit set (0 - 9) - * (byte values 30HEX to 39HEX). - * Normally, 3 data characters are represented by 10 bits. - * - * @type {Object} - */ -exports.NUMERIC = { - id: 'Numeric', - bit: 1 << 0, - ccBits: [10, 12, 14] -} - -/** - * Alphanumeric mode encodes data from a set of 45 characters, - * i.e. 10 numeric digits (0 - 9), - * 26 alphabetic characters (A - Z), - * and 9 symbols (SP, $, %, *, +, -, ., /, :). - * Normally, two input characters are represented by 11 bits. - * - * @type {Object} - */ -exports.ALPHANUMERIC = { - id: 'Alphanumeric', - bit: 1 << 1, - ccBits: [9, 11, 13] -} - -/** - * In byte mode, data is encoded at 8 bits per character. - * - * @type {Object} - */ -exports.BYTE = { - id: 'Byte', - bit: 1 << 2, - ccBits: [8, 16, 16] -} - -/** - * The Kanji mode efficiently encodes Kanji characters in accordance with - * the Shift JIS system based on JIS X 0208. - * The Shift JIS values are shifted from the JIS X 0208 values. - * JIS X 0208 gives details of the shift coded representation. - * Each two-byte character value is compacted to a 13-bit binary codeword. - * - * @type {Object} - */ -exports.KANJI = { - id: 'Kanji', - bit: 1 << 3, - ccBits: [8, 10, 12] -} - -/** - * Mixed mode will contain a sequences of data in a combination of any of - * the modes described above - * - * @type {Object} - */ -exports.MIXED = { - bit: -1 -} - -/** - * Returns the number of bits needed to store the data length - * according to QR Code specifications. - * - * @param {Mode} mode Data mode - * @param {Number} version QR Code version - * @return {Number} Number of bits - */ -exports.getCharCountIndicator = function getCharCountIndicator (mode, version) { - if (!mode.ccBits) throw new Error('Invalid mode: ' + mode) - - if (!VersionCheck.isValid(version)) { - throw new Error('Invalid version: ' + version) - } - - if (version >= 1 && version < 10) return mode.ccBits[0] - else if (version < 27) return mode.ccBits[1] - return mode.ccBits[2] -} - -/** - * Returns the most efficient mode to store the specified data - * - * @param {String} dataStr Input data string - * @return {Mode} Best mode - */ -exports.getBestModeForData = function getBestModeForData (dataStr) { - if (Regex.testNumeric(dataStr)) return exports.NUMERIC - else if (Regex.testAlphanumeric(dataStr)) return exports.ALPHANUMERIC - else if (Regex.testKanji(dataStr)) return exports.KANJI - else return exports.BYTE -} - -/** - * Return mode name as string - * - * @param {Mode} mode Mode object - * @returns {String} Mode name - */ -exports.toString = function toString (mode) { - if (mode && mode.id) return mode.id - throw new Error('Invalid mode') -} - -/** - * Check if input param is a valid mode object - * - * @param {Mode} mode Mode object - * @returns {Boolean} True if valid mode, false otherwise - */ -exports.isValid = function isValid (mode) { - return mode && mode.bit && mode.ccBits -} - -/** - * Get mode object from its name - * - * @param {String} string Mode name - * @returns {Mode} Mode object - */ -function fromString (string) { - if (typeof string !== 'string') { - throw new Error('Param is not a string') - } - - var lcStr = string.toLowerCase() - - switch (lcStr) { - case 'numeric': - return exports.NUMERIC - case 'alphanumeric': - return exports.ALPHANUMERIC - case 'kanji': - return exports.KANJI - case 'byte': - return exports.BYTE - default: - throw new Error('Unknown mode: ' + string) - } -} - -/** - * Returns mode from a value. - * If value is not a valid mode, returns defaultValue - * - * @param {Mode|String} value Encoding mode - * @param {Mode} defaultValue Fallback value - * @return {Mode} Encoding mode - */ -exports.from = function from (value, defaultValue) { - if (exports.isValid(value)) { - return value - } - - try { - return fromString(value) - } catch (e) { - return defaultValue - } } - - -/***/ }), - -/***/ 407: -/***/ (function(module) { - -module.exports = require("buffer"); - -/***/ }), - -/***/ 413: -/***/ (function(module, __unusedexports, __webpack_require__) { - -module.exports = __webpack_require__(141); - - -/***/ }), - -/***/ 417: -/***/ (function(module) { - -module.exports = require("crypto"); +exports.HttpClient = HttpClient; +const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); +//# sourceMappingURL=index.js.map /***/ }), -/***/ 424: -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -var Utils = __webpack_require__(114) -var ECCode = __webpack_require__(189) -var ECLevel = __webpack_require__(50) -var Mode = __webpack_require__(364) -var VersionCheck = __webpack_require__(54) -var isArray = __webpack_require__(714) +/***/ 4988: +/***/ ((__unused_webpack_module, exports) => { -// Generator polynomial used to encode version information -var G18 = (1 << 12) | (1 << 11) | (1 << 10) | (1 << 9) | (1 << 8) | (1 << 5) | (1 << 2) | (1 << 0) -var G18_BCH = Utils.getBCHDigit(G18) +"use strict"; -function getBestVersionForDataLength (mode, length, errorCorrectionLevel) { - for (var currentVersion = 1; currentVersion <= 40; currentVersion++) { - if (length <= exports.getCapacity(currentVersion, errorCorrectionLevel, mode)) { - return currentVersion +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.checkBypass = exports.getProxyUrl = void 0; +function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === 'https:'; + if (checkBypass(reqUrl)) { + return undefined; } - } - - return undefined -} - -function getReservedBitsCount (mode, version) { - // Character count indicator + mode indicator bits - return Mode.getCharCountIndicator(mode, version) + 4 -} - -function getTotalBitsFromDataArray (segments, version) { - var totalBits = 0 - - segments.forEach(function (data) { - var reservedBits = getReservedBitsCount(data.mode, version) - totalBits += reservedBits + data.getBitsLength() - }) - - return totalBits -} - -function getBestVersionForMixedData (segments, errorCorrectionLevel) { - for (var currentVersion = 1; currentVersion <= 40; currentVersion++) { - var length = getTotalBitsFromDataArray(segments, currentVersion) - if (length <= exports.getCapacity(currentVersion, errorCorrectionLevel, Mode.MIXED)) { - return currentVersion + const proxyVar = (() => { + if (usingSsl) { + return process.env['https_proxy'] || process.env['HTTPS_PROXY']; + } + else { + return process.env['http_proxy'] || process.env['HTTP_PROXY']; + } + })(); + if (proxyVar) { + return new URL(proxyVar); + } + else { + return undefined; } - } - - return undefined } - -/** - * Returns version number from a value. - * If value is not a valid version, returns defaultValue - * - * @param {Number|String} value QR Code version - * @param {Number} defaultValue Fallback value - * @return {Number} QR Code version number - */ -exports.from = function from (value, defaultValue) { - if (VersionCheck.isValid(value)) { - return parseInt(value, 10) - } - - return defaultValue +exports.getProxyUrl = getProxyUrl; +function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; + } + const noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || ''; + if (!noProxy) { + return false; + } + // Determine the request port + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } + else if (reqUrl.protocol === 'http:') { + reqPort = 80; + } + else if (reqUrl.protocol === 'https:') { + reqPort = 443; + } + // Format the request hostname and hostname with port + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === 'number') { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + } + // Compare request host against noproxy + for (const upperNoProxyItem of noProxy + .split(',') + .map(x => x.trim().toUpperCase()) + .filter(x => x)) { + if (upperReqHosts.some(x => x === upperNoProxyItem)) { + return true; + } + } + return false; } +exports.checkBypass = checkBypass; +//# sourceMappingURL=proxy.js.map -/** - * Returns how much data can be stored with the specified QR code version - * and error correction level - * - * @param {Number} version QR Code version (1-40) - * @param {Number} errorCorrectionLevel Error correction level - * @param {Mode} mode Data mode - * @return {Number} Quantity of storable data - */ -exports.getCapacity = function getCapacity (version, errorCorrectionLevel, mode) { - if (!VersionCheck.isValid(version)) { - throw new Error('Invalid QR Code version') - } - - // Use Byte mode as default - if (typeof mode === 'undefined') mode = Mode.BYTE - - // Total codewords for this QR code version (Data + Error correction) - var totalCodewords = Utils.getSymbolTotalCodewords(version) - - // Total number of error correction codewords - var ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel) - - // Total number of data codewords - var dataTotalCodewordsBits = (totalCodewords - ecTotalCodewords) * 8 - - if (mode === Mode.MIXED) return dataTotalCodewordsBits - - var usableBits = dataTotalCodewordsBits - getReservedBitsCount(mode, version) - - // Return max number of storable codewords - switch (mode) { - case Mode.NUMERIC: - return Math.floor((usableBits / 10) * 3) +/***/ }), - case Mode.ALPHANUMERIC: - return Math.floor((usableBits / 11) * 2) +/***/ 5207: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - case Mode.KANJI: - return Math.floor(usableBits / 13) +"use strict"; - case Mode.BYTE: - default: - return Math.floor(usableBits / 8) - } +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (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.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var _a; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getCmdPath = exports.tryGetExecutablePath = exports.isRooted = exports.isDirectory = exports.exists = exports.READONLY = exports.UV_FS_O_EXLOCK = exports.IS_WINDOWS = exports.unlink = exports.symlink = exports.stat = exports.rmdir = exports.rm = exports.rename = exports.readlink = exports.readdir = exports.open = exports.mkdir = exports.lstat = exports.copyFile = exports.chmod = void 0; +const fs = __importStar(__nccwpck_require__(9896)); +const path = __importStar(__nccwpck_require__(6928)); +_a = fs.promises +// export const {open} = 'fs' +, exports.chmod = _a.chmod, exports.copyFile = _a.copyFile, exports.lstat = _a.lstat, exports.mkdir = _a.mkdir, exports.open = _a.open, exports.readdir = _a.readdir, exports.readlink = _a.readlink, exports.rename = _a.rename, exports.rm = _a.rm, exports.rmdir = _a.rmdir, exports.stat = _a.stat, exports.symlink = _a.symlink, exports.unlink = _a.unlink; +// export const {open} = 'fs' +exports.IS_WINDOWS = process.platform === 'win32'; +// See https://github.com/nodejs/node/blob/d0153aee367422d0858105abec186da4dff0a0c5/deps/uv/include/uv/win.h#L691 +exports.UV_FS_O_EXLOCK = 0x10000000; +exports.READONLY = fs.constants.O_RDONLY; +function exists(fsPath) { + return __awaiter(this, void 0, void 0, function* () { + try { + yield exports.stat(fsPath); + } + catch (err) { + if (err.code === 'ENOENT') { + return false; + } + throw err; + } + return true; + }); } - -/** - * Returns the minimum version needed to contain the amount of data - * - * @param {Segment} data Segment of data - * @param {Number} [errorCorrectionLevel=H] Error correction level - * @param {Mode} mode Data mode - * @return {Number} QR Code version - */ -exports.getBestVersionForData = function getBestVersionForData (data, errorCorrectionLevel) { - var seg - - var ecl = ECLevel.from(errorCorrectionLevel, ECLevel.M) - - if (isArray(data)) { - if (data.length > 1) { - return getBestVersionForMixedData(data, ecl) - } - - if (data.length === 0) { - return 1 - } - - seg = data[0] - } else { - seg = data - } - - return getBestVersionForDataLength(seg.mode, seg.getLength(), ecl) +exports.exists = exists; +function isDirectory(fsPath, useStat = false) { + return __awaiter(this, void 0, void 0, function* () { + const stats = useStat ? yield exports.stat(fsPath) : yield exports.lstat(fsPath); + return stats.isDirectory(); + }); } - +exports.isDirectory = isDirectory; /** - * Returns version information with relative error correction bits - * - * The version information is included in QR Code symbols of version 7 or larger. - * It consists of an 18-bit sequence containing 6 data bits, - * with 12 error correction bits calculated using the (18, 6) Golay code. - * - * @param {Number} version QR Code version - * @return {Number} Encoded version info bits + * On OSX/Linux, true if path starts with '/'. On Windows, true for paths like: + * \, \hello, \\hello\share, C:, and C:\hello (and corresponding alternate separator cases). */ -exports.getEncodedBits = function getEncodedBits (version) { - if (!VersionCheck.isValid(version) || version < 7) { - throw new Error('Invalid QR Code version') - } - - var d = version << 12 - - while (Utils.getBCHDigit(d) - G18_BCH >= 0) { - d ^= (G18 << (Utils.getBCHDigit(d) - G18_BCH)) - } - - return (version << 12) | d +function isRooted(p) { + p = normalizeSeparators(p); + if (!p) { + throw new Error('isRooted() parameter "p" cannot be empty'); + } + if (exports.IS_WINDOWS) { + return (p.startsWith('\\') || /^[A-Z]:/i.test(p) // e.g. \ or \hello or \\hello + ); // e.g. C: or C:\hello + } + return p.startsWith('/'); } - +exports.isRooted = isRooted; +/** + * Best effort attempt to determine whether a file exists and is executable. + * @param filePath file path to check + * @param extensions additional file extensions to try + * @return if file exists and is executable, returns the file path. otherwise empty string. + */ +function tryGetExecutablePath(filePath, extensions) { + return __awaiter(this, void 0, void 0, function* () { + let stats = undefined; + try { + // test file exists + stats = yield exports.stat(filePath); + } + catch (err) { + if (err.code !== 'ENOENT') { + // eslint-disable-next-line no-console + console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); + } + } + if (stats && stats.isFile()) { + if (exports.IS_WINDOWS) { + // on Windows, test for valid extension + const upperExt = path.extname(filePath).toUpperCase(); + if (extensions.some(validExt => validExt.toUpperCase() === upperExt)) { + return filePath; + } + } + else { + if (isUnixExecutable(stats)) { + return filePath; + } + } + } + // try each extension + const originalFilePath = filePath; + for (const extension of extensions) { + filePath = originalFilePath + extension; + stats = undefined; + try { + stats = yield exports.stat(filePath); + } + catch (err) { + if (err.code !== 'ENOENT') { + // eslint-disable-next-line no-console + console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); + } + } + if (stats && stats.isFile()) { + if (exports.IS_WINDOWS) { + // preserve the case of the actual file (since an extension was appended) + try { + const directory = path.dirname(filePath); + const upperName = path.basename(filePath).toUpperCase(); + for (const actualName of yield exports.readdir(directory)) { + if (upperName === actualName.toUpperCase()) { + filePath = path.join(directory, actualName); + break; + } + } + } + catch (err) { + // eslint-disable-next-line no-console + console.log(`Unexpected error attempting to determine the actual case of the file '${filePath}': ${err}`); + } + return filePath; + } + else { + if (isUnixExecutable(stats)) { + return filePath; + } + } + } + } + return ''; + }); +} +exports.tryGetExecutablePath = tryGetExecutablePath; +function normalizeSeparators(p) { + p = p || ''; + if (exports.IS_WINDOWS) { + // convert slashes on Windows + p = p.replace(/\//g, '\\'); + // remove redundant slashes + return p.replace(/\\\\+/g, '\\'); + } + // remove redundant slashes + return p.replace(/\/\/+/g, '/'); +} +// on Mac/Linux, test the execute bit +// R W X R W X R W X +// 256 128 64 32 16 8 4 2 1 +function isUnixExecutable(stats) { + return ((stats.mode & 1) > 0 || + ((stats.mode & 8) > 0 && stats.gid === process.getgid()) || + ((stats.mode & 64) > 0 && stats.uid === process.getuid())); +} +// Get the path of cmd.exe in windows +function getCmdPath() { + var _a; + return (_a = process.env['COMSPEC']) !== null && _a !== void 0 ? _a : `cmd.exe`; +} +exports.getCmdPath = getCmdPath; +//# sourceMappingURL=io-util.js.map /***/ }), -/***/ 425: -/***/ (function(__unusedmodule, exports, __webpack_require__) { +/***/ 4994: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; -/* eslint-disable @typescript-eslint/no-explicit-any */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); @@ -3633,818 +2841,1441 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; -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(__webpack_require__(605)); -const https = __importStar(__webpack_require__(211)); -const pm = __importStar(__webpack_require__(177)); -const tunnel = __importStar(__webpack_require__(413)); -var HttpCodes; -(function (HttpCodes) { - HttpCodes[HttpCodes["OK"] = 200] = "OK"; - HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices"; - HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently"; - HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved"; - HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther"; - HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified"; - HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy"; - HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy"; - HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect"; - HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect"; - HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest"; - HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized"; - HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired"; - HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden"; - HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound"; - HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed"; - HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable"; - HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; - HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout"; - HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict"; - HttpCodes[HttpCodes["Gone"] = 410] = "Gone"; - HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests"; - HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError"; - HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented"; - HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; - HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; - HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; -})(HttpCodes = exports.HttpCodes || (exports.HttpCodes = {})); -var Headers; -(function (Headers) { - Headers["Accept"] = "accept"; - Headers["ContentType"] = "content-type"; -})(Headers = exports.Headers || (exports.Headers = {})); -var MediaTypes; -(function (MediaTypes) { - MediaTypes["ApplicationJson"] = "application/json"; -})(MediaTypes = exports.MediaTypes || (exports.MediaTypes = {})); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.findInPath = exports.which = exports.mkdirP = exports.rmRF = exports.mv = exports.cp = void 0; +const assert_1 = __nccwpck_require__(2613); +const path = __importStar(__nccwpck_require__(6928)); +const ioUtil = __importStar(__nccwpck_require__(5207)); /** - * Returns the proxy URL, depending upon the supplied url and proxy environment variables. - * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + * Copies a file or folder. + * Based off of shelljs - https://github.com/shelljs/shelljs/blob/9237f66c52e5daa40458f94f9565e18e8132f5a6/src/cp.js + * + * @param source source path + * @param dest destination path + * @param options optional. See CopyOptions. */ -function getProxyUrl(serverUrl) { - const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); - return proxyUrl ? proxyUrl.href : ''; -} -exports.getProxyUrl = getProxyUrl; -const HttpRedirectCodes = [ - HttpCodes.MovedPermanently, - HttpCodes.ResourceMoved, - HttpCodes.SeeOther, - HttpCodes.TemporaryRedirect, - HttpCodes.PermanentRedirect -]; -const HttpResponseRetryCodes = [ - HttpCodes.BadGateway, - HttpCodes.ServiceUnavailable, - HttpCodes.GatewayTimeout -]; -const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD']; -const ExponentialBackoffCeiling = 10; -const ExponentialBackoffTimeSlice = 5; -class HttpClientError extends Error { - constructor(message, statusCode) { - super(message); - this.name = 'HttpClientError'; - this.statusCode = statusCode; - Object.setPrototypeOf(this, HttpClientError.prototype); - } -} -exports.HttpClientError = HttpClientError; -class HttpClientResponse { - constructor(message) { - this.message = message; - } - readBody() { - return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { - let output = Buffer.alloc(0); - this.message.on('data', (chunk) => { - output = Buffer.concat([output, chunk]); - }); - this.message.on('end', () => { - resolve(output.toString()); - }); - })); - }); - } -} -exports.HttpClientResponse = HttpClientResponse; -function isHttps(requestUrl) { - const parsedUrl = new URL(requestUrl); - return parsedUrl.protocol === 'https:'; -} -exports.isHttps = isHttps; -class HttpClient { - constructor(userAgent, handlers, requestOptions) { - this._ignoreSslError = false; - this._allowRedirects = true; - this._allowRedirectDowngrade = false; - this._maxRedirects = 50; - this._allowRetries = false; - this._maxRetries = 1; - this._keepAlive = false; - this._disposed = false; - this.userAgent = userAgent; - this.handlers = handlers || []; - this.requestOptions = requestOptions; - if (requestOptions) { - if (requestOptions.ignoreSslError != null) { - this._ignoreSslError = requestOptions.ignoreSslError; - } - this._socketTimeout = requestOptions.socketTimeout; - if (requestOptions.allowRedirects != null) { - this._allowRedirects = requestOptions.allowRedirects; - } - if (requestOptions.allowRedirectDowngrade != null) { - this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; - } - if (requestOptions.maxRedirects != null) { - this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); - } - if (requestOptions.keepAlive != null) { - this._keepAlive = requestOptions.keepAlive; +function cp(source, dest, options = {}) { + return __awaiter(this, void 0, void 0, function* () { + const { force, recursive, copySourceDirectory } = readCopyOptions(options); + const destStat = (yield ioUtil.exists(dest)) ? yield ioUtil.stat(dest) : null; + // Dest is an existing file, but not forcing + if (destStat && destStat.isFile() && !force) { + return; + } + // If dest is an existing directory, should copy inside. + const newDest = destStat && destStat.isDirectory() && copySourceDirectory + ? path.join(dest, path.basename(source)) + : dest; + if (!(yield ioUtil.exists(source))) { + throw new Error(`no such file or directory: ${source}`); + } + const sourceStat = yield ioUtil.stat(source); + if (sourceStat.isDirectory()) { + if (!recursive) { + throw new Error(`Failed to copy. ${source} is a directory, but tried to copy without recursive flag.`); } - if (requestOptions.allowRetries != null) { - this._allowRetries = requestOptions.allowRetries; + else { + yield cpDirRecursive(source, newDest, 0, force); } - if (requestOptions.maxRetries != null) { - this._maxRetries = requestOptions.maxRetries; + } + else { + if (path.relative(source, newDest) === '') { + // a file cannot be copied to itself + throw new Error(`'${newDest}' and '${source}' are the same file`); } + yield copyFile(source, newDest, force); } - } - options(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); - }); - } - get(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('GET', requestUrl, null, additionalHeaders || {}); - }); - } - del(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('DELETE', requestUrl, null, additionalHeaders || {}); - }); - } - post(requestUrl, data, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('POST', requestUrl, data, additionalHeaders || {}); - }); - } - patch(requestUrl, data, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('PATCH', requestUrl, data, additionalHeaders || {}); - }); - } - put(requestUrl, data, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('PUT', requestUrl, data, additionalHeaders || {}); - }); - } - head(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('HEAD', requestUrl, null, additionalHeaders || {}); - }); - } - sendStream(verb, requestUrl, stream, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request(verb, requestUrl, stream, additionalHeaders); - }); - } - /** - * Gets a typed object from an endpoint - * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise - */ - getJson(requestUrl, additionalHeaders = {}) { - return __awaiter(this, void 0, void 0, function* () { - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - const res = yield this.get(requestUrl, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); - } - postJson(requestUrl, obj, additionalHeaders = {}) { - return __awaiter(this, void 0, void 0, function* () { - const data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); - const res = yield this.post(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); - } - putJson(requestUrl, obj, additionalHeaders = {}) { - return __awaiter(this, void 0, void 0, function* () { - const data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); - const res = yield this.put(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); - } - patchJson(requestUrl, obj, additionalHeaders = {}) { - return __awaiter(this, void 0, void 0, function* () { - const data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); - const res = yield this.patch(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); - } - /** - * Makes a raw http request. - * All other methods such as get, post, patch, and request ultimately call this. - * Prefer get, del, post and patch - */ - request(verb, requestUrl, data, headers) { - return __awaiter(this, void 0, void 0, function* () { - if (this._disposed) { - throw new Error('Client has already been disposed.'); + }); +} +exports.cp = cp; +/** + * Moves a path. + * + * @param source source path + * @param dest destination path + * @param options optional. See MoveOptions. + */ +function mv(source, dest, options = {}) { + return __awaiter(this, void 0, void 0, function* () { + if (yield ioUtil.exists(dest)) { + let destExists = true; + if (yield ioUtil.isDirectory(dest)) { + // If dest is directory copy src into dest + dest = path.join(dest, path.basename(source)); + destExists = yield ioUtil.exists(dest); } - const parsedUrl = new URL(requestUrl); - let info = this._prepareRequest(verb, parsedUrl, headers); - // Only perform retries on reads since writes may not be idempotent. - const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) - ? this._maxRetries + 1 - : 1; - let numTries = 0; - let response; - do { - response = yield this.requestRaw(info, data); - // Check if it's an authentication challenge - if (response && - response.message && - response.message.statusCode === HttpCodes.Unauthorized) { - let authenticationHandler; - for (const handler of this.handlers) { - if (handler.canHandleAuthentication(response)) { - authenticationHandler = handler; - break; - } - } - if (authenticationHandler) { - return authenticationHandler.handleAuthentication(this, info, data); - } - else { - // We have received an unauthorized response but have no handlers to handle it. - // Let the response return to the caller. - return response; - } + if (destExists) { + if (options.force == null || options.force) { + yield rmRF(dest); } - let redirectsRemaining = this._maxRedirects; - while (response.message.statusCode && - HttpRedirectCodes.includes(response.message.statusCode) && - this._allowRedirects && - redirectsRemaining > 0) { - const redirectUrl = response.message.headers['location']; - if (!redirectUrl) { - // if there's no location to redirect to, we won't - break; - } - const parsedRedirectUrl = new URL(redirectUrl); - if (parsedUrl.protocol === 'https:' && - parsedUrl.protocol !== parsedRedirectUrl.protocol && - !this._allowRedirectDowngrade) { - throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.'); - } - // we need to finish reading the response before reassigning response - // which will leak the open socket. - yield response.readBody(); - // strip authorization header if redirected to a different hostname - if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { - for (const header in headers) { - // header names are case insensitive - if (header.toLowerCase() === 'authorization') { - delete headers[header]; - } - } - } - // let's make the request with the new redirectUrl - info = this._prepareRequest(verb, parsedRedirectUrl, headers); - response = yield this.requestRaw(info, data); - redirectsRemaining--; + else { + throw new Error('Destination already exists'); } - if (!response.message.statusCode || - !HttpResponseRetryCodes.includes(response.message.statusCode)) { - // If not a retry code, return immediately instead of retrying - return response; + } + } + yield mkdirP(path.dirname(dest)); + yield ioUtil.rename(source, dest); + }); +} +exports.mv = mv; +/** + * Remove a path recursively with force + * + * @param inputPath path to remove + */ +function rmRF(inputPath) { + return __awaiter(this, void 0, void 0, function* () { + if (ioUtil.IS_WINDOWS) { + // Check for invalid characters + // https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file + if (/[*"<>|]/.test(inputPath)) { + throw new Error('File path must not contain `*`, `"`, `<`, `>` or `|` on Windows'); + } + } + try { + // note if path does not exist, error is silent + yield ioUtil.rm(inputPath, { + force: true, + maxRetries: 3, + recursive: true, + retryDelay: 300 + }); + } + catch (err) { + throw new Error(`File was unable to be removed ${err}`); + } + }); +} +exports.rmRF = rmRF; +/** + * Make a directory. Creates the full path with folders in between + * Will throw if it fails + * + * @param fsPath path to create + * @returns Promise + */ +function mkdirP(fsPath) { + return __awaiter(this, void 0, void 0, function* () { + assert_1.ok(fsPath, 'a path argument must be provided'); + yield ioUtil.mkdir(fsPath, { recursive: true }); + }); +} +exports.mkdirP = mkdirP; +/** + * Returns path of a tool had the tool actually been invoked. Resolves via paths. + * If you check and the tool does not exist, it will throw. + * + * @param tool name of the tool + * @param check whether to check if tool exists + * @returns Promise path to tool + */ +function which(tool, check) { + return __awaiter(this, void 0, void 0, function* () { + if (!tool) { + throw new Error("parameter 'tool' is required"); + } + // recursive when check=true + if (check) { + const result = yield which(tool, false); + if (!result) { + if (ioUtil.IS_WINDOWS) { + throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also verify the file has a valid extension for an executable file.`); } - numTries += 1; - if (numTries < maxTries) { - yield response.readBody(); - yield this._performExponentialBackoff(numTries); + else { + throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also check the file mode to verify the file is executable.`); } - } while (numTries < maxTries); - return response; - }); + } + return result; + } + const matches = yield findInPath(tool); + if (matches && matches.length > 0) { + return matches[0]; + } + return ''; + }); +} +exports.which = which; +/** + * Returns a list of all occurrences of the given tool on the system path. + * + * @returns Promise the paths of the tool + */ +function findInPath(tool) { + return __awaiter(this, void 0, void 0, function* () { + if (!tool) { + throw new Error("parameter 'tool' is required"); + } + // build the list of extensions to try + const extensions = []; + if (ioUtil.IS_WINDOWS && process.env['PATHEXT']) { + for (const extension of process.env['PATHEXT'].split(path.delimiter)) { + if (extension) { + extensions.push(extension); + } + } + } + // if it's rooted, return it if exists. otherwise return empty. + if (ioUtil.isRooted(tool)) { + const filePath = yield ioUtil.tryGetExecutablePath(tool, extensions); + if (filePath) { + return [filePath]; + } + return []; + } + // if any path separators, return empty + if (tool.includes(path.sep)) { + return []; + } + // build the list of directories + // + // Note, technically "where" checks the current directory on Windows. From a toolkit perspective, + // it feels like we should not do this. Checking the current directory seems like more of a use + // case of a shell, and the which() function exposed by the toolkit should strive for consistency + // across platforms. + const directories = []; + if (process.env.PATH) { + for (const p of process.env.PATH.split(path.delimiter)) { + if (p) { + directories.push(p); + } + } + } + // find all matches + const matches = []; + for (const directory of directories) { + const filePath = yield ioUtil.tryGetExecutablePath(path.join(directory, tool), extensions); + if (filePath) { + matches.push(filePath); + } + } + return matches; + }); +} +exports.findInPath = findInPath; +function readCopyOptions(options) { + const force = options.force == null ? true : options.force; + const recursive = Boolean(options.recursive); + const copySourceDirectory = options.copySourceDirectory == null + ? true + : Boolean(options.copySourceDirectory); + return { force, recursive, copySourceDirectory }; +} +function cpDirRecursive(sourceDir, destDir, currentDepth, force) { + return __awaiter(this, void 0, void 0, function* () { + // Ensure there is not a run away recursive copy + if (currentDepth >= 255) + return; + currentDepth++; + yield mkdirP(destDir); + const files = yield ioUtil.readdir(sourceDir); + for (const fileName of files) { + const srcFile = `${sourceDir}/${fileName}`; + const destFile = `${destDir}/${fileName}`; + const srcFileStat = yield ioUtil.lstat(srcFile); + if (srcFileStat.isDirectory()) { + // Recurse + yield cpDirRecursive(srcFile, destFile, currentDepth, force); + } + else { + yield copyFile(srcFile, destFile, force); + } + } + // Change the mode for the newly created directory + yield ioUtil.chmod(destDir, (yield ioUtil.stat(sourceDir)).mode); + }); +} +// Buffered file copy +function copyFile(srcFile, destFile, force) { + return __awaiter(this, void 0, void 0, function* () { + if ((yield ioUtil.lstat(srcFile)).isSymbolicLink()) { + // unlink/re-link it + try { + yield ioUtil.lstat(destFile); + yield ioUtil.unlink(destFile); + } + catch (e) { + // Try to override file permission + if (e.code === 'EPERM') { + yield ioUtil.chmod(destFile, '0666'); + yield ioUtil.unlink(destFile); + } + // other errors = it doesn't exist, no work to do + } + // Copy over symlink + const symlinkFull = yield ioUtil.readlink(srcFile); + yield ioUtil.symlink(symlinkFull, destFile, ioUtil.IS_WINDOWS ? 'junction' : null); + } + else if (!(yield ioUtil.exists(destFile)) || force) { + yield ioUtil.copyFile(srcFile, destFile); + } + }); +} +//# sourceMappingURL=io.js.map + +/***/ }), + +/***/ 9351: +/***/ ((module) => { + +"use strict"; + + +/****************************************************************************** + * Created 2008-08-19. + * + * Dijkstra path-finding functions. Adapted from the Dijkstar Python project. + * + * Copyright (C) 2008 + * Wyatt Baldwin + * All rights reserved + * + * Licensed under the MIT license. + * + * http://www.opensource.org/licenses/mit-license.php + * + * 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 dijkstra = { + single_source_shortest_paths: function(graph, s, d) { + // Predecessor map for each node that has been encountered. + // node ID => predecessor node ID + var predecessors = {}; + + // Costs of shortest paths from s to all nodes encountered. + // node ID => cost + var costs = {}; + costs[s] = 0; + + // Costs of shortest paths from s to all nodes encountered; differs from + // `costs` in that it provides easy access to the node that currently has + // the known shortest path from s. + // XXX: Do we actually need both `costs` and `open`? + var open = dijkstra.PriorityQueue.make(); + open.push(s, 0); + + var closest, + u, v, + cost_of_s_to_u, + adjacent_nodes, + cost_of_e, + cost_of_s_to_u_plus_cost_of_e, + cost_of_s_to_v, + first_visit; + while (!open.empty()) { + // In the nodes remaining in graph that have a known cost from s, + // find the node, u, that currently has the shortest path from s. + closest = open.pop(); + u = closest.value; + cost_of_s_to_u = closest.cost; + + // Get nodes adjacent to u... + adjacent_nodes = graph[u] || {}; + + // ...and explore the edges that connect u to those nodes, updating + // the cost of the shortest paths to any or all of those nodes as + // necessary. v is the node across the current edge from u. + for (v in adjacent_nodes) { + if (adjacent_nodes.hasOwnProperty(v)) { + // Get the cost of the edge running from u to v. + cost_of_e = adjacent_nodes[v]; + + // Cost of s to u plus the cost of u to v across e--this is *a* + // cost from s to v that may or may not be less than the current + // known cost to v. + cost_of_s_to_u_plus_cost_of_e = cost_of_s_to_u + cost_of_e; + + // If we haven't visited v yet OR if the current known cost from s to + // v is greater than the new cost we just found (cost of s to u plus + // cost of u to v across e), update v's cost in the cost list and + // update v's predecessor in the predecessor list (it's now u). + cost_of_s_to_v = costs[v]; + first_visit = (typeof costs[v] === 'undefined'); + if (first_visit || cost_of_s_to_v > cost_of_s_to_u_plus_cost_of_e) { + costs[v] = cost_of_s_to_u_plus_cost_of_e; + open.push(v, cost_of_s_to_u_plus_cost_of_e); + predecessors[v] = u; + } + } + } + } + + if (typeof d !== 'undefined' && typeof costs[d] === 'undefined') { + var msg = ['Could not find a path from ', s, ' to ', d, '.'].join(''); + throw new Error(msg); + } + + return predecessors; + }, + + extract_shortest_path_from_predecessor_list: function(predecessors, d) { + var nodes = []; + var u = d; + var predecessor; + while (u) { + nodes.push(u); + predecessor = predecessors[u]; + u = predecessors[u]; } - /** - * Needs to be called if keepAlive is set to true in request options. - */ - dispose() { - if (this._agent) { - this._agent.destroy(); + nodes.reverse(); + return nodes; + }, + + find_path: function(graph, s, d) { + var predecessors = dijkstra.single_source_shortest_paths(graph, s, d); + return dijkstra.extract_shortest_path_from_predecessor_list( + predecessors, d); + }, + + /** + * A very naive priority queue implementation. + */ + PriorityQueue: { + make: function (opts) { + var T = dijkstra.PriorityQueue, + t = {}, + key; + opts = opts || {}; + for (key in T) { + if (T.hasOwnProperty(key)) { + t[key] = T[key]; } - this._disposed = true; - } + } + t.queue = []; + t.sorter = opts.sorter || T.default_sorter; + return t; + }, + + default_sorter: function (a, b) { + return a.cost - b.cost; + }, + /** - * Raw request. - * @param info - * @param data + * Add a new item to the queue and ensure the highest priority element + * is at the front of the queue. */ - requestRaw(info, data) { - return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve, reject) => { - function callbackForResult(err, res) { - if (err) { - reject(err); - } - else if (!res) { - // If `err` is not passed, then `res` must be passed. - reject(new Error('Unknown error')); - } - else { - resolve(res); - } - } - this.requestRawWithCallback(info, data, callbackForResult); - }); - }); - } + push: function (value, cost) { + var item = {value: value, cost: cost}; + this.queue.push(item); + this.queue.sort(this.sorter); + }, + /** - * Raw request with callback. - * @param info - * @param data - * @param onResult + * Return the highest priority element in the queue. */ - requestRawWithCallback(info, data, onResult) { - if (typeof data === 'string') { - if (!info.options.headers) { - info.options.headers = {}; - } - info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8'); - } - let callbackCalled = false; - function handleResult(err, res) { - if (!callbackCalled) { - callbackCalled = true; - onResult(err, res); - } - } - const req = info.httpModule.request(info.options, (msg) => { - const res = new HttpClientResponse(msg); - handleResult(undefined, res); - }); - let socket; - req.on('socket', sock => { - socket = sock; - }); - // If we ever get disconnected, we want the socket to timeout eventually - req.setTimeout(this._socketTimeout || 3 * 60000, () => { - if (socket) { - socket.end(); - } - handleResult(new Error(`Request timeout: ${info.options.path}`)); - }); - req.on('error', function (err) { - // err has statusCode property - // res should have headers - handleResult(err); - }); - if (data && typeof data === 'string') { - req.write(data, 'utf8'); - } - if (data && typeof data !== 'string') { - data.on('close', function () { - req.end(); - }); - data.pipe(req); - } - else { - req.end(); - } + pop: function () { + return this.queue.shift(); + }, + + empty: function () { + return this.queue.length === 0; + } + } +}; + + +// node.js module exports +if (true) { + module.exports = dijkstra; +} + + +/***/ }), + +/***/ 6106: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +let interlaceUtils = __nccwpck_require__(2689); + +let 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"); + } + + let 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"); + } + + let 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]; + }, +]; + +let pixelBppCustomMapper = [ + // 0 - dummy entry + function () {}, + + // 1 - L + // 0: 0, 1: 0, 2: 0, 3: 0xff + function (pxData, pixelData, pxPos, maxBit) { + let 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) { + let 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) { + let leftOver = []; + let i = 0; + + function split() { + if (i === data.length) { + throw new Error("Ran out of data"); + } + let byte = data[i]; + i++; + let 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(); + } + let 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 + let imageWidth = image.width; + let imageHeight = image.height; + let imagePass = image.index; + for (let y = 0; y < imageHeight; y++) { + for (let x = 0; x < imageWidth; x++) { + let pxPos = getPxPos(x, y, imagePass); + pixelBppMapper[bpp](pxData, data, pxPos, rawPos); + rawPos += bpp; //eslint-disable-line no-param-reassign } - /** - * Gets an http agent. This function is useful when you need an http agent that handles - * routing through a proxy server - depending upon the url and proxy environment variables. - * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com - */ - getAgent(serverUrl) { - const parsedUrl = new URL(serverUrl); - return this._getAgent(parsedUrl); + } + return rawPos; +} + +function mapImageCustomBit(image, pxData, getPxPos, bpp, bits, maxBit) { + // eslint-disable-line max-params + let imageWidth = image.width; + let imageHeight = image.height; + let imagePass = image.index; + for (let y = 0; y < imageHeight; y++) { + for (let x = 0; x < imageWidth; x++) { + let pixelData = bits.get(bpp); + let pxPos = getPxPos(x, y, imagePass); + pixelBppCustomMapper[bpp](pxData, pixelData, pxPos, maxBit); } - _prepareRequest(method, requestUrl, headers) { - const info = {}; - info.parsedUrl = requestUrl; - const usingSsl = info.parsedUrl.protocol === 'https:'; - info.httpModule = usingSsl ? https : http; - const defaultPort = usingSsl ? 443 : 80; - info.options = {}; - info.options.host = info.parsedUrl.hostname; - info.options.port = info.parsedUrl.port - ? parseInt(info.parsedUrl.port) - : defaultPort; - info.options.path = - (info.parsedUrl.pathname || '') + (info.parsedUrl.search || ''); - info.options.method = method; - info.options.headers = this._mergeHeaders(headers); - if (this.userAgent != null) { - info.options.headers['user-agent'] = this.userAgent; - } - info.options.agent = this._getAgent(info.parsedUrl); - // gives handlers an opportunity to participate - if (this.handlers) { - for (const handler of this.handlers) { - handler.prepareRequest(info.options); - } - } - return info; + bits.resetAfterLine(); + } +} + +exports.dataToBitMap = function (data, bitmapInfo) { + let width = bitmapInfo.width; + let height = bitmapInfo.height; + let depth = bitmapInfo.depth; + let bpp = bitmapInfo.bpp; + let interlace = bitmapInfo.interlace; + let bits; + + if (depth !== 8) { + bits = bitRetriever(data, depth); + } + let pxData; + if (depth <= 8) { + pxData = Buffer.alloc(width * height * 4); + } else { + pxData = new Uint16Array(width * height * 4); + } + let maxBit = Math.pow(2, depth) - 1; + let rawPos = 0; + let images; + let getPxPos; + + if (interlace) { + images = interlaceUtils.getImagePasses(width, height); + getPxPos = interlaceUtils.getInterlaceIterator(width, height); + } else { + let nonInterlacedPxPos = 0; + getPxPos = function () { + let returner = nonInterlacedPxPos; + nonInterlacedPxPos += 4; + return returner; + }; + images = [{ width: width, height: height }]; + } + + for (let 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 + ); } - _mergeHeaders(headers) { - if (this.requestOptions && this.requestOptions.headers) { - return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); - } - return lowercaseKeys(headers || {}); + } + if (depth === 8) { + if (rawPos !== data.length) { + throw new Error("extra data found"); } - _getExistingOrDefaultHeader(additionalHeaders, header, _default) { - let clientHeader; - if (this.requestOptions && this.requestOptions.headers) { - clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; - } - return additionalHeaders[header] || clientHeader || _default; + } else { + bits.end(); + } + + return pxData; +}; + + +/***/ }), + +/***/ 9889: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +let constants = __nccwpck_require__(1929); + +module.exports = function (dataIn, width, height, options) { + let outHasAlpha = + [constants.COLORTYPE_COLOR_ALPHA, constants.COLORTYPE_ALPHA].indexOf( + options.colorType + ) !== -1; + if (options.colorType === options.inputColorType) { + let bigEndian = (function () { + let 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; } - _getAgent(parsedUrl) { - let agent; - const proxyUrl = pm.getProxyUrl(parsedUrl); - const useProxy = proxyUrl && proxyUrl.hostname; - if (this._keepAlive && useProxy) { - agent = this._proxyAgent; - } - if (this._keepAlive && !useProxy) { - agent = this._agent; - } - // if agent is already assigned use that agent. - if (agent) { - return agent; - } - const usingSsl = parsedUrl.protocol === 'https:'; - let maxSockets = 100; - if (this.requestOptions) { - maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; - } - // This is `useProxy` again, but we need to check `proxyURl` directly for TypeScripts's flow analysis. - if (proxyUrl && proxyUrl.hostname) { - const agentOptions = { - maxSockets, - keepAlive: this._keepAlive, - proxy: Object.assign(Object.assign({}, ((proxyUrl.username || proxyUrl.password) && { - proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` - })), { host: proxyUrl.hostname, port: proxyUrl.port }) - }; - let tunnelAgent; - const overHttps = proxyUrl.protocol === 'https:'; - if (usingSsl) { - tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; + } + + // map to a UInt16 array if data is 16bit, fix endianness below + let data = options.bitDepth !== 16 ? dataIn : new Uint16Array(dataIn.buffer); + + let maxValue = 255; + let inBpp = constants.COLORTYPE_TO_BPP_MAP[options.inputColorType]; + if (inBpp === 4 && !options.inputHasAlpha) { + inBpp = 3; + } + let outBpp = constants.COLORTYPE_TO_BPP_MAP[options.colorType]; + if (options.bitDepth === 16) { + maxValue = 65535; + outBpp *= 2; + } + let outData = Buffer.alloc(width * height * outBpp); + + let inIndex = 0; + let outIndex = 0; + + let 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() { + let red; + let green; + let blue; + let 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 (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + let 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 { - tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; + } 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); } - agent = tunnelAgent(agentOptions); - this._proxyAgent = agent; - } - // if reusing agent across request and tunneling agent isn't assigned create a new agent - if (this._keepAlive && !agent) { - const options = { keepAlive: this._keepAlive, maxSockets }; - agent = usingSsl ? new https.Agent(options) : new http.Agent(options); - this._agent = agent; - } - // if not using private agent and tunnel agent isn't setup then use global agent - if (!agent) { - agent = usingSsl ? https.globalAgent : http.globalAgent; - } - if (usingSsl && this._ignoreSslError) { - // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process - // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options - // we have to cast it to any and change it directly - agent.options = Object.assign(agent.options || {}, { - rejectUnauthorized: false - }); + } + break; + case constants.COLORTYPE_ALPHA: + case constants.COLORTYPE_GRAYSCALE: { + // Convert to grayscale and alpha + let 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; } - return agent; + default: + throw new Error("unrecognised color Type " + options.colorType); + } + + inIndex += inBpp; + outIndex += outBpp; } - _performExponentialBackoff(retryNumber) { - return __awaiter(this, void 0, void 0, function* () { - retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); - const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); - return new Promise(resolve => setTimeout(() => resolve(), ms)); - }); + } + + return outData; +}; + + +/***/ }), + +/***/ 4369: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +let util = __nccwpck_require__(9023); +let Stream = __nccwpck_require__(2203); + +let 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 && 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; + } + + let dataBuffer; + if (Buffer.isBuffer(data)) { + dataBuffer = data; + } else { + dataBuffer = Buffer.from(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 + let 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 + + let pos = 0; + let count = 0; + let data = Buffer.alloc(read.length); + + // create buffer for all data + while (pos < read.length) { + let buf = this._buffers[count++]; + let 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); } - _processResponse(res, options) { - return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { - const statusCode = res.message.statusCode || 0; - const response = { - statusCode, - result: null, - headers: {} - }; - // not found leads to null obj returned - if (statusCode === HttpCodes.NotFound) { - resolve(response); - } - // get the result from the body - function dateTimeDeserializer(key, value) { - if (typeof value === 'string') { - const a = new Date(value); - if (!isNaN(a.valueOf())) { - return a; - } - } - return value; - } - let obj; - let contents; - try { - contents = yield res.readBody(); - if (contents && contents.length > 0) { - if (options && options.deserializeDates) { - obj = JSON.parse(contents, dateTimeDeserializer); - } - else { - obj = JSON.parse(contents); - } - response.result = obj; - } - response.headers = res.message.headers; - } - catch (err) { - // Invalid resource (contents not json); leaving result obj null - } - // note that 3xx redirects are handled by the http layer. - if (statusCode > 299) { - let msg; - // if exception/error in body, attempt to get better error - if (obj && obj.message) { - msg = obj.message; - } - else if (contents && contents.length > 0) { - // it may be the case that the exception is in the body message as string - msg = contents; - } - else { - msg = `Failed request: (${statusCode})`; - } - const err = new HttpClientError(msg, statusCode); - err.result = response.result; - reject(err); - } - else { - resolve(response); - } - })); - }); + } + + // 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) { + let 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; + } } -} -exports.HttpClient = HttpClient; -const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); -//# sourceMappingURL=index.js.map + + if (this._buffers && !this.writable) { + this._end(); + } + } catch (ex) { + this.emit("error", ex); + } +}; + + +/***/ }), + +/***/ 1929: +/***/ ((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, +}; + /***/ }), -/***/ 431: -/***/ (function(__unusedmodule, exports, __webpack_require__) { +/***/ 2918: +/***/ ((module) => { "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (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; + +let crcTable = []; + +(function () { + for (let i = 0; i < 256; i++) { + let currentCrc = i; + for (let j = 0; j < 8; j++) { + if (currentCrc & 1) { + currentCrc = 0xedb88320 ^ (currentCrc >>> 1); + } else { + currentCrc = currentCrc >>> 1; + } + } + crcTable[i] = currentCrc; + } +})(); + +let CrcCalculator = (module.exports = function () { + this._crc = -1; }); -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.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; + +CrcCalculator.prototype.write = function (data) { + for (let i = 0; i < data.length; i++) { + this._crc = crcTable[(this._crc ^ data[i]) & 0xff] ^ (this._crc >>> 8); + } + return true; }; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.issue = exports.issueCommand = void 0; -const os = __importStar(__webpack_require__(87)); -const utils_1 = __webpack_require__(82); -/** - * Commands - * - * Command Format: - * ::name key=value,key=value::message - * - * Examples: - * ::warning::This is the message - * ::set-env name=MY_VAR::some value - */ -function issueCommand(command, properties, message) { - const cmd = new Command(command, properties, message); - process.stdout.write(cmd.toString() + os.EOL); + +CrcCalculator.prototype.crc32 = function () { + return this._crc ^ -1; +}; + +CrcCalculator.crc32 = function (buf) { + let crc = -1; + for (let i = 0; i < buf.length; i++) { + crc = crcTable[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8); + } + return crc ^ -1; +}; + + +/***/ }), + +/***/ 8696: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +let paethPredictor = __nccwpck_require__(9635); + +function filterNone(pxData, pxPos, byteWidth, rawData, rawPos) { + for (let x = 0; x < byteWidth; x++) { + rawData[rawPos + x] = pxData[pxPos + x]; + } } -exports.issueCommand = issueCommand; -function issue(name, message = '') { - issueCommand(name, {}, message); + +function filterSumNone(pxData, pxPos, byteWidth) { + let sum = 0; + let length = pxPos + byteWidth; + + for (let i = pxPos; i < length; i++) { + sum += Math.abs(pxData[i]); + } + return sum; } -exports.issue = issue; -const CMD_STRING = '::'; -class Command { - constructor(command, properties, message) { - if (!command) { - command = 'missing.command'; - } - this.command = command; - this.properties = properties; - this.message = message; - } - toString() { - let cmdStr = CMD_STRING + this.command; - if (this.properties && Object.keys(this.properties).length > 0) { - cmdStr += ' '; - let first = true; - for (const key in this.properties) { - if (this.properties.hasOwnProperty(key)) { - const val = this.properties[key]; - if (val) { - if (first) { - first = false; - } - else { - cmdStr += ','; - } - cmdStr += `${key}=${escapeProperty(val)}`; - } - } - } - } - cmdStr += `${CMD_STRING}${escapeData(this.message)}`; - return cmdStr; - } + +function filterSub(pxData, pxPos, byteWidth, rawData, rawPos, bpp) { + for (let x = 0; x < byteWidth; x++) { + let left = x >= bpp ? pxData[pxPos + x - bpp] : 0; + let val = pxData[pxPos + x] - left; + + rawData[rawPos + x] = val; + } } -function escapeData(s) { - return utils_1.toCommandValue(s) - .replace(/%/g, '%25') - .replace(/\r/g, '%0D') - .replace(/\n/g, '%0A'); + +function filterSumSub(pxData, pxPos, byteWidth, bpp) { + let sum = 0; + for (let x = 0; x < byteWidth; x++) { + let left = x >= bpp ? pxData[pxPos + x - bpp] : 0; + let val = pxData[pxPos + x] - left; + + sum += Math.abs(val); + } + + return sum; } -function escapeProperty(s) { - return utils_1.toCommandValue(s) - .replace(/%/g, '%25') - .replace(/\r/g, '%0D') - .replace(/\n/g, '%0A') - .replace(/:/g, '%3A') - .replace(/,/g, '%2C'); + +function filterUp(pxData, pxPos, byteWidth, rawData, rawPos) { + for (let x = 0; x < byteWidth; x++) { + let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0; + let val = pxData[pxPos + x] - up; + + rawData[rawPos + x] = val; + } } -//# sourceMappingURL=command.js.map -/***/ }), +function filterSumUp(pxData, pxPos, byteWidth) { + let sum = 0; + let length = pxPos + byteWidth; + for (let x = pxPos; x < length; x++) { + let up = pxPos > 0 ? pxData[x - byteWidth] : 0; + let val = pxData[x] - up; -/***/ 432: -/***/ (function(module, __unusedexports, __webpack_require__) { + sum += Math.abs(val); + } -"use strict"; + return sum; +} +function filterAvg(pxData, pxPos, byteWidth, rawData, rawPos, bpp) { + for (let x = 0; x < byteWidth; x++) { + let left = x >= bpp ? pxData[pxPos + x - bpp] : 0; + let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0; + let val = pxData[pxPos + x] - ((left + up) >> 1); -var util = __webpack_require__(669); -var ChunkStream = __webpack_require__(210); -var Filter = __webpack_require__(447); + rawData[rawPos + x] = val; + } +} +function filterSumAvg(pxData, pxPos, byteWidth, bpp) { + let sum = 0; + for (let x = 0; x < byteWidth; x++) { + let left = x >= bpp ? pxData[pxPos + x - bpp] : 0; + let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0; + let val = pxData[pxPos + x] - ((left + up) >> 1); -var FilterAsync = module.exports = function(bitmapInfo) { - ChunkStream.call(this); + sum += Math.abs(val); + } - 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)); - } - }); + return sum; +} - this._filter.start(); -}; -util.inherits(FilterAsync, ChunkStream); +function filterPaeth(pxData, pxPos, byteWidth, rawData, rawPos, bpp) { + for (let x = 0; x < byteWidth; x++) { + let left = x >= bpp ? pxData[pxPos + x - bpp] : 0; + let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0; + let upleft = + pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0; + let val = pxData[pxPos + x] - paethPredictor(left, up, upleft); + + rawData[rawPos + x] = val; + } +} +function filterSumPaeth(pxData, pxPos, byteWidth, bpp) { + let sum = 0; + for (let x = 0; x < byteWidth; x++) { + let left = x >= bpp ? pxData[pxPos + x - bpp] : 0; + let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0; + let upleft = + pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0; + let val = pxData[pxPos + x] - paethPredictor(left, up, upleft); -/***/ }), + sum += Math.abs(val); + } -/***/ 436: -/***/ (function(__unusedmodule, exports, __webpack_require__) { + return sum; +} -var fs = __webpack_require__(747) -var PNG = __webpack_require__(275).PNG -var Utils = __webpack_require__(621) +let filters = { + 0: filterNone, + 1: filterSub, + 2: filterUp, + 3: filterAvg, + 4: filterPaeth, +}; -exports.render = function render (qrData, options) { - var opts = Utils.getOptions(options) - var pngOpts = opts.rendererOpts - var size = Utils.getImageWidth(qrData.modules.size, opts) +let filterSums = { + 0: filterSumNone, + 1: filterSumSub, + 2: filterSumUp, + 3: filterSumAvg, + 4: filterSumPaeth, +}; - pngOpts.width = size - pngOpts.height = size +module.exports = function (pxData, width, height, options, bpp) { + let 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"); + } - var pngImage = new PNG(pngOpts) - Utils.qrToImageData(pngImage.data, qrData, opts) + if (options.bitDepth === 16) { + bpp *= 2; + } + let byteWidth = width * bpp; + let rawPos = 0; + let pxPos = 0; + let rawData = Buffer.alloc((byteWidth + 1) * height); - return pngImage -} + let sel = filterTypes[0]; -exports.renderToDataURL = function renderToDataURL (qrData, options, cb) { - if (typeof cb === 'undefined') { - cb = options - options = undefined + for (let y = 0; y < height; y++) { + if (filterTypes.length > 1) { + // find best filter for this line (with lowest sum of values) + let min = Infinity; + + for (let i = 0; i < filterTypes.length; i++) { + let 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; +}; - exports.renderToBuffer(qrData, options, function (err, output) { - if (err) cb(err) - var url = 'data:image/png;base64,' - url += output.toString('base64') - cb(null, url) - }) -} -exports.renderToBuffer = function renderToBuffer (qrData, options, cb) { - if (typeof cb === 'undefined') { - cb = options - options = undefined - } +/***/ }), + +/***/ 8539: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +let util = __nccwpck_require__(9023); +let ChunkStream = __nccwpck_require__(4369); +let Filter = __nccwpck_require__(3054); + +let FilterAsync = (module.exports = function (bitmapInfo) { + ChunkStream.call(this); - var png = exports.render(qrData, options) - var buffer = [] + let buffers = []; + let 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)); + }, + }); - png.on('error', cb) + this._filter.start(); +}); +util.inherits(FilterAsync, ChunkStream); - png.on('data', function (data) { - buffer.push(data) - }) - png.on('end', function () { - cb(null, Buffer.concat(buffer)) - }) +/***/ }), - png.pack() -} +/***/ 8056: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -exports.renderToFile = function renderToFile (path, qrData, options, cb) { - if (typeof cb === 'undefined') { - cb = options - options = undefined - } +"use strict"; - var stream = fs.createWriteStream(path) - stream.on('error', cb) - stream.on('close', cb) - exports.renderToFileStream(stream, qrData, options) -} +let SyncReader = __nccwpck_require__(8613); +let Filter = __nccwpck_require__(3054); -exports.renderToFileStream = function renderToFileStream (stream, qrData, options) { - var png = exports.render(qrData, options) - png.pack().pipe(stream) -} +exports.process = function (inBuffer, bitmapInfo) { + let outBuffers = []; + let reader = new SyncReader(inBuffer); + let 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); +}; /***/ }), -/***/ 447: -/***/ (function(module, __unusedexports, __webpack_require__) { +/***/ 3054: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var interlaceUtils = __webpack_require__(724); -var paethPredictor = __webpack_require__(594); +let interlaceUtils = __nccwpck_require__(2689); +let paethPredictor = __nccwpck_require__(9635); function getByteWidth(width, bpp, depth) { - var byteWidth = width * bpp; + let 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; +let Filter = (module.exports = function (bitmapInfo, dependencies) { + let width = bitmapInfo.width; + let height = bitmapInfo.height; + let interlace = bitmapInfo.interlace; + let bpp = bitmapInfo.bpp; + let depth = bitmapInfo.depth; this.read = dependencies.read; this.write = dependencies.write; @@ -4453,20 +4284,19 @@ var Filter = module.exports = function(bitmapInfo, dependencies) { this._imageIndex = 0; this._images = []; if (interlace) { - var passes = interlaceUtils.getImagePasses(width, height); - for (var i = 0; i < passes.length; i++) { + let passes = interlaceUtils.getImagePasses(width, height); + for (let i = 0; i < passes.length; i++) { this._images.push({ byteWidth: getByteWidth(passes[i].width, bpp, depth), height: passes[i].height, - lineIndex: 0 + lineIndex: 0, }); } - } - else { + } else { this._images.push({ byteWidth: getByteWidth(width, bpp, depth), height: height, - lineIndex: 0 + lineIndex: 0, }); } @@ -4476,2374 +4306,3021 @@ var Filter = module.exports = function(bitmapInfo, dependencies) { // 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) { + } else if (depth === 16) { this._xComparison = bpp * 2; - } - else { + } else { this._xComparison = 1; } +}); + +Filter.prototype.start = function () { + this.read( + this._images[this._imageIndex].byteWidth + 1, + this._reverseFilterLine.bind(this) + ); }; -Filter.prototype.start = function() { - this.read(this._images[this._imageIndex].byteWidth + 1, this._reverseFilterLine.bind(this)); +Filter.prototype._unFilterType1 = function ( + rawData, + unfilteredLine, + byteWidth +) { + let xComparison = this._xComparison; + let xBiggerThan = xComparison - 1; + + for (let x = 0; x < byteWidth; x++) { + let rawByte = rawData[1 + x]; + let f1Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0; + unfilteredLine[x] = rawByte + f1Left; + } }; -Filter.prototype._unFilterType1 = function(rawData, unfilteredLine, byteWidth) { +Filter.prototype._unFilterType2 = function ( + rawData, + unfilteredLine, + byteWidth +) { + let lastLine = this._lastLine; - var xComparison = this._xComparison; - var xBiggerThan = xComparison - 1; + for (let x = 0; x < byteWidth; x++) { + let rawByte = rawData[1 + x]; + let f2Up = lastLine ? lastLine[x] : 0; + unfilteredLine[x] = rawByte + f2Up; + } +}; - 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._unFilterType3 = function ( + rawData, + unfilteredLine, + byteWidth +) { + let xComparison = this._xComparison; + let xBiggerThan = xComparison - 1; + let lastLine = this._lastLine; + + for (let x = 0; x < byteWidth; x++) { + let rawByte = rawData[1 + x]; + let f3Up = lastLine ? lastLine[x] : 0; + let f3Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0; + let f3Add = Math.floor((f3Left + f3Up) / 2); + unfilteredLine[x] = rawByte + f3Add; + } +}; + +Filter.prototype._unFilterType4 = function ( + rawData, + unfilteredLine, + byteWidth +) { + let xComparison = this._xComparison; + let xBiggerThan = xComparison - 1; + let lastLine = this._lastLine; + + for (let x = 0; x < byteWidth; x++) { + let rawByte = rawData[1 + x]; + let f4Up = lastLine ? lastLine[x] : 0; + let f4Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0; + let f4UpLeft = x > xBiggerThan && lastLine ? lastLine[x - xComparison] : 0; + let f4Add = paethPredictor(f4Left, f4Up, f4UpLeft); + unfilteredLine[x] = rawByte + f4Add; } }; -Filter.prototype._unFilterType2 = function(rawData, unfilteredLine, byteWidth) { +Filter.prototype._reverseFilterLine = function (rawData) { + let filter = rawData[0]; + let unfilteredLine; + let currentImage = this._images[this._imageIndex]; + let byteWidth = currentImage.byteWidth; - var lastLine = this._lastLine; + if (filter === 0) { + unfilteredLine = rawData.slice(1, byteWidth + 1); + } else { + unfilteredLine = Buffer.alloc(byteWidth); - for (var x = 0; x < byteWidth; x++) { - var rawByte = rawData[1 + x]; - var f2Up = lastLine ? lastLine[x] : 0; - unfilteredLine[x] = rawByte + f2Up; + 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(); + } +}; + + +/***/ }), + +/***/ 998: +/***/ ((module) => { + +"use strict"; + + +function dePalette(indata, outdata, width, height, palette) { + let pxPos = 0; + // use values from palette + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + let color = palette[indata[pxPos]]; + + if (!color) { + throw new Error("index " + indata[pxPos] + " not in palette"); + } + + for (let i = 0; i < 4; i++) { + outdata[pxPos + i] = color[i]; + } + pxPos += 4; + } + } +} + +function replaceTransparentColor(indata, outdata, width, height, transColor) { + let pxPos = 0; + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + let 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 (let i = 0; i < 4; i++) { + outdata[pxPos + i] = 0; + } + } + pxPos += 4; + } + } +} + +function scaleDepth(indata, outdata, width, height, depth) { + let maxOutSample = 255; + let maxInSample = Math.pow(2, depth) - 1; + let pxPos = 0; + + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + for (let i = 0; i < 4; i++) { + outdata[pxPos + i] = Math.floor( + (indata[pxPos + i] * maxOutSample) / maxInSample + 0.5 + ); + } + pxPos += 4; + } + } +} + +module.exports = function (indata, imageData) { + let depth = imageData.depth; + let width = imageData.width; + let height = imageData.height; + let colorType = imageData.colorType; + let transColor = imageData.transColor; + let palette = imageData.palette; + + let 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 = Buffer.alloc(width * height * 4); + } + scaleDepth(indata, outdata, width, height, depth); + } + } + return outdata; +}; + + +/***/ }), + +/***/ 2689: +/***/ ((__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 + +let 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) { + let images = []; + let xLeftOver = width % 8; + let yLeftOver = height % 8; + let xRepeats = (width - xLeftOver) / 8; + let yRepeats = (height - yLeftOver) / 8; + for (let i = 0; i < imagePasses.length; i++) { + let pass = imagePasses[i]; + let passWidth = xRepeats * pass.x.length; + let passHeight = yRepeats * pass.y.length; + for (let j = 0; j < pass.x.length; j++) { + if (pass.x[j] < xLeftOver) { + passWidth++; + } else { + break; + } + } + for (let 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) { + let outerXLeftOver = x % imagePasses[pass].x.length; + let outerX = + ((x - outerXLeftOver) / imagePasses[pass].x.length) * 8 + + imagePasses[pass].x[outerXLeftOver]; + let outerYLeftOver = y % imagePasses[pass].y.length; + let outerY = + ((y - outerYLeftOver) / imagePasses[pass].y.length) * 8 + + imagePasses[pass].y[outerYLeftOver]; + return outerX * 4 + outerY * width * 4; + }; +}; + + +/***/ }), + +/***/ 281: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +let util = __nccwpck_require__(9023); +let Stream = __nccwpck_require__(2203); +let constants = __nccwpck_require__(1929); +let Packer = __nccwpck_require__(1736); + +let PackerAsync = (module.exports = function (opt) { + Stream.call(this); + + let 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", Buffer.from(constants.PNG_SIGNATURE)); + this.emit("data", this._packer.packIHDR(width, height)); + + if (gamma) { + this.emit("data", this._packer.packGAMA(gamma)); } + + let 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); }; -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; - } -}; +/***/ 8562: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -Filter.prototype._unFilterType4 = function(rawData, unfilteredLine, byteWidth) { +"use strict"; - 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; +let hasSyncZlib = true; +let zlib = __nccwpck_require__(3106); +if (!zlib.deflateSync) { + hasSyncZlib = false; +} +let constants = __nccwpck_require__(1929); +let Packer = __nccwpck_require__(1736); + +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" + ); } -}; -Filter.prototype._reverseFilterLine = function(rawData) { + let options = opt || {}; - var filter = rawData[0]; - var unfilteredLine; - var currentImage = this._images[this._imageIndex]; - var byteWidth = currentImage.byteWidth; + let packer = new Packer(options); - if (filter === 0) { - unfilteredLine = rawData.slice(1, byteWidth + 1); - } - else { + let chunks = []; - unfilteredLine = new Buffer(byteWidth); + // Signature + chunks.push(Buffer.from(constants.PNG_SIGNATURE)); - 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); - } + // Header + chunks.push(packer.packIHDR(metaData.width, metaData.height)); + + if (metaData.gamma) { + chunks.push(packer.packGAMA(metaData.gamma)); } - this.write(unfilteredLine); + let filteredData = packer.filterData( + metaData.data, + metaData.width, + metaData.height + ); - currentImage.lineIndex++; - if (currentImage.lineIndex >= currentImage.height) { - this._lastLine = null; - this._imageIndex++; - currentImage = this._images[this._imageIndex]; - } - else { - this._lastLine = unfilteredLine; - } + // compress it + let compressedData = zlib.deflateSync( + filteredData, + packer.getDeflateOptions() + ); + filteredData = null; - 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(); + 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); }; /***/ }), -/***/ 467: -/***/ (function(module) { +/***/ 1736: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -/****************************************************************************** - * Created 2008-08-19. - * - * Dijkstra path-finding functions. Adapted from the Dijkstar Python project. - * - * Copyright (C) 2008 - * Wyatt Baldwin - * All rights reserved - * - * Licensed under the MIT license. - * - * http://www.opensource.org/licenses/mit-license.php - * - * 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 dijkstra = { - single_source_shortest_paths: function(graph, s, d) { - // Predecessor map for each node that has been encountered. - // node ID => predecessor node ID - var predecessors = {}; - - // Costs of shortest paths from s to all nodes encountered. - // node ID => cost - var costs = {}; - costs[s] = 0; - - // Costs of shortest paths from s to all nodes encountered; differs from - // `costs` in that it provides easy access to the node that currently has - // the known shortest path from s. - // XXX: Do we actually need both `costs` and `open`? - var open = dijkstra.PriorityQueue.make(); - open.push(s, 0); - - var closest, - u, v, - cost_of_s_to_u, - adjacent_nodes, - cost_of_e, - cost_of_s_to_u_plus_cost_of_e, - cost_of_s_to_v, - first_visit; - while (!open.empty()) { - // In the nodes remaining in graph that have a known cost from s, - // find the node, u, that currently has the shortest path from s. - closest = open.pop(); - u = closest.value; - cost_of_s_to_u = closest.cost; +let constants = __nccwpck_require__(1929); +let CrcStream = __nccwpck_require__(2918); +let bitPacker = __nccwpck_require__(9889); +let filter = __nccwpck_require__(8696); +let zlib = __nccwpck_require__(3106); - // Get nodes adjacent to u... - adjacent_nodes = graph[u] || {}; +let Packer = (module.exports = function (options) { + this._options = options; - // ...and explore the edges that connect u to those nodes, updating - // the cost of the shortest paths to any or all of those nodes as - // necessary. v is the node across the current edge from u. - for (v in adjacent_nodes) { - if (adjacent_nodes.hasOwnProperty(v)) { - // Get the cost of the edge running from u to v. - cost_of_e = adjacent_nodes[v]; + 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" + ); + } +}); - // Cost of s to u plus the cost of u to v across e--this is *a* - // cost from s to v that may or may not be less than the current - // known cost to v. - cost_of_s_to_u_plus_cost_of_e = cost_of_s_to_u + cost_of_e; +Packer.prototype.getDeflateOptions = function () { + return { + chunkSize: this._options.deflateChunkSize, + level: this._options.deflateLevel, + strategy: this._options.deflateStrategy, + }; +}; - // If we haven't visited v yet OR if the current known cost from s to - // v is greater than the new cost we just found (cost of s to u plus - // cost of u to v across e), update v's cost in the cost list and - // update v's predecessor in the predecessor list (it's now u). - cost_of_s_to_v = costs[v]; - first_visit = (typeof costs[v] === 'undefined'); - if (first_visit || cost_of_s_to_v > cost_of_s_to_u_plus_cost_of_e) { - costs[v] = cost_of_s_to_u_plus_cost_of_e; - open.push(v, cost_of_s_to_u_plus_cost_of_e); - predecessors[v] = u; - } - } - } - } +Packer.prototype.createDeflate = function () { + return this._options.deflateFactory(this.getDeflateOptions()); +}; - if (typeof d !== 'undefined' && typeof costs[d] === 'undefined') { - var msg = ['Could not find a path from ', s, ' to ', d, '.'].join(''); - throw new Error(msg); - } +Packer.prototype.filterData = function (data, width, height) { + // convert to correct format for filtering (e.g. right bpp and bit depth) + let packedData = bitPacker(data, width, height, this._options); - return predecessors; - }, + // filter pixel data + let bpp = constants.COLORTYPE_TO_BPP_MAP[this._options.colorType]; + let filteredData = filter(packedData, width, height, this._options, bpp); + return filteredData; +}; - extract_shortest_path_from_predecessor_list: function(predecessors, d) { - var nodes = []; - var u = d; - var predecessor; - while (u) { - nodes.push(u); - predecessor = predecessors[u]; - u = predecessors[u]; - } - nodes.reverse(); - return nodes; - }, +Packer.prototype._packChunk = function (type, data) { + let len = data ? data.length : 0; + let buf = Buffer.alloc(len + 12); - find_path: function(graph, s, d) { - var predecessors = dijkstra.single_source_shortest_paths(graph, s, d); - return dijkstra.extract_shortest_path_from_predecessor_list( - predecessors, d); - }, + buf.writeUInt32BE(len, 0); + buf.writeUInt32BE(type, 4); - /** - * A very naive priority queue implementation. - */ - PriorityQueue: { - make: function (opts) { - var T = dijkstra.PriorityQueue, - t = {}, - key; - opts = opts || {}; - for (key in T) { - if (T.hasOwnProperty(key)) { - t[key] = T[key]; - } - } - t.queue = []; - t.sorter = opts.sorter || T.default_sorter; - return t; - }, + if (data) { + data.copy(buf, 8); + } - default_sorter: function (a, b) { - return a.cost - b.cost; - }, + buf.writeInt32BE( + CrcStream.crc32(buf.slice(4, buf.length - 4)), + buf.length - 4 + ); + return buf; +}; - /** - * Add a new item to the queue and ensure the highest priority element - * is at the front of the queue. - */ - push: function (value, cost) { - var item = {value: value, cost: cost}; - this.queue.push(item); - this.queue.sort(this.sorter); - }, +Packer.prototype.packGAMA = function (gamma) { + let buf = Buffer.alloc(4); + buf.writeUInt32BE(Math.floor(gamma * constants.GAMMA_DIVISION), 0); + return this._packChunk(constants.TYPE_gAMA, buf); +}; - /** - * Return the highest priority element in the queue. - */ - pop: function () { - return this.queue.shift(); - }, +Packer.prototype.packIHDR = function (width, height) { + let buf = Buffer.alloc(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 - empty: function () { - return this.queue.length === 0; - } - } + return this._packChunk(constants.TYPE_IHDR, buf); }; +Packer.prototype.packIDAT = function (data) { + return this._packChunk(constants.TYPE_IDAT, data); +}; -// node.js module exports -if (true) { - module.exports = dijkstra; -} +Packer.prototype.packIEND = function () { + return this._packChunk(constants.TYPE_IEND, null); +}; /***/ }), -/***/ 470: -/***/ (function(__unusedmodule, exports, __webpack_require__) { +/***/ 9635: +/***/ ((module) => { "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (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.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -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 = __webpack_require__(431); -const file_command_1 = __webpack_require__(102); -const utils_1 = __webpack_require__(82); -const os = __importStar(__webpack_require__(87)); -const path = __importStar(__webpack_require__(622)); -const oidc_utils_1 = __webpack_require__(742); -/** - * The code to exit an action - */ -var ExitCode; -(function (ExitCode) { - /** - * A code indicating that the action was successful - */ - ExitCode[ExitCode["Success"] = 0] = "Success"; - /** - * A code indicating that the action was a failure - */ - ExitCode[ExitCode["Failure"] = 1] = "Failure"; -})(ExitCode = exports.ExitCode || (exports.ExitCode = {})); -//----------------------------------------------------------------------- -// Variables -//----------------------------------------------------------------------- -/** - * Sets env variable for this action and future actions in the job - * @param name the name of the variable to set - * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function exportVariable(name, val) { - const convertedVal = utils_1.toCommandValue(val); - process.env[name] = convertedVal; - const filePath = process.env['GITHUB_ENV'] || ''; - if (filePath) { - return file_command_1.issueFileCommand('ENV', file_command_1.prepareKeyValueMessage(name, val)); - } - command_1.issueCommand('set-env', { name }, convertedVal); -} -exports.exportVariable = exportVariable; -/** - * Registers a secret which will get masked from logs - * @param secret value of the secret - */ -function setSecret(secret) { - command_1.issueCommand('add-mask', {}, secret); -} -exports.setSecret = setSecret; -/** - * Prepends inputPath to the PATH (for this action and future actions) - * @param inputPath - */ -function addPath(inputPath) { - const filePath = process.env['GITHUB_PATH'] || ''; - if (filePath) { - file_command_1.issueFileCommand('PATH', inputPath); - } - else { - command_1.issueCommand('add-path', {}, inputPath); - } - process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; -} -exports.addPath = addPath; -/** - * Gets the value of an input. - * Unless trimWhitespace is set to false in InputOptions, the value is also trimmed. - * Returns an empty string if the value is not defined. - * - * @param name name of the input to get - * @param options optional. See InputOptions. - * @returns string - */ -function getInput(name, options) { - const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || ''; - if (options && options.required && !val) { - throw new Error(`Input required and not supplied: ${name}`); - } - if (options && options.trimWhitespace === false) { - return val; - } - return val.trim(); -} -exports.getInput = getInput; -/** - * Gets the values of an multiline input. Each value is also trimmed. - * - * @param name name of the input to get - * @param options optional. See InputOptions. - * @returns string[] - * - */ -function getMultilineInput(name, options) { - const inputs = getInput(name, options) - .split('\n') - .filter(x => x !== ''); - if (options && options.trimWhitespace === false) { - return inputs; - } - return inputs.map(input => input.trim()); -} -exports.getMultilineInput = getMultilineInput; -/** - * Gets the input value of the boolean type in the YAML 1.2 "core schema" specification. - * Support boolean input list: `true | True | TRUE | false | False | FALSE` . - * The return value is also in boolean type. - * ref: https://yaml.org/spec/1.2/spec.html#id2804923 - * - * @param name name of the input to get - * @param options optional. See InputOptions. - * @returns boolean - */ -function getBooleanInput(name, options) { - const trueValue = ['true', 'True', 'TRUE']; - const falseValue = ['false', 'False', 'FALSE']; - const val = getInput(name, options); - if (trueValue.includes(val)) - return true; - if (falseValue.includes(val)) - return false; - throw new TypeError(`Input does not meet YAML 1.2 "Core Schema" specification: ${name}\n` + - `Support boolean input list: \`true | True | TRUE | false | False | FALSE\``); -} -exports.getBooleanInput = getBooleanInput; -/** - * Sets the value of an output. - * - * @param name name of the output to set - * @param value value to store. Non-string values will be converted to a string via JSON.stringify - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function setOutput(name, value) { - const filePath = process.env['GITHUB_OUTPUT'] || ''; - if (filePath) { - return file_command_1.issueFileCommand('OUTPUT', file_command_1.prepareKeyValueMessage(name, value)); - } - process.stdout.write(os.EOL); - command_1.issueCommand('set-output', { name }, utils_1.toCommandValue(value)); -} -exports.setOutput = setOutput; -/** - * Enables or disables the echoing of commands into stdout for the rest of the step. - * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set. - * - */ -function setCommandEcho(enabled) { - command_1.issue('echo', enabled ? 'on' : 'off'); -} -exports.setCommandEcho = setCommandEcho; -//----------------------------------------------------------------------- -// Results -//----------------------------------------------------------------------- -/** - * Sets the action status to failed. - * When the action exits it will be with an exit code of 1 - * @param message add error issue message - */ -function setFailed(message) { - process.exitCode = ExitCode.Failure; - error(message); -} -exports.setFailed = setFailed; -//----------------------------------------------------------------------- -// Logging Commands -//----------------------------------------------------------------------- -/** - * Gets whether Actions Step Debug is on or not - */ -function isDebug() { - return process.env['RUNNER_DEBUG'] === '1'; -} -exports.isDebug = isDebug; -/** - * Writes debug message to user log - * @param message debug message - */ -function debug(message) { - command_1.issueCommand('debug', {}, message); -} -exports.debug = debug; -/** - * Adds an error issue - * @param message error issue message. Errors will be converted to string via toString() - * @param properties optional properties to add to the annotation. - */ -function error(message, properties = {}) { - command_1.issueCommand('error', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); -} -exports.error = error; -/** - * Adds a warning issue - * @param message warning issue message. Errors will be converted to string via toString() - * @param properties optional properties to add to the annotation. - */ -function warning(message, properties = {}) { - command_1.issueCommand('warning', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); -} -exports.warning = warning; -/** - * Adds a notice issue - * @param message notice issue message. Errors will be converted to string via toString() - * @param properties optional properties to add to the annotation. - */ -function notice(message, properties = {}) { - command_1.issueCommand('notice', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); -} -exports.notice = notice; -/** - * Writes info to log with console.log. - * @param message info message - */ -function info(message) { - process.stdout.write(message + os.EOL); -} -exports.info = info; -/** - * Begin an output group. - * - * Output until the next `groupEnd` will be foldable in this group - * - * @param name The name of the output group - */ -function startGroup(name) { - command_1.issue('group', name); -} -exports.startGroup = startGroup; -/** - * End an output group. - */ -function endGroup() { - command_1.issue('endgroup'); -} -exports.endGroup = endGroup; -/** - * Wrap an asynchronous function call in a group. - * - * Returns the same type as the function itself. - * - * @param name The name of the group - * @param fn The function to wrap in the group - */ -function group(name, fn) { - return __awaiter(this, void 0, void 0, function* () { - startGroup(name); - let result; - try { - result = yield fn(); + +module.exports = function paethPredictor(left, above, upLeft) { + let paeth = left + above - upLeft; + let pLeft = Math.abs(paeth - left); + let pAbove = Math.abs(paeth - above); + let pUpLeft = Math.abs(paeth - upLeft); + + if (pLeft <= pAbove && pLeft <= pUpLeft) { + return left; + } + if (pAbove <= pUpLeft) { + return above; + } + return upLeft; +}; + + +/***/ }), + +/***/ 7504: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +let util = __nccwpck_require__(9023); +let zlib = __nccwpck_require__(3106); +let ChunkStream = __nccwpck_require__(4369); +let FilterAsync = __nccwpck_require__(8539); +let Parser = __nccwpck_require__(6609); +let bitmapper = __nccwpck_require__(6106); +let formatNormaliser = __nccwpck_require__(998); + +let 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 { + let rowSize = + ((this._bitmapInfo.width * + this._bitmapInfo.bpp * + this._bitmapInfo.depth + + 7) >> + 3) + + 1; + let imageSize = rowSize * this._bitmapInfo.height; + let chunkSize = Math.max(imageSize, zlib.Z_MIN_CHUNK); + + this._inflate = zlib.createInflate({ chunkSize: chunkSize }); + let leftToInflate = imageSize; + + let emitError = this.emit.bind(this, "error"); + this._inflate.on("error", function (err) { + if (!leftToInflate) { + return; } - finally { - endGroup(); + + emitError(err); + }); + this._filter.on("complete", this._complete.bind(this)); + + let filterWrite = this._filter.write.bind(this._filter); + this._inflate.on("data", function (chunk) { + if (!leftToInflate) { + return; } - return result; - }); + + 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(); + } +}; + +ParserAsync.prototype._complete = function (filteredData) { + if (this.errord) { + return; + } + + let normalisedBitmapData; + + try { + let bitmapData = bitmapper.dataToBitMap(filteredData, this._bitmapInfo); + + normalisedBitmapData = formatNormaliser(bitmapData, this._bitmapInfo); + bitmapData = null; + } catch (ex) { + this._handleError(ex); + return; + } + + this.emit("parsed", normalisedBitmapData); +}; + + +/***/ }), + +/***/ 7345: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +let hasSyncZlib = true; +let zlib = __nccwpck_require__(3106); +let inflateSync = __nccwpck_require__(447); +if (!zlib.deflateSync) { + hasSyncZlib = false; } -exports.group = group; -//----------------------------------------------------------------------- -// Wrapper action state -//----------------------------------------------------------------------- -/** - * Saves state for current action, the state can only be retrieved by this action's post job execution. - * - * @param name name of the state to store - * @param value value to store. Non-string values will be converted to a string via JSON.stringify - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function saveState(name, value) { - const filePath = process.env['GITHUB_STATE'] || ''; - if (filePath) { - return file_command_1.issueFileCommand('STATE', file_command_1.prepareKeyValueMessage(name, value)); +let SyncReader = __nccwpck_require__(8613); +let FilterSync = __nccwpck_require__(8056); +let Parser = __nccwpck_require__(6609); +let bitmapper = __nccwpck_require__(6106); +let formatNormaliser = __nccwpck_require__(998); + +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" + ); + } + + let err; + function handleError(_err_) { + err = _err_; + } + + let metaData; + function handleMetaData(_metaData_) { + metaData = _metaData_; + } + + function handleTransColor(transColor) { + metaData.transColor = transColor; + } + + function handlePalette(palette) { + metaData.palette = palette; + } + + function handleSimpleTransparency() { + metaData.alpha = true; + } + + let gamma; + function handleGamma(_gamma_) { + gamma = _gamma_; + } + + let inflateDataList = []; + function handleInflateData(inflatedData) { + inflateDataList.push(inflatedData); + } + + let reader = new SyncReader(buffer); + + let 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 + let inflateData = Buffer.concat(inflateDataList); + inflateDataList.length = 0; + + let inflatedData; + if (metaData.interlace) { + inflatedData = zlib.inflateSync(inflateData); + } else { + let rowSize = + ((metaData.width * metaData.bpp * metaData.depth + 7) >> 3) + 1; + let 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"); + } + + let unfilteredData = FilterSync.process(inflatedData, metaData); + inflateData = null; + + let bitmapData = bitmapper.dataToBitMap(unfilteredData, metaData); + unfilteredData = null; + + let normalisedBitmapData = formatNormaliser(bitmapData, metaData); + + metaData.data = normalisedBitmapData; + metaData.gamma = gamma || 0; + + return metaData; +}; + + +/***/ }), + +/***/ 6609: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +let constants = __nccwpck_require__(1929); +let CrcCalculator = __nccwpck_require__(2918); + +let 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) { + let signature = constants.PNG_SIGNATURE; + + for (let i = 0; i < signature.length; i++) { + if (data[i] !== signature[i]) { + this.error(new Error("Invalid file signature")); + return; } - command_1.issueCommand('save-state', { name }, utils_1.toCommandValue(value)); -} -exports.saveState = saveState; -/** - * Gets the value of an state set by this action's main execution. - * - * @param name name of the state to get - * @returns string - */ -function getState(name) { - return process.env[`STATE_${name}`] || ''; -} -exports.getState = getState; -function getIDToken(aud) { - return __awaiter(this, void 0, void 0, function* () { - return yield oidc_utils_1.OidcClient.getIDToken(aud); - }); -} -exports.getIDToken = getIDToken; -/** - * Summary exports - */ -var summary_1 = __webpack_require__(665); -Object.defineProperty(exports, "summary", { enumerable: true, get: function () { return summary_1.summary; } }); -/** - * @deprecated use core.summary - */ -var summary_2 = __webpack_require__(665); -Object.defineProperty(exports, "markdownSummary", { enumerable: true, get: function () { return summary_2.markdownSummary; } }); -/** - * Path exports - */ -var path_utils_1 = __webpack_require__(573); -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; } }); -//# sourceMappingURL=core.js.map + } + this.read(8, this._parseChunkBegin.bind(this)); +}; -/***/ }), +Parser.prototype._parseChunkBegin = function (data) { + // chunk content length + let length = data.readUInt32BE(0); -/***/ 475: -/***/ (function(module, __unusedexports, __webpack_require__) { + // chunk type + let type = data.readUInt32BE(4); + let name = ""; + for (let i = 4; i < 8; i++) { + name += String.fromCharCode(data[i]); + } -var Mode = __webpack_require__(364) + //console.log('chunk ', name, length); -/** - * Array of characters available in alphanumeric mode - * - * As per QR Code specification, to each character - * is assigned a value from 0 to 44 which in this case coincides - * with the array index - * - * @type {Array} - */ -var ALPHA_NUM_CHARS = [ - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', - 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', - ' ', '$', '%', '*', '+', '-', '.', '/', ':' -] + // chunk flags + let ancillary = Boolean(data[4] & 0x20); // or critical + // priv = Boolean(data[5] & 0x20), // or public + // safeToCopy = Boolean(data[7] & 0x20); // or unsafe -function AlphanumericData (data) { - this.mode = Mode.ALPHANUMERIC - this.data = data -} + if (!this._hasIHDR && type !== constants.TYPE_IHDR) { + this.error(new Error("Expected IHDR on beggining")); + return; + } -AlphanumericData.getBitsLength = function getBitsLength (length) { - return 11 * Math.floor(length / 2) + 6 * (length % 2) -} + this._crc = new CrcCalculator(); + this._crc.write(Buffer.from(name)); -AlphanumericData.prototype.getLength = function getLength () { - return this.data.length -} + if (this._chunks[type]) { + return this._chunks[type](length); + } -AlphanumericData.prototype.getBitsLength = function getBitsLength () { - return AlphanumericData.getBitsLength(this.data.length) -} + if (!ancillary) { + this.error(new Error("Unsupported critical chunk type " + name)); + return; + } -AlphanumericData.prototype.write = function write (bitBuffer) { - var i + this.read(length + 4, this._skipChunk.bind(this)); +}; - // Input data characters are divided into groups of two characters - // and encoded as 11-bit binary codes. - for (i = 0; i + 2 <= this.data.length; i += 2) { - // The character value of the first character is multiplied by 45 - var value = ALPHA_NUM_CHARS.indexOf(this.data[i]) * 45 +Parser.prototype._skipChunk = function (/*data*/) { + this.read(8, this._parseChunkBegin.bind(this)); +}; - // The character value of the second digit is added to the product - value += ALPHA_NUM_CHARS.indexOf(this.data[i + 1]) +Parser.prototype._handleChunkEnd = function () { + this.read(4, this._parseChunkEnd.bind(this)); +}; - // The sum is then stored as 11-bit binary number - bitBuffer.put(value, 11) +Parser.prototype._parseChunkEnd = function (data) { + let fileCrc = data.readInt32BE(0); + let calcCrc = this._crc.crc32(); + + // check CRC + if (this._options.checkCRC && calcCrc !== fileCrc) { + this.error(new Error("Crc error - " + fileCrc + " - " + calcCrc)); + return; } - // If the number of input data characters is not a multiple of two, - // the character value of the final character is encoded as a 6-bit binary number. - if (this.data.length % 2) { - bitBuffer.put(ALPHA_NUM_CHARS.indexOf(this.data[i]), 6) + if (!this._hasIEND) { + this.read(8, this._parseChunkBegin.bind(this)); } -} +}; -module.exports = AlphanumericData +Parser.prototype._handleIHDR = function (length) { + this.read(length, this._parseIHDR.bind(this)); +}; +Parser.prototype._parseIHDR = function (data) { + this._crc.write(data); + let width = data.readUInt32BE(0); + let height = data.readUInt32BE(4); + let depth = data[8]; + let colorType = data[9]; // bits: 1 palette, 2 color, 4 alpha + let compr = data[10]; + let filter = data[11]; + let 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; -/***/ 501: -/***/ (function(module) { + let bpp = constants.COLORTYPE_TO_BPP_MAP[this._colorType]; -var toString = Object.prototype.toString + this._hasIHDR = true; -var isModern = ( - typeof Buffer.alloc === 'function' && - typeof Buffer.allocUnsafe === 'function' && - typeof Buffer.from === 'function' -) + 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, + }); -function isArrayBuffer (input) { - return toString.call(input).slice(8, -1) === 'ArrayBuffer' -} + this._handleChunkEnd(); +}; -function fromArrayBuffer (obj, byteOffset, length) { - byteOffset >>>= 0 +Parser.prototype._handlePLTE = function (length) { + this.read(length, this._parsePLTE.bind(this)); +}; +Parser.prototype._parsePLTE = function (data) { + this._crc.write(data); - var maxLength = obj.byteLength - byteOffset + let entries = Math.floor(data.length / 3); + // console.log('Palette:', entries); - if (maxLength < 0) { - throw new RangeError("'offset' is out of bounds") + for (let i = 0; i < entries; i++) { + this._palette.push([data[i * 3], data[i * 3 + 1], data[i * 3 + 2], 0xff]); } - if (length === undefined) { - length = maxLength - } else { - length >>>= 0 + 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); - if (length > maxLength) { - throw new RangeError("'length' is out of bounds") + // 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 (let i = 0; i < data.length; i++) { + this._palette[i][3] = data[i]; + } + this.palette(this._palette); } - return isModern - ? Buffer.from(obj.slice(byteOffset, byteOffset + length)) - : new Buffer(new Uint8Array(obj.slice(byteOffset, byteOffset + length))) -} + // 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), + ]); + } -function fromString (string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8' + 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 (!Buffer.isEncoding(encoding)) { - throw new TypeError('"encoding" must be a valid string encoding') + if ( + this._colorType === constants.COLORTYPE_PALETTE_COLOR && + this._palette.length === 0 + ) { + throw new Error("Expected palette not found"); } - return isModern - ? Buffer.from(string, encoding) - : new Buffer(string, encoding) -} + this.inflateData(data); + let leftOverLength = length - data.length; -function bufferFrom (value, encodingOrOffset, length) { - if (typeof value === 'number') { - throw new TypeError('"value" argument must not be a number') + if (leftOverLength > 0) { + this._handleIDAT(leftOverLength); + } else { + this._handleChunkEnd(); } +}; - if (isArrayBuffer(value)) { - return fromArrayBuffer(value, encodingOrOffset, length) - } +Parser.prototype._handleIEND = function (length) { + this.read(length, this._parseIEND.bind(this)); +}; +Parser.prototype._parseIEND = function (data) { + this._crc.write(data); - if (typeof value === 'string') { - return fromString(value, encodingOrOffset) + this._hasIEND = true; + this._handleChunkEnd(); + + if (this.finished) { + this.finished(); } +}; - return isModern - ? Buffer.from(value) - : new Buffer(value) -} -module.exports = bufferFrom +/***/ }), + +/***/ 3647: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +let parse = __nccwpck_require__(7345); +let pack = __nccwpck_require__(8562); + +exports.read = function (buffer, options) { + return parse(buffer, options || {}); +}; + +exports.write = function (png, options) { + return pack(png, options); +}; /***/ }), -/***/ 506: -/***/ (function(__unusedmodule, exports, __webpack_require__) { +/***/ 359: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +let util = __nccwpck_require__(9023); +let Stream = __nccwpck_require__(2203); +let Parser = __nccwpck_require__(7504); +let Packer = __nccwpck_require__(281); +let PNGSync = __nccwpck_require__(3647); + +let PNG = (exports.O = 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 + ? Buffer.alloc(4 * this.width * this.height) + : null; + + if (options.fill && this.data) { + this.data.fill(0); + } + + this.gamma = 0; + this.readable = this.writable = true; -"use strict"; + 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) + ); -Object.defineProperty(exports, "__esModule", { - value: true + 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")); }); -exports.default = rng; - -var _crypto = _interopRequireDefault(__webpack_require__(417)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +util.inherits(PNG, Stream); -const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate +PNG.sync = PNGSync; -let poolPtr = rnds8Pool.length; +PNG.prototype.pack = function () { + if (!this.data || !this.data.length) { + this.emit("error", "No data provided"); + return this; + } -function rng() { - if (poolPtr > rnds8Pool.length - 16) { - _crypto.default.randomFillSync(rnds8Pool); + process.nextTick( + function () { + this._packer.pack(this.data, this.width, this.height, this.gamma); + }.bind(this) + ); - poolPtr = 0; - } + return this; +}; - return rnds8Pool.slice(poolPtr, poolPtr += 16); -} +PNG.prototype.parse = function (data, callback) { + if (callback) { + let onParsed, onError; -/***/ }), + onParsed = function (parsedData) { + this.removeListener("error", onError); -/***/ 507: -/***/ (function(module, __unusedexports, __webpack_require__) { + this.data = parsedData; + callback(null, this); + }.bind(this); -"use strict"; + onError = function (err) { + this.removeListener("parsed", onParsed); + callback(err, null); + }.bind(this); -var util = __webpack_require__(669); -var zlib = __webpack_require__(761); -var ChunkStream = __webpack_require__(210); -var FilterAsync = __webpack_require__(432); -var Parser = __webpack_require__(932); -var bitmapper = __webpack_require__(319); -var formatNormaliser = __webpack_require__(994); + this.once("parsed", onParsed); + this.once("error", onError); + } -var ParserAsync = module.exports = function(options) { - ChunkStream.call(this); + this.end(data); + return 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; +PNG.prototype.write = function (data) { + this._parser.write(data); + return true; +}; - this._parser.start(); +PNG.prototype.end = function (data) { + this._parser.end(data); }; -util.inherits(ParserAsync, ChunkStream); +PNG.prototype._metadata = function (metadata) { + this.width = metadata.width; + this.height = metadata.height; -ParserAsync.prototype._handleError = function(err) { + this.emit("metadata", metadata); +}; - this.emit('error', err); +PNG.prototype._gamma = function (gamma) { + this.gamma = gamma; +}; - this.writable = false; +PNG.prototype._handleClose = function () { + if (!this._parser.writable && !this._packer.readable) { + this.emit("close"); + } +}; - this.destroy(); +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 (this._inflate && this._inflate.destroy) { - this._inflate.destroy(); + if ( + srcX > src.width || + srcY > src.height || + srcX + width > src.width || + srcY + height > src.height + ) { + throw new Error("bitblt reading outside image"); } - 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() {}); + if ( + deltaX > dst.width || + deltaY > dst.height || + deltaX + width > dst.width || + deltaY + height > dst.height + ) { + throw new Error("bitblt writing outside image"); } - this.errord = true; + for (let 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 + ); + } }; -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)); +PNG.prototype.bitblt = function ( + dst, + srcX, + srcY, + width, + height, + deltaX, + deltaY +) { + // eslint-disable-line max-params - 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); + PNG.bitblt(this, dst, srcX, srcY, width, height, deltaX, deltaY); + return this; +}; - this._inflate = zlib.createInflate({ chunkSize: chunkSize }); - var leftToInflate = imageSize; +PNG.adjustGamma = function (src) { + if (src.gamma) { + for (let y = 0; y < src.height; y++) { + for (let x = 0; x < src.width; x++) { + let idx = (src.width * y + x) << 2; - var emitError = this.emit.bind(this, 'error'); - this._inflate.on('error', function(err) { - if (!leftToInflate) { - return; + for (let i = 0; i < 3; i++) { + let 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; + } +}; - emitError(err); - }); - this._filter.on('complete', this._complete.bind(this)); +PNG.prototype.adjustGamma = function () { + PNG.adjustGamma(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; +/***/ 447: +/***/ ((module, exports, __nccwpck_require__) => { - filterWrite(chunk); - }); +"use strict"; - 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); +let assert = (__nccwpck_require__(2613).ok); +let zlib = __nccwpck_require__(3106); +let util = __nccwpck_require__(9023); - this._filter = new FilterAsync(this._bitmapInfo); -}; +let kMaxLength = (__nccwpck_require__(181).kMaxLength); -ParserAsync.prototype._handleTransColor = function(transColor) { - this._bitmapInfo.transColor = transColor; -}; +function Inflate(opts) { + if (!(this instanceof Inflate)) { + return new Inflate(opts); + } -ParserAsync.prototype._handlePalette = function(palette) { - this._bitmapInfo.palette = palette; -}; + if (opts && opts.chunkSize < zlib.Z_MIN_CHUNK) { + opts.chunkSize = zlib.Z_MIN_CHUNK; + } -ParserAsync.prototype._simpleTransparency = function() { - this._metaData.alpha = true; -}; + zlib.Inflate.call(this, opts); -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); -}; + // Node 8 --> 9 compatibility check + this._offset = this._offset === undefined ? this._outOffset : this._offset; + this._buffer = this._buffer || this._outBuffer; -ParserAsync.prototype._finished = function() { - if (this.errord) { - return; + if (opts && opts.maxLength != null) { + this._maxLength = opts.maxLength; } +} - if (!this._inflate) { - this.emit('error', 'No Inflate block'); - } - else { - // no more data to inflate - this._inflate.end(); - } - this.destroySoon(); -}; +function createInflate(opts) { + return new Inflate(opts); +} -ParserAsync.prototype._complete = function(filteredData) { +function _close(engine, callback) { + if (callback) { + process.nextTick(callback); + } - if (this.errord) { + // Caller may invoke .close after a zlib error (which will null _handle). + if (!engine._handle) { return; } - try { - var bitmapData = bitmapper.dataToBitMap(filteredData, this._bitmapInfo); + engine._handle.close(); + engine._handle = null; +} - var normalisedBitmapData = formatNormaliser(bitmapData, this._bitmapInfo); - bitmapData = null; - } - catch (ex) { - this._handleError(ex); - return; +Inflate.prototype._processChunk = function (chunk, flushFlag, asyncCb) { + if (typeof asyncCb === "function") { + return zlib.Inflate._processChunk.call(this, chunk, flushFlag, asyncCb); } - this.emit('parsed', normalisedBitmapData); -}; + let self = this; + let availInBefore = chunk && chunk.length; + let availOutBefore = this._chunkSize - this._offset; + let leftToInflate = this._maxLength; + let inOff = 0; -/***/ }), + let buffers = []; + let nread = 0; -/***/ 525: -/***/ (function(__unusedmodule, exports) { + let error; + this.on("error", function (err) { + error = err; + }); -"use strict"; + function handleChunk(availInAfter, availOutAfter) { + if (self._hadError) { + return; + } + let have = availOutBefore - availOutAfter; + assert(have >= 0, "have should not go down"); -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = void 0; -var _default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; -exports.default = _default; + if (have > 0) { + let out = self._buffer.slice(self._offset, self._offset + have); + self._offset += have; -/***/ }), + if (out.length > leftToInflate) { + out = out.slice(0, leftToInflate); + } -/***/ 526: -/***/ (function(__unusedmodule, exports, __webpack_require__) { + buffers.push(out); + nread += out.length; + leftToInflate -= out.length; -var BufferUtil = __webpack_require__(628) + if (leftToInflate === 0) { + return false; + } + } -var EXP_TABLE = BufferUtil.alloc(512) -var LOG_TABLE = BufferUtil.alloc(256) -/** - * Precompute the log and anti-log tables for faster computation later - * - * For each possible value in the galois field 2^8, we will pre-compute - * the logarithm and anti-logarithm (exponential) of this value - * - * ref {@link https://en.wikiversity.org/wiki/Reed%E2%80%93Solomon_codes_for_coders#Introduction_to_mathematical_fields} - */ -;(function initTables () { - var x = 1 - for (var i = 0; i < 255; i++) { - EXP_TABLE[i] = x - LOG_TABLE[x] = i + if (availOutAfter === 0 || self._offset >= self._chunkSize) { + availOutBefore = self._chunkSize; + self._offset = 0; + self._buffer = Buffer.allocUnsafe(self._chunkSize); + } - x <<= 1 // multiply by 2 + if (availOutAfter === 0) { + inOff += availInBefore - availInAfter; + availInBefore = availInAfter; - // The QR code specification says to use byte-wise modulo 100011101 arithmetic. - // This means that when a number is 256 or larger, it should be XORed with 0x11D. - if (x & 0x100) { // similar to x >= 256, but a lot faster (because 0x100 == 256) - x ^= 0x11D + return true; } + + return false; + } + + assert(this._handle, "zlib binding closed"); + let res; + do { + 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" + ); + } + + let 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"); } - // Optimization: double the size of the anti-log table so that we don't need to mod 255 to - // stay inside the bounds (because we will mainly use this table for the multiplication of - // two GF numbers, no more). - // @see {@link mul} - for (i = 255; i < 512; i++) { - EXP_TABLE[i] = EXP_TABLE[i - 255] + let flushFlag = engine._finishFlushFlag; + if (flushFlag == null) { + flushFlag = zlib.Z_FINISH; } -}()) -/** - * Returns log value of n inside Galois Field - * - * @param {Number} n - * @return {Number} - */ -exports.log = function log (n) { - if (n < 1) throw new Error('log(' + n + ')') - return LOG_TABLE[n] + return engine._processChunk(buffer, flushFlag); } -/** - * Returns anti-log value of n inside Galois Field - * - * @param {Number} n - * @return {Number} - */ -exports.exp = function exp (n) { - return EXP_TABLE[n] +function inflateSync(buffer, opts) { + return zlibBufferSync(new Inflate(opts), buffer); } -/** - * Multiplies two number inside Galois Field - * - * @param {Number} x - * @param {Number} y - * @return {Number} - */ -exports.mul = function mul (x, y) { - if (x === 0 || y === 0) return 0 - - // should be EXP_TABLE[(LOG_TABLE[x] + LOG_TABLE[y]) % 255] if EXP_TABLE wasn't oversized - // @see {@link initTables} - return EXP_TABLE[LOG_TABLE[x] + LOG_TABLE[y]] -} +module.exports = exports = inflateSync; +exports.Inflate = Inflate; +exports.createInflate = createInflate; +exports.inflateSync = inflateSync; /***/ }), -/***/ 554: -/***/ (function(__unusedmodule, exports) { +/***/ 8613: +/***/ ((module) => { "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.PersonalAccessTokenCredentialHandler = exports.BearerCredentialHandler = exports.BasicCredentialHandler = void 0; -class BasicCredentialHandler { - constructor(username, password) { - this.username = username; - this.password = password; - } - prepareRequest(options) { - if (!options.headers) { - throw Error('The request has no headers'); - } - options.headers['Authorization'] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString('base64')}`; - } - // This handler cannot handle 401 - canHandleAuthentication() { - return false; - } - handleAuthentication() { - return __awaiter(this, void 0, void 0, function* () { - throw new Error('not implemented'); - }); - } -} -exports.BasicCredentialHandler = BasicCredentialHandler; -class BearerCredentialHandler { - constructor(token) { - this.token = token; - } - // currently implements pre-authorization - // TODO: support preAuth = false where it hooks on 401 - prepareRequest(options) { - if (!options.headers) { - throw Error('The request has no headers'); - } - options.headers['Authorization'] = `Bearer ${this.token}`; - } - // This handler cannot handle 401 - canHandleAuthentication() { - return false; - } - handleAuthentication() { - return __awaiter(this, void 0, void 0, function* () { - throw new Error('not implemented'); - }); - } -} -exports.BearerCredentialHandler = BearerCredentialHandler; -class PersonalAccessTokenCredentialHandler { - constructor(token) { - this.token = token; - } - // currently implements pre-authorization - // TODO: support preAuth = false where it hooks on 401 - prepareRequest(options) { - if (!options.headers) { - throw Error('The request has no headers'); - } - options.headers['Authorization'] = `Basic ${Buffer.from(`PAT:${this.token}`).toString('base64')}`; - } - // This handler cannot handle 401 - canHandleAuthentication() { - return false; - } - handleAuthentication() { - return __awaiter(this, void 0, void 0, function* () { - throw new Error('not implemented'); - }); - } -} -exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; -//# sourceMappingURL=auth.js.map -/***/ }), +let 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, + }); +}; -/***/ 572: -/***/ (function(__unusedmodule, exports, __webpack_require__) { +SyncReader.prototype.process = function () { + // as long as there is any data and read requests + while (this._reads.length > 0 && this._buffer.length) { + let read = this._reads[0]; -"use strict"; + 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 + let buf = this._buffer; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = void 0; + this._buffer = buf.slice(read.length); -var _v = _interopRequireDefault(__webpack_require__(136)); + read.func.call(this, buf.slice(0, read.length)); + } else { + break; + } + } -var _md = _interopRequireDefault(__webpack_require__(659)); + if (this._reads.length > 0) { + return new Error("There are some read requests waitng on finished stream"); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (this._buffer.length > 0) { + return new Error("unrecognised content at end of stream"); + } +}; -const v3 = (0, _v.default)('v3', 0x30, _md.default); -var _default = v3; -exports.default = _default; /***/ }), -/***/ 573: -/***/ (function(__unusedmodule, exports, __webpack_require__) { +/***/ 1462: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; +var __webpack_unused_export__; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (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.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = void 0; -const path = __importStar(__webpack_require__(622)); -/** - * toPosixPath converts the given path to the posix form. On Windows, \\ will be - * replaced with /. - * - * @param pth. Path to transform. - * @return string Posix path. - */ -function toPosixPath(pth) { - return pth.replace(/[\\]/g, '/'); -} -exports.toPosixPath = toPosixPath; -/** - * toWin32Path converts the given path to the win32 form. On Linux, / will be - * replaced with \\. - * - * @param pth. Path to transform. - * @return string Win32 path. - */ -function toWin32Path(pth) { - return pth.replace(/[/]/g, '\\'); -} -exports.toWin32Path = toWin32Path; -/** - * toPlatformPath converts the given path to a platform-specific path. It does - * this by replacing instances of / and \ with the platform-specific path - * separator. - * - * @param pth The path to platformize. - * @return string The platform-specific path. - */ -function toPlatformPath(pth) { - return pth.replace(/[/\\]/g, path.sep); -} -exports.toPlatformPath = toPlatformPath; -//# sourceMappingURL=path-utils.js.map +const canPromise = __nccwpck_require__(5552) -/***/ }), +const QRCode = __nccwpck_require__(4024) +const CanvasRenderer = __nccwpck_require__(6090) +const SvgRenderer = __nccwpck_require__(8291) -/***/ 594: -/***/ (function(module) { +function renderCanvas (renderFunc, canvas, text, opts, cb) { + const args = [].slice.call(arguments, 1) + const argsNum = args.length + const isLastArgCb = typeof args[argsNum - 1] === 'function' -"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; -}; + if (!isLastArgCb && !canPromise()) { + throw new Error('Callback required as last argument') + } -/***/ }), + if (isLastArgCb) { + if (argsNum < 2) { + throw new Error('Too few arguments provided') + } + + if (argsNum === 2) { + cb = text + text = canvas + canvas = opts = undefined + } else if (argsNum === 3) { + if (canvas.getContext && typeof cb === 'undefined') { + cb = opts + opts = undefined + } else { + cb = opts + opts = text + text = canvas + canvas = undefined + } + } + } else { + if (argsNum < 1) { + throw new Error('Too few arguments provided') + } + + if (argsNum === 1) { + text = canvas + canvas = opts = undefined + } else if (argsNum === 2 && !canvas.getContext) { + opts = text + text = canvas + canvas = undefined + } -/***/ 605: -/***/ (function(module) { + return new Promise(function (resolve, reject) { + try { + const data = QRCode.create(text, opts) + resolve(renderFunc(data, canvas, opts)) + } catch (e) { + reject(e) + } + }) + } -module.exports = require("http"); + try { + const data = QRCode.create(text, opts) + cb(null, renderFunc(data, canvas, opts)) + } catch (e) { + cb(e) + } +} -/***/ }), +__webpack_unused_export__ = QRCode.create +exports.toCanvas = renderCanvas.bind(null, CanvasRenderer.render) +__webpack_unused_export__ = renderCanvas.bind(null, CanvasRenderer.renderToDataURL) -/***/ 614: -/***/ (function(module) { +// only svg for now. +__webpack_unused_export__ = renderCanvas.bind(null, function (data, _, opts) { + return SvgRenderer.render(data, opts) +}) -module.exports = require("events"); /***/ }), -/***/ 621: -/***/ (function(__unusedmodule, exports) { - -function hex2rgba (hex) { - if (typeof hex === 'number') { - hex = hex.toString() - } +/***/ 5552: +/***/ ((module) => { - if (typeof hex !== 'string') { - throw new Error('Color should be defined as hex string') - } +// can-promise has a crash in some versions of react native that dont have +// standard global objects +// https://github.com/soldair/node-qrcode/issues/157 - var hexCode = hex.slice().replace('#', '').split('') - if (hexCode.length < 3 || hexCode.length === 5 || hexCode.length > 8) { - throw new Error('Invalid hex color: ' + hex) - } +module.exports = function () { + return typeof Promise === 'function' && Promise.prototype && Promise.prototype.then +} - // Convert from short to long form (fff -> ffffff) - if (hexCode.length === 3 || hexCode.length === 4) { - hexCode = Array.prototype.concat.apply([], hexCode.map(function (c) { - return [c, c] - })) - } - // Add default alpha value - if (hexCode.length === 6) hexCode.push('F', 'F') +/***/ }), - var hexValue = parseInt(hexCode.join(''), 16) +/***/ 7290: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return { - r: (hexValue >> 24) & 255, - g: (hexValue >> 16) & 255, - b: (hexValue >> 8) & 255, - a: hexValue & 255, - hex: '#' + hexCode.slice(0, 6).join('') - } -} +/** + * Alignment pattern are fixed reference pattern in defined positions + * in a matrix symbology, which enables the decode software to re-synchronise + * the coordinate mapping of the image modules in the event of moderate amounts + * of distortion of the image. + * + * Alignment patterns are present only in QR Code symbols of version 2 or larger + * and their number depends on the symbol version. + */ -exports.getOptions = function getOptions (options) { - if (!options) options = {} - if (!options.color) options.color = {} +const getSymbolSize = (__nccwpck_require__(8317).getSymbolSize) - var margin = typeof options.margin === 'undefined' || - options.margin === null || - options.margin < 0 ? 4 : options.margin +/** + * Calculate the row/column coordinates of the center module of each alignment pattern + * for the specified QR Code version. + * + * The alignment patterns are positioned symmetrically on either side of the diagonal + * running from the top left corner of the symbol to the bottom right corner. + * + * Since positions are simmetrical only half of the coordinates are returned. + * Each item of the array will represent in turn the x and y coordinate. + * @see {@link getPositions} + * + * @param {Number} version QR Code version + * @return {Array} Array of coordinate + */ +exports.getRowColCoords = function getRowColCoords (version) { + if (version === 1) return [] - var width = options.width && options.width >= 21 ? options.width : undefined - var scale = options.scale || 4 + const posCount = Math.floor(version / 7) + 2 + const size = getSymbolSize(version) + const intervals = size === 145 ? 26 : Math.ceil((size - 13) / (2 * posCount - 2)) * 2 + const positions = [size - 7] // Last coord is always (size - 7) - return { - width: width, - scale: width ? 4 : scale, - margin: margin, - color: { - dark: hex2rgba(options.color.dark || '#000000ff'), - light: hex2rgba(options.color.light || '#ffffffff') - }, - type: options.type, - rendererOpts: options.rendererOpts || {} + for (let i = 1; i < posCount - 1; i++) { + positions[i] = positions[i - 1] - intervals } -} -exports.getScale = function getScale (qrSize, opts) { - return opts.width && opts.width >= qrSize + opts.margin * 2 - ? opts.width / (qrSize + opts.margin * 2) - : opts.scale -} + positions.push(6) // First coord is always 6 -exports.getImageWidth = function getImageWidth (qrSize, opts) { - var scale = exports.getScale(qrSize, opts) - return Math.floor((qrSize + opts.margin * 2) * scale) + return positions.reverse() } -exports.qrToImageData = function qrToImageData (imgData, qr, opts) { - var size = qr.modules.size - var data = qr.modules.data - var scale = exports.getScale(size, opts) - var symbolSize = Math.floor((size + opts.margin * 2) * scale) - var scaledMargin = opts.margin * scale - var palette = [opts.color.light, opts.color.dark] - - for (var i = 0; i < symbolSize; i++) { - for (var j = 0; j < symbolSize; j++) { - var posDst = (i * symbolSize + j) * 4 - var pxColor = opts.color.light +/** + * Returns an array containing the positions of each alignment pattern. + * Each array's element represent the center point of the pattern as (x, y) coordinates + * + * Coordinates are calculated expanding the row/column coordinates returned by {@link getRowColCoords} + * and filtering out the items that overlaps with finder pattern + * + * @example + * For a Version 7 symbol {@link getRowColCoords} returns values 6, 22 and 38. + * The alignment patterns, therefore, are to be centered on (row, column) + * positions (6,22), (22,6), (22,22), (22,38), (38,22), (38,38). + * Note that the coordinates (6,6), (6,38), (38,6) are occupied by finder patterns + * and are not therefore used for alignment patterns. + * + * let pos = getPositions(7) + * // [[6,22], [22,6], [22,22], [22,38], [38,22], [38,38]] + * + * @param {Number} version QR Code version + * @return {Array} Array of coordinates + */ +exports.getPositions = function getPositions (version) { + const coords = [] + const pos = exports.getRowColCoords(version) + const posLength = pos.length - if (i >= scaledMargin && j >= scaledMargin && - i < symbolSize - scaledMargin && j < symbolSize - scaledMargin) { - var iSrc = Math.floor((i - scaledMargin) / scale) - var jSrc = Math.floor((j - scaledMargin) / scale) - pxColor = palette[data[iSrc * size + jSrc] ? 1 : 0] + for (let i = 0; i < posLength; i++) { + for (let j = 0; j < posLength; j++) { + // Skip if position is occupied by finder patterns + if ((i === 0 && j === 0) || // top-left + (i === 0 && j === posLength - 1) || // bottom-left + (i === posLength - 1 && j === 0)) { // top-right + continue } - imgData[posDst++] = pxColor.r - imgData[posDst++] = pxColor.g - imgData[posDst++] = pxColor.b - imgData[posDst] = pxColor.a + coords.push([pos[i], pos[j]]) } } + + return coords } /***/ }), -/***/ 622: -/***/ (function(module) { +/***/ 6526: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -module.exports = require("path"); +const Mode = __nccwpck_require__(3913) -/***/ }), +/** + * Array of characters available in alphanumeric mode + * + * As per QR Code specification, to each character + * is assigned a value from 0 to 44 which in this case coincides + * with the array index + * + * @type {Array} + */ +const ALPHA_NUM_CHARS = [ + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', + 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', + ' ', '$', '%', '*', '+', '-', '.', '/', ':' +] -/***/ 628: -/***/ (function(module, __unusedexports, __webpack_require__) { +function AlphanumericData (data) { + this.mode = Mode.ALPHANUMERIC + this.data = data +} -module.exports.alloc = __webpack_require__(345) -module.exports.from = __webpack_require__(501) +AlphanumericData.getBitsLength = function getBitsLength (length) { + return 11 * Math.floor(length / 2) + 6 * (length % 2) +} +AlphanumericData.prototype.getLength = function getLength () { + return this.data.length +} -/***/ }), +AlphanumericData.prototype.getBitsLength = function getBitsLength () { + return AlphanumericData.getBitsLength(this.data.length) +} -/***/ 631: -/***/ (function(module) { +AlphanumericData.prototype.write = function write (bitBuffer) { + let i -module.exports = require("net"); + // Input data characters are divided into groups of two characters + // and encoded as 11-bit binary codes. + for (i = 0; i + 2 <= this.data.length; i += 2) { + // The character value of the first character is multiplied by 45 + let value = ALPHA_NUM_CHARS.indexOf(this.data[i]) * 45 -/***/ }), + // The character value of the second digit is added to the product + value += ALPHA_NUM_CHARS.indexOf(this.data[i + 1]) -/***/ 634: -/***/ (function(__unusedmodule, exports, __webpack_require__) { + // The sum is then stored as 11-bit binary number + bitBuffer.put(value, 11) + } -"use strict"; + // If the number of input data characters is not a multiple of two, + // the character value of the final character is encoded as a 6-bit binary number. + if (this.data.length % 2) { + bitBuffer.put(ALPHA_NUM_CHARS.indexOf(this.data[i]), 6) + } +} +module.exports = AlphanumericData -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = void 0; -var _regex = _interopRequireDefault(__webpack_require__(525)); +/***/ }), -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +/***/ 9618: +/***/ ((module) => { -function validate(uuid) { - return typeof uuid === 'string' && _regex.default.test(uuid); +function BitBuffer () { + this.buffer = [] + this.length = 0 } -var _default = validate; -exports.default = _default; - -/***/ }), +BitBuffer.prototype = { -/***/ 638: -/***/ (function(__unusedmodule, exports, __webpack_require__) { + get: function (index) { + const bufIndex = Math.floor(index / 8) + return ((this.buffer[bufIndex] >>> (7 - index % 8)) & 1) === 1 + }, -"use strict"; + put: function (num, length) { + for (let i = 0; i < length; i++) { + this.putBit(((num >>> (length - i - 1)) & 1) === 1) + } + }, + getLengthInBits: function () { + return this.length + }, -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = void 0; + putBit: function (bit) { + const bufIndex = Math.floor(this.length / 8) + if (this.buffer.length <= bufIndex) { + this.buffer.push(0) + } -var _v = _interopRequireDefault(__webpack_require__(136)); + if (bit) { + this.buffer[bufIndex] |= (0x80 >>> (this.length % 8)) + } -var _sha = _interopRequireDefault(__webpack_require__(329)); + this.length++ + } +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +module.exports = BitBuffer -const v5 = (0, _v.default)('v5', 0x50, _sha.default); -var _default = v5; -exports.default = _default; /***/ }), -/***/ 656: -/***/ (function(module, exports, __webpack_require__) { +/***/ 5281: +/***/ ((module) => { -"use strict"; +/** + * Helper class to handle QR Code symbol modules + * + * @param {Number} size Symbol size + */ +function BitMatrix (size) { + if (!size || size < 1) { + throw new Error('BitMatrix size must be defined and greater than 0') + } + + this.size = size + this.data = new Uint8Array(size * size) + this.reservedBit = new Uint8Array(size * size) +} + +/** + * Set bit value at specified location + * If reserved flag is set, this bit will be ignored during masking process + * + * @param {Number} row + * @param {Number} col + * @param {Boolean} value + * @param {Boolean} reserved + */ +BitMatrix.prototype.set = function (row, col, value, reserved) { + const index = row * this.size + col + this.data[index] = value + if (reserved) this.reservedBit[index] = true +} + +/** + * Returns bit value at specified location + * + * @param {Number} row + * @param {Number} col + * @return {Boolean} + */ +BitMatrix.prototype.get = function (row, col) { + return this.data[row * this.size + col] +} +/** + * Applies xor operator at specified location + * (used during masking process) + * + * @param {Number} row + * @param {Number} col + * @param {Boolean} value + */ +BitMatrix.prototype.xor = function (row, col, value) { + this.data[row * this.size + col] ^= value +} -var assert = __webpack_require__(357).ok; -var zlib = __webpack_require__(761); -var util = __webpack_require__(669); +/** + * Check if bit at specified location is reserved + * + * @param {Number} row + * @param {Number} col + * @return {Boolean} + */ +BitMatrix.prototype.isReserved = function (row, col) { + return this.reservedBit[row * this.size + col] +} -var kMaxLength = __webpack_require__(407).kMaxLength; +module.exports = BitMatrix -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); +/***/ 7205: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // Node 8 --> 9 compatibility check - this._offset = this._offset === undefined ? this._outOffset : this._offset; - this._buffer = this._buffer || this._outBuffer; +const Mode = __nccwpck_require__(3913) - if (opts && opts.maxLength != null) { - this._maxLength = opts.maxLength; +function ByteData (data) { + this.mode = Mode.BYTE + if (typeof (data) === 'string') { + this.data = new TextEncoder().encode(data) + } else { + this.data = new Uint8Array(data) } } -function createInflate(opts) { - return new Inflate(opts); +ByteData.getBitsLength = function getBitsLength (length) { + return length * 8 } -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; - } +ByteData.prototype.getLength = function getLength () { + return this.data.length +} - engine._handle.close(); - engine._handle = null; +ByteData.prototype.getBitsLength = function getBitsLength () { + return ByteData.getBitsLength(this.data.length) } -Inflate.prototype._processChunk = function(chunk, flushFlag, asyncCb) { - if (typeof asyncCb === 'function') { - return zlib.Inflate._processChunk.call(this, chunk, flushFlag, asyncCb); +ByteData.prototype.write = function (bitBuffer) { + for (let i = 0, l = this.data.length; i < l; i++) { + bitBuffer.put(this.data[i], 8) } +} - 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; +module.exports = ByteData - if (out.length > leftToInflate) { - out = out.slice(0, leftToInflate); - } - buffers.push(out); - nread += out.length; - leftToInflate -= out.length; +/***/ }), - if (leftToInflate === 0) { - return false; - } - } +/***/ 3185: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (availOutAfter === 0 || self._offset >= self._chunkSize) { - availOutBefore = self._chunkSize; - self._offset = 0; - self._buffer = Buffer.allocUnsafe(self._chunkSize); - } +const ECLevel = __nccwpck_require__(3644) + +const EC_BLOCKS_TABLE = [ +// L M Q H + 1, 1, 1, 1, + 1, 1, 1, 1, + 1, 1, 2, 2, + 1, 2, 2, 4, + 1, 2, 4, 4, + 2, 4, 4, 4, + 2, 4, 6, 5, + 2, 4, 6, 6, + 2, 5, 8, 8, + 4, 5, 8, 8, + 4, 5, 8, 11, + 4, 8, 10, 11, + 4, 9, 12, 16, + 4, 9, 16, 16, + 6, 10, 12, 18, + 6, 10, 17, 16, + 6, 11, 16, 19, + 6, 13, 18, 21, + 7, 14, 21, 25, + 8, 16, 20, 25, + 8, 17, 23, 25, + 9, 17, 23, 34, + 9, 18, 25, 30, + 10, 20, 27, 32, + 12, 21, 29, 35, + 12, 23, 34, 37, + 12, 25, 34, 40, + 13, 26, 35, 42, + 14, 28, 38, 45, + 15, 29, 40, 48, + 16, 31, 43, 51, + 17, 33, 45, 54, + 18, 35, 48, 57, + 19, 37, 51, 60, + 19, 38, 53, 63, + 20, 40, 56, 66, + 21, 43, 59, 70, + 22, 45, 62, 74, + 24, 47, 65, 77, + 25, 49, 68, 81 +] + +const EC_CODEWORDS_TABLE = [ +// L M Q H + 7, 10, 13, 17, + 10, 16, 22, 28, + 15, 26, 36, 44, + 20, 36, 52, 64, + 26, 48, 72, 88, + 36, 64, 96, 112, + 40, 72, 108, 130, + 48, 88, 132, 156, + 60, 110, 160, 192, + 72, 130, 192, 224, + 80, 150, 224, 264, + 96, 176, 260, 308, + 104, 198, 288, 352, + 120, 216, 320, 384, + 132, 240, 360, 432, + 144, 280, 408, 480, + 168, 308, 448, 532, + 180, 338, 504, 588, + 196, 364, 546, 650, + 224, 416, 600, 700, + 224, 442, 644, 750, + 252, 476, 690, 816, + 270, 504, 750, 900, + 300, 560, 810, 960, + 312, 588, 870, 1050, + 336, 644, 952, 1110, + 360, 700, 1020, 1200, + 390, 728, 1050, 1260, + 420, 784, 1140, 1350, + 450, 812, 1200, 1440, + 480, 868, 1290, 1530, + 510, 924, 1350, 1620, + 540, 980, 1440, 1710, + 570, 1036, 1530, 1800, + 570, 1064, 1590, 1890, + 600, 1120, 1680, 1980, + 630, 1204, 1770, 2100, + 660, 1260, 1860, 2220, + 720, 1316, 1950, 2310, + 750, 1372, 2040, 2430 +] + +/** + * Returns the number of error correction block that the QR Code should contain + * for the specified version and error correction level. + * + * @param {Number} version QR Code version + * @param {Number} errorCorrectionLevel Error correction level + * @return {Number} Number of error correction blocks + */ +exports.getBlocksCount = function getBlocksCount (version, errorCorrectionLevel) { + switch (errorCorrectionLevel) { + case ECLevel.L: + return EC_BLOCKS_TABLE[(version - 1) * 4 + 0] + case ECLevel.M: + return EC_BLOCKS_TABLE[(version - 1) * 4 + 1] + case ECLevel.Q: + return EC_BLOCKS_TABLE[(version - 1) * 4 + 2] + case ECLevel.H: + return EC_BLOCKS_TABLE[(version - 1) * 4 + 3] + default: + return undefined + } +} + +/** + * Returns the number of error correction codewords to use for the specified + * version and error correction level. + * + * @param {Number} version QR Code version + * @param {Number} errorCorrectionLevel Error correction level + * @return {Number} Number of error correction codewords + */ +exports.getTotalCodewordsCount = function getTotalCodewordsCount (version, errorCorrectionLevel) { + switch (errorCorrectionLevel) { + case ECLevel.L: + return EC_CODEWORDS_TABLE[(version - 1) * 4 + 0] + case ECLevel.M: + return EC_CODEWORDS_TABLE[(version - 1) * 4 + 1] + case ECLevel.Q: + return EC_CODEWORDS_TABLE[(version - 1) * 4 + 2] + case ECLevel.H: + return EC_CODEWORDS_TABLE[(version - 1) * 4 + 3] + default: + return undefined + } +} - if (availOutAfter === 0) { - inOff += (availInBefore - availInAfter); - availInBefore = availInAfter; - return true; - } +/***/ }), - return false; - } +/***/ 3644: +/***/ ((__unused_webpack_module, exports) => { - 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])); +exports.L = { bit: 1 } +exports.M = { bit: 0 } +exports.Q = { bit: 3 } +exports.H = { bit: 2 } - if (this._hadError) { - throw error; +function fromString (string) { + if (typeof string !== 'string') { + throw new Error('Param is not a string') } - if (nread >= kMaxLength) { - _close(this); - throw new RangeError('Cannot create final Buffer. It would be larger than 0x' + kMaxLength.toString(16) + ' bytes'); - } + const lcStr = string.toLowerCase() - var buf = Buffer.concat(buffers, nread); - _close(this); + switch (lcStr) { + case 'l': + case 'low': + return exports.L - return buf; -}; + case 'm': + case 'medium': + return exports.M -util.inherits(Inflate, zlib.Inflate); + case 'q': + case 'quartile': + return exports.Q -function zlibBufferSync(engine, buffer) { - if (typeof buffer === 'string') { - buffer = Buffer.from(buffer); - } - if (!(buffer instanceof Buffer)) { - throw new TypeError('Not a string or buffer'); - } + case 'h': + case 'high': + return exports.H - var flushFlag = engine._finishFlushFlag; - if (flushFlag == null) { - flushFlag = zlib.Z_FINISH; + default: + throw new Error('Unknown EC Level: ' + string) } - - return engine._processChunk(buffer, flushFlag); } -function inflateSync(buffer, opts) { - return zlibBufferSync(new Inflate(opts), buffer); +exports.isValid = function isValid (level) { + return level && typeof level.bit !== 'undefined' && + level.bit >= 0 && level.bit < 4 } -module.exports = exports = inflateSync; -exports.Inflate = Inflate; -exports.createInflate = createInflate; -exports.inflateSync = inflateSync; +exports.from = function from (value, defaultValue) { + if (exports.isValid(value)) { + return value + } + + try { + return fromString(value) + } catch (e) { + return defaultValue + } +} /***/ }), -/***/ 657: -/***/ (function(module, __unusedexports, __webpack_require__) { +/***/ 8129: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; +const getSymbolSize = (__nccwpck_require__(8317).getSymbolSize) +const FINDER_PATTERN_SIZE = 7 +/** + * Returns an array containing the positions of each finder pattern. + * Each array's element represent the top-left point of the pattern as (x, y) coordinates + * + * @param {Number} version QR Code version + * @return {Array} Array of coordinates + */ +exports.getPositions = function getPositions (version) { + const size = getSymbolSize(version) -var hasSyncZlib = true; -var zlib = __webpack_require__(761); -var inflateSync = __webpack_require__(656); -if (!zlib.deflateSync) { - hasSyncZlib = false; + return [ + // top-left + [0, 0], + // top-right + [size - FINDER_PATTERN_SIZE, 0], + // bottom-left + [0, size - FINDER_PATTERN_SIZE] + ] } -var SyncReader = __webpack_require__(80); -var FilterSync = __webpack_require__(904); -var Parser = __webpack_require__(932); -var bitmapper = __webpack_require__(319); -var formatNormaliser = __webpack_require__(994); -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'); - } +/***/ 7570: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - var err; - function handleError(_err_) { - err = _err_; - } +const Utils = __nccwpck_require__(8317) - var metaData; - function handleMetaData(_metaData_) { - metaData = _metaData_; - } +const G15 = (1 << 10) | (1 << 8) | (1 << 5) | (1 << 4) | (1 << 2) | (1 << 1) | (1 << 0) +const G15_MASK = (1 << 14) | (1 << 12) | (1 << 10) | (1 << 4) | (1 << 1) +const G15_BCH = Utils.getBCHDigit(G15) - function handleTransColor(transColor) { - metaData.transColor = transColor; - } +/** + * Returns format information with relative error correction bits + * + * The format information is a 15-bit sequence containing 5 data bits, + * with 10 error correction bits calculated using the (15, 5) BCH code. + * + * @param {Number} errorCorrectionLevel Error correction level + * @param {Number} mask Mask pattern + * @return {Number} Encoded format information bits + */ +exports.getEncodedBits = function getEncodedBits (errorCorrectionLevel, mask) { + const data = ((errorCorrectionLevel.bit << 3) | mask) + let d = data << 10 - function handlePalette(palette) { - metaData.palette = palette; + while (Utils.getBCHDigit(d) - G15_BCH >= 0) { + d ^= (G15 << (Utils.getBCHDigit(d) - G15_BCH)) } - function handleSimpleTransparency() { - metaData.alpha = true; - } + // xor final data with mask pattern in order to ensure that + // no combination of Error Correction Level and data mask pattern + // will result in an all-zero data string + return ((data << 10) | d) ^ G15_MASK +} - var gamma; - function handleGamma(_gamma_) { - gamma = _gamma_; - } - var inflateDataList = []; - function handleInflateData(inflatedData) { - inflateDataList.push(inflatedData); - } +/***/ }), - var reader = new SyncReader(buffer); +/***/ 234: +/***/ ((__unused_webpack_module, exports) => { - var parser = new Parser(options, { - read: reader.read.bind(reader), - error: handleError, - metadata: handleMetaData, - gamma: handleGamma, - palette: handlePalette, - transColor: handleTransColor, - inflateData: handleInflateData, - simpleTransparency: handleSimpleTransparency - }); +const EXP_TABLE = new Uint8Array(512) +const LOG_TABLE = new Uint8Array(256) +/** + * Precompute the log and anti-log tables for faster computation later + * + * For each possible value in the galois field 2^8, we will pre-compute + * the logarithm and anti-logarithm (exponential) of this value + * + * ref {@link https://en.wikiversity.org/wiki/Reed%E2%80%93Solomon_codes_for_coders#Introduction_to_mathematical_fields} + */ +;(function initTables () { + let x = 1 + for (let i = 0; i < 255; i++) { + EXP_TABLE[i] = x + LOG_TABLE[x] = i - parser.start(); - reader.process(); + x <<= 1 // multiply by 2 - if (err) { - throw err; + // The QR code specification says to use byte-wise modulo 100011101 arithmetic. + // This means that when a number is 256 or larger, it should be XORed with 0x11D. + if (x & 0x100) { // similar to x >= 256, but a lot faster (because 0x100 == 256) + x ^= 0x11D + } } - //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 }); + // Optimization: double the size of the anti-log table so that we don't need to mod 255 to + // stay inside the bounds (because we will mainly use this table for the multiplication of + // two GF numbers, no more). + // @see {@link mul} + for (let i = 255; i < 512; i++) { + EXP_TABLE[i] = EXP_TABLE[i - 255] } - inflateData = null; +}()) - if (!inflatedData || !inflatedData.length) { - throw new Error('bad png - invalid inflate data response'); - } +/** + * Returns log value of n inside Galois Field + * + * @param {Number} n + * @return {Number} + */ +exports.log = function log (n) { + if (n < 1) throw new Error('log(' + n + ')') + return LOG_TABLE[n] +} - var unfilteredData = FilterSync.process(inflatedData, metaData); - inflateData = null; +/** + * Returns anti-log value of n inside Galois Field + * + * @param {Number} n + * @return {Number} + */ +exports.exp = function exp (n) { + return EXP_TABLE[n] +} - var bitmapData = bitmapper.dataToBitMap(unfilteredData, metaData); - unfilteredData = null; +/** + * Multiplies two number inside Galois Field + * + * @param {Number} x + * @param {Number} y + * @return {Number} + */ +exports.mul = function mul (x, y) { + if (x === 0 || y === 0) return 0 - var normalisedBitmapData = formatNormaliser(bitmapData, metaData); + // should be EXP_TABLE[(LOG_TABLE[x] + LOG_TABLE[y]) % 255] if EXP_TABLE wasn't oversized + // @see {@link initTables} + return EXP_TABLE[LOG_TABLE[x] + LOG_TABLE[y]] +} - metaData.data = normalisedBitmapData; - metaData.gamma = gamma || 0; - return metaData; -}; +/***/ }), +/***/ 7596: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/***/ }), +const Mode = __nccwpck_require__(3913) +const Utils = __nccwpck_require__(8317) -/***/ 659: -/***/ (function(__unusedmodule, exports, __webpack_require__) { +function KanjiData (data) { + this.mode = Mode.KANJI + this.data = data +} -"use strict"; +KanjiData.getBitsLength = function getBitsLength (length) { + return length * 13 +} +KanjiData.prototype.getLength = function getLength () { + return this.data.length +} -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = void 0; +KanjiData.prototype.getBitsLength = function getBitsLength () { + return KanjiData.getBitsLength(this.data.length) +} + +KanjiData.prototype.write = function (bitBuffer) { + let i + + // In the Shift JIS system, Kanji characters are represented by a two byte combination. + // These byte values are shifted from the JIS X 0208 values. + // JIS X 0208 gives details of the shift coded representation. + for (i = 0; i < this.data.length; i++) { + let value = Utils.toSJIS(this.data[i]) + + // For characters with Shift JIS values from 0x8140 to 0x9FFC: + if (value >= 0x8140 && value <= 0x9FFC) { + // Subtract 0x8140 from Shift JIS value + value -= 0x8140 -var _crypto = _interopRequireDefault(__webpack_require__(417)); + // For characters with Shift JIS values from 0xE040 to 0xEBBF + } else if (value >= 0xE040 && value <= 0xEBBF) { + // Subtract 0xC140 from Shift JIS value + value -= 0xC140 + } else { + throw new Error( + 'Invalid SJIS character: ' + this.data[i] + '\n' + + 'Make sure your charset is UTF-8') + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + // Multiply most significant byte of result by 0xC0 + // and add least significant byte to product + value = (((value >>> 8) & 0xff) * 0xC0) + (value & 0xff) -function md5(bytes) { - if (Array.isArray(bytes)) { - bytes = Buffer.from(bytes); - } else if (typeof bytes === 'string') { - bytes = Buffer.from(bytes, 'utf8'); + // Convert result to a 13-bit binary string + bitBuffer.put(value, 13) } +} + +module.exports = KanjiData - return _crypto.default.createHash('md5').update(bytes).digest(); + +/***/ }), + +/***/ 1597: +/***/ ((__unused_webpack_module, exports) => { + +/** + * Data mask pattern reference + * @type {Object} + */ +exports.Patterns = { + PATTERN000: 0, + PATTERN001: 1, + PATTERN010: 2, + PATTERN011: 3, + PATTERN100: 4, + PATTERN101: 5, + PATTERN110: 6, + PATTERN111: 7 } -var _default = md5; -exports.default = _default; - -/***/ }), - -/***/ 665: -/***/ (function(__unusedmodule, exports, __webpack_require__) { +/** + * Weighted penalty scores for the undesirable features + * @type {Object} + */ +const PenaltyScores = { + N1: 3, + N2: 3, + N3: 40, + N4: 10 +} -"use strict"; +/** + * Check if mask pattern value is valid + * + * @param {Number} mask Mask pattern + * @return {Boolean} true if valid, false otherwise + */ +exports.isValid = function isValid (mask) { + return mask != null && mask !== '' && !isNaN(mask) && mask >= 0 && mask <= 7 +} -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.summary = exports.markdownSummary = exports.SUMMARY_DOCS_URL = exports.SUMMARY_ENV_VAR = void 0; -const os_1 = __webpack_require__(87); -const fs_1 = __webpack_require__(747); -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'; -class Summary { - constructor() { - this._buffer = ''; - } - /** - * Finds the summary file path from the environment, rejects if env var is not found or file does not exist - * Also checks r/w permissions. - * - * @returns step summary file path - */ - filePath() { - return __awaiter(this, void 0, void 0, function* () { - if (this._filePath) { - return this._filePath; - } - const pathFromEnv = process.env[exports.SUMMARY_ENV_VAR]; - if (!pathFromEnv) { - throw new Error(`Unable to find environment variable for $${exports.SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`); - } - try { - yield access(pathFromEnv, fs_1.constants.R_OK | fs_1.constants.W_OK); - } - catch (_a) { - throw new Error(`Unable to access summary file: '${pathFromEnv}'. Check if the file has correct read/write permissions.`); - } - this._filePath = pathFromEnv; - return this._filePath; - }); - } - /** - * Wraps content in an HTML tag, adding any HTML attributes - * - * @param {string} tag HTML tag to wrap - * @param {string | null} content content within the tag - * @param {[attribute: string]: string} attrs key-value list of HTML attributes to add - * - * @returns {string} content wrapped in HTML element - */ - wrap(tag, content, attrs = {}) { - const htmlAttrs = Object.entries(attrs) - .map(([key, value]) => ` ${key}="${value}"`) - .join(''); - if (!content) { - return `<${tag}${htmlAttrs}>`; - } - return `<${tag}${htmlAttrs}>${content}`; - } - /** - * Writes text in the buffer to the summary buffer file and empties buffer. Will append by default. - * - * @param {SummaryWriteOptions} [options] (optional) options for write operation - * - * @returns {Promise} summary instance - */ - write(options) { - return __awaiter(this, void 0, void 0, function* () { - const overwrite = !!(options === null || options === void 0 ? void 0 : options.overwrite); - const filePath = yield this.filePath(); - const writeFunc = overwrite ? writeFile : appendFile; - yield writeFunc(filePath, this._buffer, { encoding: 'utf8' }); - return this.emptyBuffer(); - }); - } - /** - * Clears the summary buffer and wipes the summary file - * - * @returns {Summary} summary instance - */ - clear() { - return __awaiter(this, void 0, void 0, function* () { - return this.emptyBuffer().write({ overwrite: true }); - }); - } - /** - * Returns the current summary buffer as a string - * - * @returns {string} string of summary buffer - */ - stringify() { - return this._buffer; - } - /** - * If the summary buffer is empty - * - * @returns {boolen} true if the buffer is empty - */ - isEmptyBuffer() { - return this._buffer.length === 0; - } - /** - * Resets the summary buffer without writing to summary file - * - * @returns {Summary} summary instance - */ - emptyBuffer() { - this._buffer = ''; - return this; - } - /** - * Adds raw text to the summary buffer - * - * @param {string} text content to add - * @param {boolean} [addEOL=false] (optional) append an EOL to the raw text (default: false) - * - * @returns {Summary} summary instance - */ - addRaw(text, addEOL = false) { - this._buffer += text; - return addEOL ? this.addEOL() : this; - } - /** - * Adds the operating system-specific end-of-line marker to the buffer - * - * @returns {Summary} summary instance - */ - addEOL() { - return this.addRaw(os_1.EOL); - } - /** - * Adds an HTML codeblock to the summary buffer - * - * @param {string} code content to render within fenced code block - * @param {string} lang (optional) language to syntax highlight code - * - * @returns {Summary} summary instance - */ - addCodeBlock(code, lang) { - const attrs = Object.assign({}, (lang && { lang })); - const element = this.wrap('pre', this.wrap('code', code), attrs); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML list to the summary buffer - * - * @param {string[]} items list of items to render - * @param {boolean} [ordered=false] (optional) if the rendered list should be ordered or not (default: false) - * - * @returns {Summary} summary instance - */ - addList(items, ordered = false) { - const tag = ordered ? 'ol' : 'ul'; - const listItems = items.map(item => this.wrap('li', item)).join(''); - const element = this.wrap(tag, listItems); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML table to the summary buffer - * - * @param {SummaryTableCell[]} rows table rows - * - * @returns {Summary} summary instance - */ - addTable(rows) { - const tableBody = rows - .map(row => { - const cells = row - .map(cell => { - if (typeof cell === 'string') { - return this.wrap('td', cell); - } - const { header, data, colspan, rowspan } = cell; - const tag = header ? 'th' : 'td'; - const attrs = Object.assign(Object.assign({}, (colspan && { colspan })), (rowspan && { rowspan })); - return this.wrap(tag, data, attrs); - }) - .join(''); - return this.wrap('tr', cells); - }) - .join(''); - const element = this.wrap('table', tableBody); - return this.addRaw(element).addEOL(); - } - /** - * Adds a collapsable HTML details element to the summary buffer - * - * @param {string} label text for the closed state - * @param {string} content collapsable content - * - * @returns {Summary} summary instance - */ - addDetails(label, content) { - const element = this.wrap('details', this.wrap('summary', label) + content); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML image tag to the summary buffer - * - * @param {string} src path to the image you to embed - * @param {string} alt text description of the image - * @param {SummaryImageOptions} options (optional) addition image attributes - * - * @returns {Summary} summary instance - */ - addImage(src, alt, options) { - const { width, height } = options || {}; - const attrs = Object.assign(Object.assign({}, (width && { width })), (height && { height })); - const element = this.wrap('img', null, Object.assign({ src, alt }, attrs)); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML section heading element - * - * @param {string} text heading text - * @param {number | string} [level=1] (optional) the heading level, default: 1 - * - * @returns {Summary} summary instance - */ - addHeading(text, level) { - const tag = `h${level}`; - const allowedTag = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(tag) - ? tag - : 'h1'; - const element = this.wrap(allowedTag, text); - return this.addRaw(element).addEOL(); +/** + * Returns mask pattern from a value. + * If value is not valid, returns undefined + * + * @param {Number|String} value Mask pattern value + * @return {Number} Valid mask pattern or undefined + */ +exports.from = function from (value) { + return exports.isValid(value) ? parseInt(value, 10) : undefined +} + +/** +* Find adjacent modules in row/column with the same color +* and assign a penalty value. +* +* Points: N1 + i +* i is the amount by which the number of adjacent modules of the same color exceeds 5 +*/ +exports.getPenaltyN1 = function getPenaltyN1 (data) { + const size = data.size + let points = 0 + let sameCountCol = 0 + let sameCountRow = 0 + let lastCol = null + let lastRow = null + + for (let row = 0; row < size; row++) { + sameCountCol = sameCountRow = 0 + lastCol = lastRow = null + + for (let col = 0; col < size; col++) { + let module = data.get(row, col) + if (module === lastCol) { + sameCountCol++ + } else { + if (sameCountCol >= 5) points += PenaltyScores.N1 + (sameCountCol - 5) + lastCol = module + sameCountCol = 1 + } + + module = data.get(col, row) + if (module === lastRow) { + sameCountRow++ + } else { + if (sameCountRow >= 5) points += PenaltyScores.N1 + (sameCountRow - 5) + lastRow = module + sameCountRow = 1 + } } - /** - * Adds an HTML thematic break (
) to the summary buffer - * - * @returns {Summary} summary instance - */ - addSeparator() { - const element = this.wrap('hr', null); - return this.addRaw(element).addEOL(); + + if (sameCountCol >= 5) points += PenaltyScores.N1 + (sameCountCol - 5) + if (sameCountRow >= 5) points += PenaltyScores.N1 + (sameCountRow - 5) + } + + return points +} + +/** + * Find 2x2 blocks with the same color and assign a penalty value + * + * Points: N2 * (m - 1) * (n - 1) + */ +exports.getPenaltyN2 = function getPenaltyN2 (data) { + const size = data.size + let points = 0 + + for (let row = 0; row < size - 1; row++) { + for (let col = 0; col < size - 1; col++) { + const last = data.get(row, col) + + data.get(row, col + 1) + + data.get(row + 1, col) + + data.get(row + 1, col + 1) + + if (last === 4 || last === 0) points++ } - /** - * Adds an HTML line break (
) to the summary buffer - * - * @returns {Summary} summary instance - */ - addBreak() { - const element = this.wrap('br', null); - return this.addRaw(element).addEOL(); + } + + return points * PenaltyScores.N2 +} + +/** + * Find 1:1:3:1:1 ratio (dark:light:dark:light:dark) pattern in row/column, + * preceded or followed by light area 4 modules wide + * + * Points: N3 * number of pattern found + */ +exports.getPenaltyN3 = function getPenaltyN3 (data) { + const size = data.size + let points = 0 + let bitsCol = 0 + let bitsRow = 0 + + for (let row = 0; row < size; row++) { + bitsCol = bitsRow = 0 + for (let col = 0; col < size; col++) { + bitsCol = ((bitsCol << 1) & 0x7FF) | data.get(row, col) + if (col >= 10 && (bitsCol === 0x5D0 || bitsCol === 0x05D)) points++ + + bitsRow = ((bitsRow << 1) & 0x7FF) | data.get(col, row) + if (col >= 10 && (bitsRow === 0x5D0 || bitsRow === 0x05D)) points++ } - /** - * Adds an HTML blockquote to the summary buffer - * - * @param {string} text quote text - * @param {string} cite (optional) citation url - * - * @returns {Summary} summary instance - */ - addQuote(text, cite) { - const attrs = Object.assign({}, (cite && { cite })); - const element = this.wrap('blockquote', text, attrs); - return this.addRaw(element).addEOL(); + } + + return points * PenaltyScores.N3 +} + +/** + * Calculate proportion of dark modules in entire symbol + * + * Points: N4 * k + * + * k is the rating of the deviation of the proportion of dark modules + * in the symbol from 50% in steps of 5% + */ +exports.getPenaltyN4 = function getPenaltyN4 (data) { + let darkCount = 0 + const modulesCount = data.data.length + + for (let i = 0; i < modulesCount; i++) darkCount += data.data[i] + + const k = Math.abs(Math.ceil((darkCount * 100 / modulesCount) / 5) - 10) + + return k * PenaltyScores.N4 +} + +/** + * Return mask value at given position + * + * @param {Number} maskPattern Pattern reference value + * @param {Number} i Row + * @param {Number} j Column + * @return {Boolean} Mask value + */ +function getMaskAt (maskPattern, i, j) { + switch (maskPattern) { + case exports.Patterns.PATTERN000: return (i + j) % 2 === 0 + case exports.Patterns.PATTERN001: return i % 2 === 0 + case exports.Patterns.PATTERN010: return j % 3 === 0 + case exports.Patterns.PATTERN011: return (i + j) % 3 === 0 + case exports.Patterns.PATTERN100: return (Math.floor(i / 2) + Math.floor(j / 3)) % 2 === 0 + case exports.Patterns.PATTERN101: return (i * j) % 2 + (i * j) % 3 === 0 + case exports.Patterns.PATTERN110: return ((i * j) % 2 + (i * j) % 3) % 2 === 0 + case exports.Patterns.PATTERN111: return ((i * j) % 3 + (i + j) % 2) % 2 === 0 + + default: throw new Error('bad maskPattern:' + maskPattern) + } +} + +/** + * Apply a mask pattern to a BitMatrix + * + * @param {Number} pattern Pattern reference number + * @param {BitMatrix} data BitMatrix data + */ +exports.applyMask = function applyMask (pattern, data) { + const size = data.size + + for (let col = 0; col < size; col++) { + for (let row = 0; row < size; row++) { + if (data.isReserved(row, col)) continue + data.xor(row, col, getMaskAt(pattern, row, col)) } - /** - * Adds an HTML anchor tag to the summary buffer - * - * @param {string} text link text/content - * @param {string} href hyperlink - * - * @returns {Summary} summary instance - */ - addLink(text, href) { - const element = this.wrap('a', text, { href }); - return this.addRaw(element).addEOL(); + } +} + +/** + * Returns the best mask pattern for data + * + * @param {BitMatrix} data + * @return {Number} Mask pattern reference number + */ +exports.getBestMask = function getBestMask (data, setupFormatFunc) { + const numPatterns = Object.keys(exports.Patterns).length + let bestPattern = 0 + let lowerPenalty = Infinity + + for (let p = 0; p < numPatterns; p++) { + setupFormatFunc(p) + exports.applyMask(p, data) + + // Calculate penalty + const penalty = + exports.getPenaltyN1(data) + + exports.getPenaltyN2(data) + + exports.getPenaltyN3(data) + + exports.getPenaltyN4(data) + + // Undo previously applied mask + exports.applyMask(p, data) + + if (penalty < lowerPenalty) { + lowerPenalty = penalty + bestPattern = p } + } + + return bestPattern +} + + +/***/ }), + +/***/ 3913: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +const VersionCheck = __nccwpck_require__(2541) +const Regex = __nccwpck_require__(8411) + +/** + * Numeric mode encodes data from the decimal digit set (0 - 9) + * (byte values 30HEX to 39HEX). + * Normally, 3 data characters are represented by 10 bits. + * + * @type {Object} + */ +exports.NUMERIC = { + id: 'Numeric', + bit: 1 << 0, + ccBits: [10, 12, 14] +} + +/** + * Alphanumeric mode encodes data from a set of 45 characters, + * i.e. 10 numeric digits (0 - 9), + * 26 alphabetic characters (A - Z), + * and 9 symbols (SP, $, %, *, +, -, ., /, :). + * Normally, two input characters are represented by 11 bits. + * + * @type {Object} + */ +exports.ALPHANUMERIC = { + id: 'Alphanumeric', + bit: 1 << 1, + ccBits: [9, 11, 13] +} + +/** + * In byte mode, data is encoded at 8 bits per character. + * + * @type {Object} + */ +exports.BYTE = { + id: 'Byte', + bit: 1 << 2, + ccBits: [8, 16, 16] +} + +/** + * The Kanji mode efficiently encodes Kanji characters in accordance with + * the Shift JIS system based on JIS X 0208. + * The Shift JIS values are shifted from the JIS X 0208 values. + * JIS X 0208 gives details of the shift coded representation. + * Each two-byte character value is compacted to a 13-bit binary codeword. + * + * @type {Object} + */ +exports.KANJI = { + id: 'Kanji', + bit: 1 << 3, + ccBits: [8, 10, 12] +} + +/** + * Mixed mode will contain a sequences of data in a combination of any of + * the modes described above + * + * @type {Object} + */ +exports.MIXED = { + bit: -1 } -const _summary = new Summary(); + /** - * @deprecated use `core.summary` + * Returns the number of bits needed to store the data length + * according to QR Code specifications. + * + * @param {Mode} mode Data mode + * @param {Number} version QR Code version + * @return {Number} Number of bits */ -exports.markdownSummary = _summary; -exports.summary = _summary; -//# sourceMappingURL=summary.js.map - -/***/ }), - -/***/ 667: -/***/ (function(module, __unusedexports, __webpack_require__) { +exports.getCharCountIndicator = function getCharCountIndicator (mode, version) { + if (!mode.ccBits) throw new Error('Invalid mode: ' + mode) -"use strict"; + if (!VersionCheck.isValid(version)) { + throw new Error('Invalid version: ' + version) + } + if (version >= 1 && version < 10) return mode.ccBits[0] + else if (version < 27) return mode.ccBits[1] + return mode.ccBits[2] +} -var constants = __webpack_require__(268); +/** + * Returns the most efficient mode to store the specified data + * + * @param {String} dataStr Input data string + * @return {Mode} Best mode + */ +exports.getBestModeForData = function getBestModeForData (dataStr) { + if (Regex.testNumeric(dataStr)) return exports.NUMERIC + else if (Regex.testAlphanumeric(dataStr)) return exports.ALPHANUMERIC + else if (Regex.testKanji(dataStr)) return exports.KANJI + else return exports.BYTE +} -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; - } - } +/** + * Return mode name as string + * + * @param {Mode} mode Mode object + * @returns {String} Mode name + */ +exports.toString = function toString (mode) { + if (mode && mode.id) return mode.id + throw new Error('Invalid mode') +} - // map to a UInt16 array if data is 16bit, fix endianness below - var data = options.bitDepth !== 16 ? dataIn : new Uint16Array(dataIn.buffer); +/** + * Check if input param is a valid mode object + * + * @param {Mode} mode Mode object + * @returns {Boolean} True if valid mode, false otherwise + */ +exports.isValid = function isValid (mode) { + return mode && mode.bit && mode.ccBits +} - 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; +/** + * Get mode object from its name + * + * @param {String} string Mode name + * @returns {Mode} Mode object + */ +function fromString (string) { + if (typeof string !== 'string') { + throw new Error('Param is not a string') } - var outData = new Buffer(width * height * outBpp); - var inIndex = 0; - var outIndex = 0; + const lcStr = string.toLowerCase() - 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; + switch (lcStr) { + case 'numeric': + return exports.NUMERIC + case 'alphanumeric': + return exports.ALPHANUMERIC + case 'kanji': + return exports.KANJI + case 'byte': + return exports.BYTE + default: + throw new Error('Unknown mode: ' + string) } +} - 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 }; +/** + * Returns mode from a value. + * If value is not a valid mode, returns defaultValue + * + * @param {Mode|String} value Encoding mode + * @param {Mode} defaultValue Fallback value + * @return {Mode} Encoding mode + */ +exports.from = function from (value, defaultValue) { + if (exports.isValid(value)) { + return value } - 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; - } + try { + return fromString(value) + } catch (e) { + return defaultValue } +} - return outData; -}; - - -/***/ }), - -/***/ 669: -/***/ (function(module) { - -module.exports = require("util"); /***/ }), -/***/ 673: -/***/ (function(__unusedmodule, exports, __webpack_require__) { +/***/ 6376: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var Utils = __webpack_require__(621) +const Mode = __nccwpck_require__(3913) -function getColorAttrib (color, attrib) { - var alpha = color.a / 255 - var str = attrib + '="' + color.hex + '"' - - return alpha < 1 - ? str + ' ' + attrib + '-opacity="' + alpha.toFixed(2).slice(1) + '"' - : str +function NumericData (data) { + this.mode = Mode.NUMERIC + this.data = data.toString() } -function svgCmd (cmd, x, y) { - var str = cmd + x - if (typeof y !== 'undefined') str += ' ' + y - - return str +NumericData.getBitsLength = function getBitsLength (length) { + return 10 * Math.floor(length / 3) + ((length % 3) ? ((length % 3) * 3 + 1) : 0) } -function qrToPath (data, size, margin) { - var path = '' - var moveBy = 0 - var newRow = false - var lineLength = 0 - - for (var i = 0; i < data.length; i++) { - var col = Math.floor(i % size) - var row = Math.floor(i / size) - - if (!col && !newRow) newRow = true +NumericData.prototype.getLength = function getLength () { + return this.data.length +} - if (data[i]) { - lineLength++ +NumericData.prototype.getBitsLength = function getBitsLength () { + return NumericData.getBitsLength(this.data.length) +} - if (!(i > 0 && col > 0 && data[i - 1])) { - path += newRow - ? svgCmd('M', col + margin, 0.5 + row + margin) - : svgCmd('m', moveBy, 0) +NumericData.prototype.write = function write (bitBuffer) { + let i, group, value - moveBy = 0 - newRow = false - } + // The input data string is divided into groups of three digits, + // and each group is converted to its 10-bit binary equivalent. + for (i = 0; i + 3 <= this.data.length; i += 3) { + group = this.data.substr(i, 3) + value = parseInt(group, 10) - if (!(col + 1 < size && data[i + 1])) { - path += svgCmd('h', lineLength) - lineLength = 0 - } - } else { - moveBy++ - } + bitBuffer.put(value, 10) } - return path + // If the number of input digits is not an exact multiple of three, + // the final one or two digits are converted to 4 or 7 bits respectively. + const remainingNum = this.data.length - i + if (remainingNum > 0) { + group = this.data.substr(i) + value = parseInt(group, 10) + + bitBuffer.put(value, remainingNum * 3 + 1) + } } -exports.render = function render (qrData, options, cb) { - var opts = Utils.getOptions(options) - var size = qrData.modules.size - var data = qrData.modules.data - var qrcodesize = size + opts.margin * 2 +module.exports = NumericData - var bg = !opts.color.light.a - ? '' - : '' - var path = - '' +/***/ }), - var viewBox = 'viewBox="' + '0 0 ' + qrcodesize + ' ' + qrcodesize + '"' +/***/ 3292: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - var width = !opts.width ? '' : 'width="' + opts.width + '" height="' + opts.width + '" ' +const GF = __nccwpck_require__(234) - var svgTag = '' + bg + path + '\n' +/** + * Multiplies two polynomials inside Galois Field + * + * @param {Uint8Array} p1 Polynomial + * @param {Uint8Array} p2 Polynomial + * @return {Uint8Array} Product of p1 and p2 + */ +exports.mul = function mul (p1, p2) { + const coeff = new Uint8Array(p1.length + p2.length - 1) - if (typeof cb === 'function') { - cb(null, svgTag) + for (let i = 0; i < p1.length; i++) { + for (let j = 0; j < p2.length; j++) { + coeff[i + j] ^= GF.mul(p1[i], p2[j]) + } } - return svgTag + return coeff } +/** + * Calculate the remainder of polynomials division + * + * @param {Uint8Array} divident Polynomial + * @param {Uint8Array} divisor Polynomial + * @return {Uint8Array} Remainder + */ +exports.mod = function mod (divident, divisor) { + let result = new Uint8Array(divident) -/***/ }), + while ((result.length - divisor.length) >= 0) { + const coeff = result[0] -/***/ 675: -/***/ (function(__unusedmodule, exports, __webpack_require__) { + for (let i = 0; i < divisor.length; i++) { + result[i] ^= GF.mul(divisor[i], coeff) + } -var Utils = __webpack_require__(114) + // remove all zeros from buffer head + let offset = 0 + while (offset < result.length && result[offset] === 0) offset++ + result = result.slice(offset) + } -var G15 = (1 << 10) | (1 << 8) | (1 << 5) | (1 << 4) | (1 << 2) | (1 << 1) | (1 << 0) -var G15_MASK = (1 << 14) | (1 << 12) | (1 << 10) | (1 << 4) | (1 << 1) -var G15_BCH = Utils.getBCHDigit(G15) + return result +} /** - * Returns format information with relative error correction bits - * - * The format information is a 15-bit sequence containing 5 data bits, - * with 10 error correction bits calculated using the (15, 5) BCH code. + * Generate an irreducible generator polynomial of specified degree + * (used by Reed-Solomon encoder) * - * @param {Number} errorCorrectionLevel Error correction level - * @param {Number} mask Mask pattern - * @return {Number} Encoded format information bits + * @param {Number} degree Degree of the generator polynomial + * @return {Uint8Array} Buffer containing polynomial coefficients */ -exports.getEncodedBits = function getEncodedBits (errorCorrectionLevel, mask) { - var data = ((errorCorrectionLevel.bit << 3) | mask) - var d = data << 10 - - while (Utils.getBCHDigit(d) - G15_BCH >= 0) { - d ^= (G15 << (Utils.getBCHDigit(d) - G15_BCH)) +exports.generateECPolynomial = function generateECPolynomial (degree) { + let poly = new Uint8Array([1]) + for (let i = 0; i < degree; i++) { + poly = exports.mul(poly, new Uint8Array([1, GF.exp(i)])) } - // xor final data with mask pattern in order to ensure that - // no combination of Error Correction Level and data mask pattern - // will result in an all-zero data string - return ((data << 10) | d) ^ G15_MASK + return poly } /***/ }), -/***/ 702: -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -var BufferUtil = __webpack_require__(628) -var Utils = __webpack_require__(114) -var ECLevel = __webpack_require__(50) -var BitBuffer = __webpack_require__(765) -var BitMatrix = __webpack_require__(287) -var AlignmentPattern = __webpack_require__(254) -var FinderPattern = __webpack_require__(227) -var MaskPattern = __webpack_require__(741) -var ECCode = __webpack_require__(189) -var ReedSolomonEncoder = __webpack_require__(185) -var Version = __webpack_require__(424) -var FormatInfo = __webpack_require__(675) -var Mode = __webpack_require__(364) -var Segments = __webpack_require__(777) -var isArray = __webpack_require__(714) +/***/ 4024: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +const Utils = __nccwpck_require__(8317) +const ECLevel = __nccwpck_require__(3644) +const BitBuffer = __nccwpck_require__(9618) +const BitMatrix = __nccwpck_require__(5281) +const AlignmentPattern = __nccwpck_require__(7290) +const FinderPattern = __nccwpck_require__(8129) +const MaskPattern = __nccwpck_require__(1597) +const ECCode = __nccwpck_require__(3185) +const ReedSolomonEncoder = __nccwpck_require__(9245) +const Version = __nccwpck_require__(7272) +const FormatInfo = __nccwpck_require__(7570) +const Mode = __nccwpck_require__(3913) +const Segments = __nccwpck_require__(3072) /** * QRCode for JavaScript @@ -6878,17 +7355,17 @@ var isArray = __webpack_require__(714) * @param {Number} version QR Code version */ function setupFinderPattern (matrix, version) { - var size = matrix.size - var pos = FinderPattern.getPositions(version) + const size = matrix.size + const pos = FinderPattern.getPositions(version) - for (var i = 0; i < pos.length; i++) { - var row = pos[i][0] - var col = pos[i][1] + for (let i = 0; i < pos.length; i++) { + const row = pos[i][0] + const col = pos[i][1] - for (var r = -1; r <= 7; r++) { + for (let r = -1; r <= 7; r++) { if (row + r <= -1 || size <= row + r) continue - for (var c = -1; c <= 7; c++) { + for (let c = -1; c <= 7; c++) { if (col + c <= -1 || size <= col + c) continue if ((r >= 0 && r <= 6 && (c === 0 || c === 6)) || @@ -6911,10 +7388,10 @@ function setupFinderPattern (matrix, version) { * @param {BitMatrix} matrix Modules matrix */ function setupTimingPattern (matrix) { - var size = matrix.size + const size = matrix.size - for (var r = 8; r < size - 8; r++) { - var value = r % 2 === 0 + for (let r = 8; r < size - 8; r++) { + const value = r % 2 === 0 matrix.set(r, 6, value, true) matrix.set(6, r, value, true) } @@ -6929,14 +7406,14 @@ function setupTimingPattern (matrix) { * @param {Number} version QR Code version */ function setupAlignmentPattern (matrix, version) { - var pos = AlignmentPattern.getPositions(version) + const pos = AlignmentPattern.getPositions(version) - for (var i = 0; i < pos.length; i++) { - var row = pos[i][0] - var col = pos[i][1] + for (let i = 0; i < pos.length; i++) { + const row = pos[i][0] + const col = pos[i][1] - for (var r = -2; r <= 2; r++) { - for (var c = -2; c <= 2; c++) { + for (let r = -2; r <= 2; r++) { + for (let c = -2; c <= 2; c++) { if (r === -2 || r === 2 || c === -2 || c === 2 || (r === 0 && c === 0)) { matrix.set(row + r, col + c, true, true) @@ -6955,11 +7432,11 @@ function setupAlignmentPattern (matrix, version) { * @param {Number} version QR Code version */ function setupVersionInfo (matrix, version) { - var size = matrix.size - var bits = Version.getEncodedBits(version) - var row, col, mod + const size = matrix.size + const bits = Version.getEncodedBits(version) + let row, col, mod - for (var i = 0; i < 18; i++) { + for (let i = 0; i < 18; i++) { row = Math.floor(i / 3) col = i % 3 + size - 8 - 3 mod = ((bits >> i) & 1) === 1 @@ -6977,9 +7454,9 @@ function setupVersionInfo (matrix, version) { * @param {Number} maskPattern Mask pattern reference value */ function setupFormatInfo (matrix, errorCorrectionLevel, maskPattern) { - var size = matrix.size - var bits = FormatInfo.getEncodedBits(errorCorrectionLevel, maskPattern) - var i, mod + const size = matrix.size + const bits = FormatInfo.getEncodedBits(errorCorrectionLevel, maskPattern) + let i, mod for (i = 0; i < 15; i++) { mod = ((bits >> i) & 1) === 1 @@ -7010,23 +7487,23 @@ function setupFormatInfo (matrix, errorCorrectionLevel, maskPattern) { /** * Add encoded data bits to matrix * - * @param {BitMatrix} matrix Modules matrix - * @param {Buffer} data Data codewords + * @param {BitMatrix} matrix Modules matrix + * @param {Uint8Array} data Data codewords */ function setupData (matrix, data) { - var size = matrix.size - var inc = -1 - var row = size - 1 - var bitIndex = 7 - var byteIndex = 0 + const size = matrix.size + let inc = -1 + let row = size - 1 + let bitIndex = 7 + let byteIndex = 0 - for (var col = size - 1; col > 0; col -= 2) { + for (let col = size - 1; col > 0; col -= 2) { if (col === 6) col-- while (true) { - for (var c = 0; c < 2; c++) { + for (let c = 0; c < 2; c++) { if (!matrix.isReserved(row, col - c)) { - var dark = false + let dark = false if (byteIndex < data.length) { dark = (((data[byteIndex] >>> bitIndex) & 1) === 1) @@ -7059,11 +7536,11 @@ function setupData (matrix, data) { * @param {Number} version QR Code version * @param {ErrorCorrectionLevel} errorCorrectionLevel Error correction level * @param {ByteData} data Data input - * @return {Buffer} Buffer containing encoded codewords + * @return {Uint8Array} Buffer containing encoded codewords */ function createData (version, errorCorrectionLevel, segments) { // Prepare data buffer - var buffer = new BitBuffer() + const buffer = new BitBuffer() segments.forEach(function (data) { // prefix data with mode indicator (4 bits) @@ -7083,9 +7560,9 @@ function createData (version, errorCorrectionLevel, segments) { }) // Calculate required number of bits - var totalCodewords = Utils.getSymbolTotalCodewords(version) - var ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel) - var dataTotalCodewordsBits = (totalCodewords - ecTotalCodewords) * 8 + const totalCodewords = Utils.getSymbolTotalCodewords(version) + const ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel) + const dataTotalCodewordsBits = (totalCodewords - ecTotalCodewords) * 8 // Add a terminator. // If the bit string is shorter than the total number of required bits, @@ -7109,8 +7586,8 @@ function createData (version, errorCorrectionLevel, segments) { // Extend the buffer to fill the data capacity of the symbol corresponding to // the Version and Error Correction Level by adding the Pad Codewords 11101100 (0xEC) // and 00010001 (0x11) alternately. - var remainingByte = (dataTotalCodewordsBits - buffer.getLengthInBits()) / 8 - for (var i = 0; i < remainingByte; i++) { + const remainingByte = (dataTotalCodewordsBits - buffer.getLengthInBits()) / 8 + for (let i = 0; i < remainingByte; i++) { buffer.put(i % 2 ? 0x11 : 0xEC, 8) } @@ -7118,1435 +7595,1557 @@ function createData (version, errorCorrectionLevel, segments) { } /** - * Encode input data with Reed-Solomon and return codewords with - * relative error correction bits + * Encode input data with Reed-Solomon and return codewords with + * relative error correction bits + * + * @param {BitBuffer} bitBuffer Data to encode + * @param {Number} version QR Code version + * @param {ErrorCorrectionLevel} errorCorrectionLevel Error correction level + * @return {Uint8Array} Buffer containing encoded codewords + */ +function createCodewords (bitBuffer, version, errorCorrectionLevel) { + // Total codewords for this QR code version (Data + Error correction) + const totalCodewords = Utils.getSymbolTotalCodewords(version) + + // Total number of error correction codewords + const ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel) + + // Total number of data codewords + const dataTotalCodewords = totalCodewords - ecTotalCodewords + + // Total number of blocks + const ecTotalBlocks = ECCode.getBlocksCount(version, errorCorrectionLevel) + + // Calculate how many blocks each group should contain + const blocksInGroup2 = totalCodewords % ecTotalBlocks + const blocksInGroup1 = ecTotalBlocks - blocksInGroup2 + + const totalCodewordsInGroup1 = Math.floor(totalCodewords / ecTotalBlocks) + + const dataCodewordsInGroup1 = Math.floor(dataTotalCodewords / ecTotalBlocks) + const dataCodewordsInGroup2 = dataCodewordsInGroup1 + 1 + + // Number of EC codewords is the same for both groups + const ecCount = totalCodewordsInGroup1 - dataCodewordsInGroup1 + + // Initialize a Reed-Solomon encoder with a generator polynomial of degree ecCount + const rs = new ReedSolomonEncoder(ecCount) + + let offset = 0 + const dcData = new Array(ecTotalBlocks) + const ecData = new Array(ecTotalBlocks) + let maxDataSize = 0 + const buffer = new Uint8Array(bitBuffer.buffer) + + // Divide the buffer into the required number of blocks + for (let b = 0; b < ecTotalBlocks; b++) { + const dataSize = b < blocksInGroup1 ? dataCodewordsInGroup1 : dataCodewordsInGroup2 + + // extract a block of data from buffer + dcData[b] = buffer.slice(offset, offset + dataSize) + + // Calculate EC codewords for this data block + ecData[b] = rs.encode(dcData[b]) + + offset += dataSize + maxDataSize = Math.max(maxDataSize, dataSize) + } + + // Create final data + // Interleave the data and error correction codewords from each block + const data = new Uint8Array(totalCodewords) + let index = 0 + let i, r + + // Add data codewords + for (i = 0; i < maxDataSize; i++) { + for (r = 0; r < ecTotalBlocks; r++) { + if (i < dcData[r].length) { + data[index++] = dcData[r][i] + } + } + } + + // Apped EC codewords + for (i = 0; i < ecCount; i++) { + for (r = 0; r < ecTotalBlocks; r++) { + data[index++] = ecData[r][i] + } + } + + return data +} + +/** + * Build QR Code symbol + * + * @param {String} data Input string + * @param {Number} version QR Code version + * @param {ErrorCorretionLevel} errorCorrectionLevel Error level + * @param {MaskPattern} maskPattern Mask pattern + * @return {Object} Object containing symbol data + */ +function createSymbol (data, version, errorCorrectionLevel, maskPattern) { + let segments + + if (Array.isArray(data)) { + segments = Segments.fromArray(data) + } else if (typeof data === 'string') { + let estimatedVersion = version + + if (!estimatedVersion) { + const rawSegments = Segments.rawSplit(data) + + // Estimate best version that can contain raw splitted segments + estimatedVersion = Version.getBestVersionForData(rawSegments, errorCorrectionLevel) + } + + // Build optimized segments + // If estimated version is undefined, try with the highest version + segments = Segments.fromString(data, estimatedVersion || 40) + } else { + throw new Error('Invalid data') + } + + // Get the min version that can contain data + const bestVersion = Version.getBestVersionForData(segments, errorCorrectionLevel) + + // If no version is found, data cannot be stored + if (!bestVersion) { + throw new Error('The amount of data is too big to be stored in a QR Code') + } + + // If not specified, use min version as default + if (!version) { + version = bestVersion + + // Check if the specified version can contain the data + } else if (version < bestVersion) { + throw new Error('\n' + + 'The chosen QR Code version cannot contain this amount of data.\n' + + 'Minimum version required to store current data is: ' + bestVersion + '.\n' + ) + } + + const dataBits = createData(version, errorCorrectionLevel, segments) + + // Allocate matrix buffer + const moduleCount = Utils.getSymbolSize(version) + const modules = new BitMatrix(moduleCount) + + // Add function modules + setupFinderPattern(modules, version) + setupTimingPattern(modules) + setupAlignmentPattern(modules, version) + + // Add temporary dummy bits for format info just to set them as reserved. + // This is needed to prevent these bits from being masked by {@link MaskPattern.applyMask} + // since the masking operation must be performed only on the encoding region. + // These blocks will be replaced with correct values later in code. + setupFormatInfo(modules, errorCorrectionLevel, 0) + + if (version >= 7) { + setupVersionInfo(modules, version) + } + + // Add data codewords + setupData(modules, dataBits) + + if (isNaN(maskPattern)) { + // Find best mask pattern + maskPattern = MaskPattern.getBestMask(modules, + setupFormatInfo.bind(null, modules, errorCorrectionLevel)) + } + + // Apply mask pattern + MaskPattern.applyMask(maskPattern, modules) + + // Replace format info bits with correct values + setupFormatInfo(modules, errorCorrectionLevel, maskPattern) + + return { + modules: modules, + version: version, + errorCorrectionLevel: errorCorrectionLevel, + maskPattern: maskPattern, + segments: segments + } +} + +/** + * QR Code + * + * @param {String | Array} data Input data + * @param {Object} options Optional configurations + * @param {Number} options.version QR Code version + * @param {String} options.errorCorrectionLevel Error correction level + * @param {Function} options.toSJISFunc Helper func to convert utf8 to sjis + */ +exports.create = function create (data, options) { + if (typeof data === 'undefined' || data === '') { + throw new Error('No input text') + } + + let errorCorrectionLevel = ECLevel.M + let version + let mask + + if (typeof options !== 'undefined') { + // Use higher error correction level as default + errorCorrectionLevel = ECLevel.from(options.errorCorrectionLevel, ECLevel.M) + version = Version.from(options.version) + mask = MaskPattern.from(options.maskPattern) + + if (options.toSJISFunc) { + Utils.setToSJISFunction(options.toSJISFunc) + } + } + + return createSymbol(data, version, errorCorrectionLevel, mask) +} + + +/***/ }), + +/***/ 9245: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const Polynomial = __nccwpck_require__(3292) + +function ReedSolomonEncoder (degree) { + this.genPoly = undefined + this.degree = degree + + if (this.degree) this.initialize(this.degree) +} + +/** + * Initialize the encoder. + * The input param should correspond to the number of error correction codewords. + * + * @param {Number} degree + */ +ReedSolomonEncoder.prototype.initialize = function initialize (degree) { + // create an irreducible generator polynomial + this.degree = degree + this.genPoly = Polynomial.generateECPolynomial(this.degree) +} + +/** + * Encodes a chunk of data * - * @param {BitBuffer} bitBuffer Data to encode - * @param {Number} version QR Code version - * @param {ErrorCorrectionLevel} errorCorrectionLevel Error correction level - * @return {Buffer} Buffer containing encoded codewords + * @param {Uint8Array} data Buffer containing input data + * @return {Uint8Array} Buffer containing encoded data */ -function createCodewords (bitBuffer, version, errorCorrectionLevel) { - // Total codewords for this QR code version (Data + Error correction) - var totalCodewords = Utils.getSymbolTotalCodewords(version) +ReedSolomonEncoder.prototype.encode = function encode (data) { + if (!this.genPoly) { + throw new Error('Encoder not initialized') + } - // Total number of error correction codewords - var ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel) + // Calculate EC for this data block + // extends data size to data+genPoly size + const paddedData = new Uint8Array(data.length + this.degree) + paddedData.set(data) - // Total number of data codewords - var dataTotalCodewords = totalCodewords - ecTotalCodewords + // The error correction codewords are the remainder after dividing the data codewords + // by a generator polynomial + const remainder = Polynomial.mod(paddedData, this.genPoly) - // Total number of blocks - var ecTotalBlocks = ECCode.getBlocksCount(version, errorCorrectionLevel) + // return EC data blocks (last n byte, where n is the degree of genPoly) + // If coefficients number in remainder are less than genPoly degree, + // pad with 0s to the left to reach the needed number of coefficients + const start = this.degree - remainder.length + if (start > 0) { + const buff = new Uint8Array(this.degree) + buff.set(remainder, start) - // Calculate how many blocks each group should contain - var blocksInGroup2 = totalCodewords % ecTotalBlocks - var blocksInGroup1 = ecTotalBlocks - blocksInGroup2 + return buff + } - var totalCodewordsInGroup1 = Math.floor(totalCodewords / ecTotalBlocks) + return remainder +} - var dataCodewordsInGroup1 = Math.floor(dataTotalCodewords / ecTotalBlocks) - var dataCodewordsInGroup2 = dataCodewordsInGroup1 + 1 +module.exports = ReedSolomonEncoder - // Number of EC codewords is the same for both groups - var ecCount = totalCodewordsInGroup1 - dataCodewordsInGroup1 - // Initialize a Reed-Solomon encoder with a generator polynomial of degree ecCount - var rs = new ReedSolomonEncoder(ecCount) +/***/ }), - var offset = 0 - var dcData = new Array(ecTotalBlocks) - var ecData = new Array(ecTotalBlocks) - var maxDataSize = 0 - var buffer = BufferUtil.from(bitBuffer.buffer) +/***/ 8411: +/***/ ((__unused_webpack_module, exports) => { - // Divide the buffer into the required number of blocks - for (var b = 0; b < ecTotalBlocks; b++) { - var dataSize = b < blocksInGroup1 ? dataCodewordsInGroup1 : dataCodewordsInGroup2 +const numeric = '[0-9]+' +const alphanumeric = '[A-Z $%*+\\-./:]+' +let kanji = '(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|' + + '[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|' + + '[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|' + + '[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+' +kanji = kanji.replace(/u/g, '\\u') - // extract a block of data from buffer - dcData[b] = buffer.slice(offset, offset + dataSize) +const byte = '(?:(?![A-Z0-9 $%*+\\-./:]|' + kanji + ')(?:.|[\r\n]))+' - // Calculate EC codewords for this data block - ecData[b] = rs.encode(dcData[b]) +exports.KANJI = new RegExp(kanji, 'g') +exports.BYTE_KANJI = new RegExp('[^A-Z0-9 $%*+\\-./:]+', 'g') +exports.BYTE = new RegExp(byte, 'g') +exports.NUMERIC = new RegExp(numeric, 'g') +exports.ALPHANUMERIC = new RegExp(alphanumeric, 'g') - offset += dataSize - maxDataSize = Math.max(maxDataSize, dataSize) - } +const TEST_KANJI = new RegExp('^' + kanji + '$') +const TEST_NUMERIC = new RegExp('^' + numeric + '$') +const TEST_ALPHANUMERIC = new RegExp('^[A-Z0-9 $%*+\\-./:]+$') - // Create final data - // Interleave the data and error correction codewords from each block - var data = BufferUtil.alloc(totalCodewords) - var index = 0 - var i, r +exports.testKanji = function testKanji (str) { + return TEST_KANJI.test(str) +} - // Add data codewords - for (i = 0; i < maxDataSize; i++) { - for (r = 0; r < ecTotalBlocks; r++) { - if (i < dcData[r].length) { - data[index++] = dcData[r][i] - } - } - } +exports.testNumeric = function testNumeric (str) { + return TEST_NUMERIC.test(str) +} - // Apped EC codewords - for (i = 0; i < ecCount; i++) { - for (r = 0; r < ecTotalBlocks; r++) { - data[index++] = ecData[r][i] - } - } +exports.testAlphanumeric = function testAlphanumeric (str) { + return TEST_ALPHANUMERIC.test(str) +} - return data + +/***/ }), + +/***/ 3072: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +const Mode = __nccwpck_require__(3913) +const NumericData = __nccwpck_require__(6376) +const AlphanumericData = __nccwpck_require__(6526) +const ByteData = __nccwpck_require__(7205) +const KanjiData = __nccwpck_require__(7596) +const Regex = __nccwpck_require__(8411) +const Utils = __nccwpck_require__(8317) +const dijkstra = __nccwpck_require__(9351) + +/** + * Returns UTF8 byte length + * + * @param {String} str Input string + * @return {Number} Number of byte + */ +function getStringByteLength (str) { + return unescape(encodeURIComponent(str)).length } /** - * Build QR Code symbol + * Get a list of segments of the specified mode + * from a string * - * @param {String} data Input string - * @param {Number} version QR Code version - * @param {ErrorCorretionLevel} errorCorrectionLevel Error level - * @param {MaskPattern} maskPattern Mask pattern - * @return {Object} Object containing symbol data + * @param {Mode} mode Segment mode + * @param {String} str String to process + * @return {Array} Array of object with segments data */ -function createSymbol (data, version, errorCorrectionLevel, maskPattern) { - var segments +function getSegments (regex, mode, str) { + const segments = [] + let result - if (isArray(data)) { - segments = Segments.fromArray(data) - } else if (typeof data === 'string') { - var estimatedVersion = version + while ((result = regex.exec(str)) !== null) { + segments.push({ + data: result[0], + index: result.index, + mode: mode, + length: result[0].length + }) + } - if (!estimatedVersion) { - var rawSegments = Segments.rawSplit(data) + return segments +} - // Estimate best version that can contain raw splitted segments - estimatedVersion = Version.getBestVersionForData(rawSegments, - errorCorrectionLevel) - } +/** + * Extracts a series of segments with the appropriate + * modes from a string + * + * @param {String} dataStr Input string + * @return {Array} Array of object with segments data + */ +function getSegmentsFromString (dataStr) { + const numSegs = getSegments(Regex.NUMERIC, Mode.NUMERIC, dataStr) + const alphaNumSegs = getSegments(Regex.ALPHANUMERIC, Mode.ALPHANUMERIC, dataStr) + let byteSegs + let kanjiSegs - // Build optimized segments - // If estimated version is undefined, try with the highest version - segments = Segments.fromString(data, estimatedVersion || 40) + if (Utils.isKanjiModeEnabled()) { + byteSegs = getSegments(Regex.BYTE, Mode.BYTE, dataStr) + kanjiSegs = getSegments(Regex.KANJI, Mode.KANJI, dataStr) } else { - throw new Error('Invalid data') + byteSegs = getSegments(Regex.BYTE_KANJI, Mode.BYTE, dataStr) + kanjiSegs = [] } - // Get the min version that can contain data - var bestVersion = Version.getBestVersionForData(segments, - errorCorrectionLevel) - - // If no version is found, data cannot be stored - if (!bestVersion) { - throw new Error('The amount of data is too big to be stored in a QR Code') - } + const segs = numSegs.concat(alphaNumSegs, byteSegs, kanjiSegs) - // If not specified, use min version as default - if (!version) { - version = bestVersion + return segs + .sort(function (s1, s2) { + return s1.index - s2.index + }) + .map(function (obj) { + return { + data: obj.data, + mode: obj.mode, + length: obj.length + } + }) +} - // Check if the specified version can contain the data - } else if (version < bestVersion) { - throw new Error('\n' + - 'The chosen QR Code version cannot contain this amount of data.\n' + - 'Minimum version required to store current data is: ' + bestVersion + '.\n' - ) +/** + * Returns how many bits are needed to encode a string of + * specified length with the specified mode + * + * @param {Number} length String length + * @param {Mode} mode Segment mode + * @return {Number} Bit length + */ +function getSegmentBitsLength (length, mode) { + switch (mode) { + case Mode.NUMERIC: + return NumericData.getBitsLength(length) + case Mode.ALPHANUMERIC: + return AlphanumericData.getBitsLength(length) + case Mode.KANJI: + return KanjiData.getBitsLength(length) + case Mode.BYTE: + return ByteData.getBitsLength(length) } +} - var dataBits = createData(version, errorCorrectionLevel, segments) - - // Allocate matrix buffer - var moduleCount = Utils.getSymbolSize(version) - var modules = new BitMatrix(moduleCount) - - // Add function modules - setupFinderPattern(modules, version) - setupTimingPattern(modules) - setupAlignmentPattern(modules, version) - - // Add temporary dummy bits for format info just to set them as reserved. - // This is needed to prevent these bits from being masked by {@link MaskPattern.applyMask} - // since the masking operation must be performed only on the encoding region. - // These blocks will be replaced with correct values later in code. - setupFormatInfo(modules, errorCorrectionLevel, 0) +/** + * Merges adjacent segments which have the same mode + * + * @param {Array} segs Array of object with segments data + * @return {Array} Array of object with segments data + */ +function mergeSegments (segs) { + return segs.reduce(function (acc, curr) { + const prevSeg = acc.length - 1 >= 0 ? acc[acc.length - 1] : null + if (prevSeg && prevSeg.mode === curr.mode) { + acc[acc.length - 1].data += curr.data + return acc + } - if (version >= 7) { - setupVersionInfo(modules, version) - } + acc.push(curr) + return acc + }, []) +} - // Add data codewords - setupData(modules, dataBits) +/** + * Generates a list of all possible nodes combination which + * will be used to build a segments graph. + * + * Nodes are divided by groups. Each group will contain a list of all the modes + * in which is possible to encode the given text. + * + * For example the text '12345' can be encoded as Numeric, Alphanumeric or Byte. + * The group for '12345' will contain then 3 objects, one for each + * possible encoding mode. + * + * Each node represents a possible segment. + * + * @param {Array} segs Array of object with segments data + * @return {Array} Array of object with segments data + */ +function buildNodes (segs) { + const nodes = [] + for (let i = 0; i < segs.length; i++) { + const seg = segs[i] - if (isNaN(maskPattern)) { - // Find best mask pattern - maskPattern = MaskPattern.getBestMask(modules, - setupFormatInfo.bind(null, modules, errorCorrectionLevel)) + switch (seg.mode) { + case Mode.NUMERIC: + nodes.push([seg, + { data: seg.data, mode: Mode.ALPHANUMERIC, length: seg.length }, + { data: seg.data, mode: Mode.BYTE, length: seg.length } + ]) + break + case Mode.ALPHANUMERIC: + nodes.push([seg, + { data: seg.data, mode: Mode.BYTE, length: seg.length } + ]) + break + case Mode.KANJI: + nodes.push([seg, + { data: seg.data, mode: Mode.BYTE, length: getStringByteLength(seg.data) } + ]) + break + case Mode.BYTE: + nodes.push([ + { data: seg.data, mode: Mode.BYTE, length: getStringByteLength(seg.data) } + ]) + } } - // Apply mask pattern - MaskPattern.applyMask(maskPattern, modules) - - // Replace format info bits with correct values - setupFormatInfo(modules, errorCorrectionLevel, maskPattern) - - return { - modules: modules, - version: version, - errorCorrectionLevel: errorCorrectionLevel, - maskPattern: maskPattern, - segments: segments - } + return nodes } /** - * QR Code + * Builds a graph from a list of nodes. + * All segments in each node group will be connected with all the segments of + * the next group and so on. * - * @param {String | Array} data Input data - * @param {Object} options Optional configurations - * @param {Number} options.version QR Code version - * @param {String} options.errorCorrectionLevel Error correction level - * @param {Function} options.toSJISFunc Helper func to convert utf8 to sjis + * At each connection will be assigned a weight depending on the + * segment's byte length. + * + * @param {Array} nodes Array of object with segments data + * @param {Number} version QR Code version + * @return {Object} Graph of all possible segments */ -exports.create = function create (data, options) { - if (typeof data === 'undefined' || data === '') { - throw new Error('No input text') - } - - var errorCorrectionLevel = ECLevel.M - var version - var mask - - if (typeof options !== 'undefined') { - // Use higher error correction level as default - errorCorrectionLevel = ECLevel.from(options.errorCorrectionLevel, ECLevel.M) - version = Version.from(options.version) - mask = MaskPattern.from(options.maskPattern) - - if (options.toSJISFunc) { - Utils.setToSJISFunction(options.toSJISFunc) - } - } - - return createSymbol(data, version, errorCorrectionLevel, mask) -} +function buildGraph (nodes, version) { + const table = {} + const graph = { start: {} } + let prevNodeIds = ['start'] + for (let i = 0; i < nodes.length; i++) { + const nodeGroup = nodes[i] + const currentNodeIds = [] -/***/ }), + for (let j = 0; j < nodeGroup.length; j++) { + const node = nodeGroup[j] + const key = '' + i + j -/***/ 714: -/***/ (function(module) { + currentNodeIds.push(key) + table[key] = { node: node, lastCount: 0 } + graph[key] = {} -var toString = {}.toString; + for (let n = 0; n < prevNodeIds.length; n++) { + const prevNodeId = prevNodeIds[n] -module.exports = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; -}; + if (table[prevNodeId] && table[prevNodeId].node.mode === node.mode) { + graph[prevNodeId][key] = + getSegmentBitsLength(table[prevNodeId].lastCount + node.length, node.mode) - + getSegmentBitsLength(table[prevNodeId].lastCount, node.mode) + table[prevNodeId].lastCount += node.length + } else { + if (table[prevNodeId]) table[prevNodeId].lastCount = node.length -/***/ }), + graph[prevNodeId][key] = getSegmentBitsLength(node.length, node.mode) + + 4 + Mode.getCharCountIndicator(node.mode, version) // switch cost + } + } + } -/***/ 724: -/***/ (function(__unusedmodule, exports) { + prevNodeIds = currentNodeIds + } -"use strict"; + for (let n = 0; n < prevNodeIds.length; n++) { + graph[prevNodeIds[n]].end = 0 + } + return { map: graph, table: table } +} -// 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 +/** + * Builds a segment from a specified data and mode. + * If a mode is not specified, the more suitable will be used. + * + * @param {String} data Input data + * @param {Mode | String} modesHint Data mode + * @return {Segment} Segment + */ +function buildSingleSegment (data, modesHint) { + let mode + const bestMode = Mode.getBestModeForData(data) + mode = Mode.from(modesHint, bestMode) -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] + // Make sure data can be encoded + if (mode !== Mode.BYTE && mode.bit < bestMode.bit) { + throw new Error('"' + data + '"' + + ' cannot be encoded with mode ' + Mode.toString(mode) + + '.\n Suggested mode is: ' + Mode.toString(bestMode)) } -]; -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 }); - } + // Use Mode.BYTE if Kanji support is disabled + if (mode === Mode.KANJI && !Utils.isKanjiModeEnabled()) { + mode = Mode.BYTE } - 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); - }; -}; + switch (mode) { + case Mode.NUMERIC: + return new NumericData(data) -/***/ }), + case Mode.ALPHANUMERIC: + return new AlphanumericData(data) -/***/ 741: -/***/ (function(__unusedmodule, exports) { + case Mode.KANJI: + return new KanjiData(data) -/** - * Data mask pattern reference - * @type {Object} - */ -exports.Patterns = { - PATTERN000: 0, - PATTERN001: 1, - PATTERN010: 2, - PATTERN011: 3, - PATTERN100: 4, - PATTERN101: 5, - PATTERN110: 6, - PATTERN111: 7 + case Mode.BYTE: + return new ByteData(data) + } } /** - * Weighted penalty scores for the undesirable features - * @type {Object} + * Builds a list of segments from an array. + * Array can contain Strings or Objects with segment's info. + * + * For each item which is a string, will be generated a segment with the given + * string and the more appropriate encoding mode. + * + * For each item which is an object, will be generated a segment with the given + * data and mode. + * Objects must contain at least the property "data". + * If property "mode" is not present, the more suitable mode will be used. + * + * @param {Array} array Array of objects with segments data + * @return {Array} Array of Segments */ -var PenaltyScores = { - N1: 3, - N2: 3, - N3: 40, - N4: 10 +exports.fromArray = function fromArray (array) { + return array.reduce(function (acc, seg) { + if (typeof seg === 'string') { + acc.push(buildSingleSegment(seg, null)) + } else if (seg.data) { + acc.push(buildSingleSegment(seg.data, seg.mode)) + } + + return acc + }, []) } /** - * Check if mask pattern value is valid + * Builds an optimized sequence of segments from a string, + * which will produce the shortest possible bitstream. * - * @param {Number} mask Mask pattern - * @return {Boolean} true if valid, false otherwise + * @param {String} data Input string + * @param {Number} version QR Code version + * @return {Array} Array of segments */ -exports.isValid = function isValid (mask) { - return mask != null && mask !== '' && !isNaN(mask) && mask >= 0 && mask <= 7 +exports.fromString = function fromString (data, version) { + const segs = getSegmentsFromString(data, Utils.isKanjiModeEnabled()) + + const nodes = buildNodes(segs) + const graph = buildGraph(nodes, version) + const path = dijkstra.find_path(graph.map, 'start', 'end') + + const optimizedSegs = [] + for (let i = 1; i < path.length - 1; i++) { + optimizedSegs.push(graph.table[path[i]].node) + } + + return exports.fromArray(mergeSegments(optimizedSegs)) } /** - * Returns mask pattern from a value. - * If value is not valid, returns undefined + * Splits a string in various segments with the modes which + * best represent their content. + * The produced segments are far from being optimized. + * The output of this function is only used to estimate a QR Code version + * which may contain the data. * - * @param {Number|String} value Mask pattern value - * @return {Number} Valid mask pattern or undefined + * @param {string} data Input string + * @return {Array} Array of segments */ -exports.from = function from (value) { - return exports.isValid(value) ? parseInt(value, 10) : undefined +exports.rawSplit = function rawSplit (data) { + return exports.fromArray( + getSegmentsFromString(data, Utils.isKanjiModeEnabled()) + ) } -/** -* Find adjacent modules in row/column with the same color -* and assign a penalty value. -* -* Points: N1 + i -* i is the amount by which the number of adjacent modules of the same color exceeds 5 -*/ -exports.getPenaltyN1 = function getPenaltyN1 (data) { - var size = data.size - var points = 0 - var sameCountCol = 0 - var sameCountRow = 0 - var lastCol = null - var lastRow = null - - for (var row = 0; row < size; row++) { - sameCountCol = sameCountRow = 0 - lastCol = lastRow = null - for (var col = 0; col < size; col++) { - var module = data.get(row, col) - if (module === lastCol) { - sameCountCol++ - } else { - if (sameCountCol >= 5) points += PenaltyScores.N1 + (sameCountCol - 5) - lastCol = module - sameCountCol = 1 - } +/***/ }), - module = data.get(col, row) - if (module === lastRow) { - sameCountRow++ - } else { - if (sameCountRow >= 5) points += PenaltyScores.N1 + (sameCountRow - 5) - lastRow = module - sameCountRow = 1 - } - } +/***/ 8317: +/***/ ((__unused_webpack_module, exports) => { + +let toSJISFunction +const CODEWORDS_COUNT = [ + 0, // Not used + 26, 44, 70, 100, 134, 172, 196, 242, 292, 346, + 404, 466, 532, 581, 655, 733, 815, 901, 991, 1085, + 1156, 1258, 1364, 1474, 1588, 1706, 1828, 1921, 2051, 2185, + 2323, 2465, 2611, 2761, 2876, 3034, 3196, 3362, 3532, 3706 +] - if (sameCountCol >= 5) points += PenaltyScores.N1 + (sameCountCol - 5) - if (sameCountRow >= 5) points += PenaltyScores.N1 + (sameCountRow - 5) - } +/** + * Returns the QR Code size for the specified version + * + * @param {Number} version QR Code version + * @return {Number} size of QR code + */ +exports.getSymbolSize = function getSymbolSize (version) { + if (!version) throw new Error('"version" cannot be null or undefined') + if (version < 1 || version > 40) throw new Error('"version" should be in range from 1 to 40') + return version * 4 + 17 +} - return points +/** + * Returns the total number of codewords used to store data and EC information. + * + * @param {Number} version QR Code version + * @return {Number} Data length in bits + */ +exports.getSymbolTotalCodewords = function getSymbolTotalCodewords (version) { + return CODEWORDS_COUNT[version] } /** - * Find 2x2 blocks with the same color and assign a penalty value + * Encode data with Bose-Chaudhuri-Hocquenghem * - * Points: N2 * (m - 1) * (n - 1) + * @param {Number} data Value to encode + * @return {Number} Encoded value */ -exports.getPenaltyN2 = function getPenaltyN2 (data) { - var size = data.size - var points = 0 +exports.getBCHDigit = function (data) { + let digit = 0 - for (var row = 0; row < size - 1; row++) { - for (var col = 0; col < size - 1; col++) { - var last = data.get(row, col) + - data.get(row, col + 1) + - data.get(row + 1, col) + - data.get(row + 1, col + 1) + while (data !== 0) { + digit++ + data >>>= 1 + } - if (last === 4 || last === 0) points++ - } + return digit +} + +exports.setToSJISFunction = function setToSJISFunction (f) { + if (typeof f !== 'function') { + throw new Error('"toSJISFunc" is not a valid function.') } - return points * PenaltyScores.N2 + toSJISFunction = f +} + +exports.isKanjiModeEnabled = function () { + return typeof toSJISFunction !== 'undefined' +} + +exports.toSJIS = function toSJIS (kanji) { + return toSJISFunction(kanji) } + +/***/ }), + +/***/ 2541: +/***/ ((__unused_webpack_module, exports) => { + /** - * Find 1:1:3:1:1 ratio (dark:light:dark:light:dark) pattern in row/column, - * preceded or followed by light area 4 modules wide + * Check if QR Code version is valid * - * Points: N3 * number of pattern found + * @param {Number} version QR Code version + * @return {Boolean} true if valid version, false otherwise */ -exports.getPenaltyN3 = function getPenaltyN3 (data) { - var size = data.size - var points = 0 - var bitsCol = 0 - var bitsRow = 0 +exports.isValid = function isValid (version) { + return !isNaN(version) && version >= 1 && version <= 40 +} - for (var row = 0; row < size; row++) { - bitsCol = bitsRow = 0 - for (var col = 0; col < size; col++) { - bitsCol = ((bitsCol << 1) & 0x7FF) | data.get(row, col) - if (col >= 10 && (bitsCol === 0x5D0 || bitsCol === 0x05D)) points++ - bitsRow = ((bitsRow << 1) & 0x7FF) | data.get(col, row) - if (col >= 10 && (bitsRow === 0x5D0 || bitsRow === 0x05D)) points++ +/***/ }), + +/***/ 7272: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +const Utils = __nccwpck_require__(8317) +const ECCode = __nccwpck_require__(3185) +const ECLevel = __nccwpck_require__(3644) +const Mode = __nccwpck_require__(3913) +const VersionCheck = __nccwpck_require__(2541) + +// Generator polynomial used to encode version information +const G18 = (1 << 12) | (1 << 11) | (1 << 10) | (1 << 9) | (1 << 8) | (1 << 5) | (1 << 2) | (1 << 0) +const G18_BCH = Utils.getBCHDigit(G18) + +function getBestVersionForDataLength (mode, length, errorCorrectionLevel) { + for (let currentVersion = 1; currentVersion <= 40; currentVersion++) { + if (length <= exports.getCapacity(currentVersion, errorCorrectionLevel, mode)) { + return currentVersion } } - return points * PenaltyScores.N3 + return undefined } -/** - * Calculate proportion of dark modules in entire symbol - * - * Points: N4 * k - * - * k is the rating of the deviation of the proportion of dark modules - * in the symbol from 50% in steps of 5% - */ -exports.getPenaltyN4 = function getPenaltyN4 (data) { - var darkCount = 0 - var modulesCount = data.data.length +function getReservedBitsCount (mode, version) { + // Character count indicator + mode indicator bits + return Mode.getCharCountIndicator(mode, version) + 4 +} - for (var i = 0; i < modulesCount; i++) darkCount += data.data[i] +function getTotalBitsFromDataArray (segments, version) { + let totalBits = 0 - var k = Math.abs(Math.ceil((darkCount * 100 / modulesCount) / 5) - 10) + segments.forEach(function (data) { + const reservedBits = getReservedBitsCount(data.mode, version) + totalBits += reservedBits + data.getBitsLength() + }) - return k * PenaltyScores.N4 + return totalBits } -/** - * Return mask value at given position - * - * @param {Number} maskPattern Pattern reference value - * @param {Number} i Row - * @param {Number} j Column - * @return {Boolean} Mask value - */ -function getMaskAt (maskPattern, i, j) { - switch (maskPattern) { - case exports.Patterns.PATTERN000: return (i + j) % 2 === 0 - case exports.Patterns.PATTERN001: return i % 2 === 0 - case exports.Patterns.PATTERN010: return j % 3 === 0 - case exports.Patterns.PATTERN011: return (i + j) % 3 === 0 - case exports.Patterns.PATTERN100: return (Math.floor(i / 2) + Math.floor(j / 3)) % 2 === 0 - case exports.Patterns.PATTERN101: return (i * j) % 2 + (i * j) % 3 === 0 - case exports.Patterns.PATTERN110: return ((i * j) % 2 + (i * j) % 3) % 2 === 0 - case exports.Patterns.PATTERN111: return ((i * j) % 3 + (i + j) % 2) % 2 === 0 - - default: throw new Error('bad maskPattern:' + maskPattern) +function getBestVersionForMixedData (segments, errorCorrectionLevel) { + for (let currentVersion = 1; currentVersion <= 40; currentVersion++) { + const length = getTotalBitsFromDataArray(segments, currentVersion) + if (length <= exports.getCapacity(currentVersion, errorCorrectionLevel, Mode.MIXED)) { + return currentVersion + } } + + return undefined } /** - * Apply a mask pattern to a BitMatrix + * Returns version number from a value. + * If value is not a valid version, returns defaultValue * - * @param {Number} pattern Pattern reference number - * @param {BitMatrix} data BitMatrix data + * @param {Number|String} value QR Code version + * @param {Number} defaultValue Fallback value + * @return {Number} QR Code version number */ -exports.applyMask = function applyMask (pattern, data) { - var size = data.size - - for (var col = 0; col < size; col++) { - for (var row = 0; row < size; row++) { - if (data.isReserved(row, col)) continue - data.xor(row, col, getMaskAt(pattern, row, col)) - } +exports.from = function from (value, defaultValue) { + if (VersionCheck.isValid(value)) { + return parseInt(value, 10) } + + return defaultValue } /** - * Returns the best mask pattern for data + * Returns how much data can be stored with the specified QR code version + * and error correction level * - * @param {BitMatrix} data - * @return {Number} Mask pattern reference number + * @param {Number} version QR Code version (1-40) + * @param {Number} errorCorrectionLevel Error correction level + * @param {Mode} mode Data mode + * @return {Number} Quantity of storable data */ -exports.getBestMask = function getBestMask (data, setupFormatFunc) { - var numPatterns = Object.keys(exports.Patterns).length - var bestPattern = 0 - var lowerPenalty = Infinity +exports.getCapacity = function getCapacity (version, errorCorrectionLevel, mode) { + if (!VersionCheck.isValid(version)) { + throw new Error('Invalid QR Code version') + } - for (var p = 0; p < numPatterns; p++) { - setupFormatFunc(p) - exports.applyMask(p, data) + // Use Byte mode as default + if (typeof mode === 'undefined') mode = Mode.BYTE - // Calculate penalty - var penalty = - exports.getPenaltyN1(data) + - exports.getPenaltyN2(data) + - exports.getPenaltyN3(data) + - exports.getPenaltyN4(data) + // Total codewords for this QR code version (Data + Error correction) + const totalCodewords = Utils.getSymbolTotalCodewords(version) - // Undo previously applied mask - exports.applyMask(p, data) + // Total number of error correction codewords + const ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel) - if (penalty < lowerPenalty) { - lowerPenalty = penalty - bestPattern = p - } - } + // Total number of data codewords + const dataTotalCodewordsBits = (totalCodewords - ecTotalCodewords) * 8 - return bestPattern -} + if (mode === Mode.MIXED) return dataTotalCodewordsBits + const usableBits = dataTotalCodewordsBits - getReservedBitsCount(mode, version) -/***/ }), + // Return max number of storable codewords + switch (mode) { + case Mode.NUMERIC: + return Math.floor((usableBits / 10) * 3) + + case Mode.ALPHANUMERIC: + return Math.floor((usableBits / 11) * 2) -/***/ 742: -/***/ (function(__unusedmodule, exports, __webpack_require__) { + case Mode.KANJI: + return Math.floor(usableBits / 13) -"use strict"; + case Mode.BYTE: + default: + return Math.floor(usableBits / 8) + } +} -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.OidcClient = void 0; -const http_client_1 = __webpack_require__(425); -const auth_1 = __webpack_require__(554); -const core_1 = __webpack_require__(470); -class OidcClient { - static createHttpClient(allowRetry = true, maxRetry = 10) { - const requestOptions = { - allowRetries: allowRetry, - maxRetries: maxRetry - }; - return new http_client_1.HttpClient('actions/oidc-client', [new auth_1.BearerCredentialHandler(OidcClient.getRequestToken())], requestOptions); - } - static getRequestToken() { - const token = process.env['ACTIONS_ID_TOKEN_REQUEST_TOKEN']; - if (!token) { - throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_TOKEN env variable'); - } - return token; - } - static getIDTokenUrl() { - const runtimeUrl = process.env['ACTIONS_ID_TOKEN_REQUEST_URL']; - if (!runtimeUrl) { - throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable'); - } - return runtimeUrl; - } - static getCall(id_token_url) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - const httpclient = OidcClient.createHttpClient(); - const res = yield httpclient - .getJson(id_token_url) - .catch(error => { - throw new Error(`Failed to get ID Token. \n - Error Code : ${error.statusCode}\n - Error Message: ${error.result.message}`); - }); - const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value; - if (!id_token) { - throw new Error('Response json body do not have ID Token field'); - } - return id_token; - }); +/** + * Returns the minimum version needed to contain the amount of data + * + * @param {Segment} data Segment of data + * @param {Number} [errorCorrectionLevel=H] Error correction level + * @param {Mode} mode Data mode + * @return {Number} QR Code version + */ +exports.getBestVersionForData = function getBestVersionForData (data, errorCorrectionLevel) { + let seg + + const ecl = ECLevel.from(errorCorrectionLevel, ECLevel.M) + + if (Array.isArray(data)) { + if (data.length > 1) { + return getBestVersionForMixedData(data, ecl) } - static getIDToken(audience) { - return __awaiter(this, void 0, void 0, function* () { - try { - // New ID Token is requested from action service - let id_token_url = OidcClient.getIDTokenUrl(); - if (audience) { - const encodedAudience = encodeURIComponent(audience); - id_token_url = `${id_token_url}&audience=${encodedAudience}`; - } - core_1.debug(`ID token url is ${id_token_url}`); - const id_token = yield OidcClient.getCall(id_token_url); - core_1.setSecret(id_token); - return id_token; - } - catch (error) { - throw new Error(`Error message: ${error.message}`); - } - }); + + if (data.length === 0) { + return 1 } -} -exports.OidcClient = OidcClient; -//# sourceMappingURL=oidc-utils.js.map -/***/ }), + seg = data[0] + } else { + seg = data + } -/***/ 747: -/***/ (function(module) { + return getBestVersionForDataLength(seg.mode, seg.getLength(), ecl) +} -module.exports = require("fs"); +/** + * Returns version information with relative error correction bits + * + * The version information is included in QR Code symbols of version 7 or larger. + * It consists of an 18-bit sequence containing 6 data bits, + * with 12 error correction bits calculated using the (18, 6) Golay code. + * + * @param {Number} version QR Code version + * @return {Number} Encoded version info bits + */ +exports.getEncodedBits = function getEncodedBits (version) { + if (!VersionCheck.isValid(version) || version < 7) { + throw new Error('Invalid QR Code version') + } -/***/ }), + let d = version << 12 -/***/ 761: -/***/ (function(module) { + while (Utils.getBCHDigit(d) - G18_BCH >= 0) { + d ^= (G18 << (Utils.getBCHDigit(d) - G18_BCH)) + } + + return (version << 12) | d +} -module.exports = require("zlib"); /***/ }), -/***/ 765: -/***/ (function(module) { +/***/ 1302: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function BitBuffer () { - this.buffer = [] - this.length = 0 -} +/* +*copyright Ryan Day 2012 +* +* Licensed under the MIT license: +* http://www.opensource.org/licenses/mit-license.php +* +* this is the main server side application file for node-qrcode. +* these exports use serverside canvas api methods for file IO and buffers +* +*/ -BitBuffer.prototype = { +module.exports = __nccwpck_require__(2467) - get: function (index) { - var bufIndex = Math.floor(index / 8) - return ((this.buffer[bufIndex] >>> (7 - index % 8)) & 1) === 1 - }, - put: function (num, length) { - for (var i = 0; i < length; i++) { - this.putBit(((num >>> (length - i - 1)) & 1) === 1) - } - }, +/***/ }), - getLengthInBits: function () { - return this.length - }, +/***/ 6090: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - putBit: function (bit) { - var bufIndex = Math.floor(this.length / 8) - if (this.buffer.length <= bufIndex) { - this.buffer.push(0) - } +const Utils = __nccwpck_require__(8441) - if (bit) { - this.buffer[bufIndex] |= (0x80 >>> (this.length % 8)) - } +function clearCanvas (ctx, canvas, size) { + ctx.clearRect(0, 0, canvas.width, canvas.height) - this.length++ + if (!canvas.style) canvas.style = {} + canvas.height = size + canvas.width = size + canvas.style.height = size + 'px' + canvas.style.width = size + 'px' +} + +function getCanvasElement () { + try { + return document.createElement('canvas') + } catch (e) { + throw new Error('You need to specify a canvas element') } } -module.exports = BitBuffer +exports.render = function render (qrData, canvas, options) { + let opts = options + let canvasEl = canvas + if (typeof opts === 'undefined' && (!canvas || !canvas.getContext)) { + opts = canvas + canvas = undefined + } -/***/ }), + if (!canvas) { + canvasEl = getCanvasElement() + } -/***/ 769: -/***/ (function(__unusedmodule, exports, __webpack_require__) { + opts = Utils.getOptions(opts) + const size = Utils.getImageWidth(qrData.modules.size, opts) + const ctx = canvasEl.getContext('2d') + const image = ctx.createImageData(size, size) + Utils.qrToImageData(image.data, qrData, opts) -var canPromise = __webpack_require__(778) + clearCanvas(ctx, canvasEl, size) + ctx.putImageData(image, 0, 0) -var QRCode = __webpack_require__(702) -var CanvasRenderer = __webpack_require__(261) -var SvgRenderer = __webpack_require__(673) + return canvasEl +} -function renderCanvas (renderFunc, canvas, text, opts, cb) { - var args = [].slice.call(arguments, 1) - var argsNum = args.length - var isLastArgCb = typeof args[argsNum - 1] === 'function' +exports.renderToDataURL = function renderToDataURL (qrData, canvas, options) { + let opts = options - if (!isLastArgCb && !canPromise()) { - throw new Error('Callback required as last argument') + if (typeof opts === 'undefined' && (!canvas || !canvas.getContext)) { + opts = canvas + canvas = undefined } - if (isLastArgCb) { - if (argsNum < 2) { - throw new Error('Too few arguments provided') - } - - if (argsNum === 2) { - cb = text - text = canvas - canvas = opts = undefined - } else if (argsNum === 3) { - if (canvas.getContext && typeof cb === 'undefined') { - cb = opts - opts = undefined - } else { - cb = opts - opts = text - text = canvas - canvas = undefined - } - } - } else { - if (argsNum < 1) { - throw new Error('Too few arguments provided') - } + if (!opts) opts = {} - if (argsNum === 1) { - text = canvas - canvas = opts = undefined - } else if (argsNum === 2 && !canvas.getContext) { - opts = text - text = canvas - canvas = undefined - } + const canvasEl = exports.render(qrData, canvas, opts) - return new Promise(function (resolve, reject) { - try { - var data = QRCode.create(text, opts) - resolve(renderFunc(data, canvas, opts)) - } catch (e) { - reject(e) - } - }) - } + const type = opts.type || 'image/png' + const rendererOpts = opts.rendererOpts || {} - try { - var data = QRCode.create(text, opts) - cb(null, renderFunc(data, canvas, opts)) - } catch (e) { - cb(e) - } + return canvasEl.toDataURL(type, rendererOpts.quality) } -exports.create = QRCode.create -exports.toCanvas = renderCanvas.bind(null, CanvasRenderer.render) -exports.toDataURL = renderCanvas.bind(null, CanvasRenderer.renderToDataURL) -// only svg for now. -exports.toString = renderCanvas.bind(null, function (data, _, opts) { - return SvgRenderer.render(data, opts) -}) +/***/ }), +/***/ 4187: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/***/ }), +const fs = __nccwpck_require__(9896) +const PNG = (__nccwpck_require__(359)/* .PNG */ .O) +const Utils = __nccwpck_require__(8441) -/***/ 777: -/***/ (function(__unusedmodule, exports, __webpack_require__) { +exports.render = function render (qrData, options) { + const opts = Utils.getOptions(options) + const pngOpts = opts.rendererOpts + const size = Utils.getImageWidth(qrData.modules.size, opts) -var Mode = __webpack_require__(364) -var NumericData = __webpack_require__(363) -var AlphanumericData = __webpack_require__(475) -var ByteData = __webpack_require__(296) -var KanjiData = __webpack_require__(801) -var Regex = __webpack_require__(290) -var Utils = __webpack_require__(114) -var dijkstra = __webpack_require__(467) + pngOpts.width = size + pngOpts.height = size -/** - * Returns UTF8 byte length - * - * @param {String} str Input string - * @return {Number} Number of byte - */ -function getStringByteLength (str) { - return unescape(encodeURIComponent(str)).length + const pngImage = new PNG(pngOpts) + Utils.qrToImageData(pngImage.data, qrData, opts) + + return pngImage } -/** - * Get a list of segments of the specified mode - * from a string - * - * @param {Mode} mode Segment mode - * @param {String} str String to process - * @return {Array} Array of object with segments data - */ -function getSegments (regex, mode, str) { - var segments = [] - var result +exports.renderToDataURL = function renderToDataURL (qrData, options, cb) { + if (typeof cb === 'undefined') { + cb = options + options = undefined + } - while ((result = regex.exec(str)) !== null) { - segments.push({ - data: result[0], - index: result.index, - mode: mode, - length: result[0].length - }) + exports.renderToBuffer(qrData, options, function (err, output) { + if (err) cb(err) + let url = 'data:image/png;base64,' + url += output.toString('base64') + cb(null, url) + }) +} + +exports.renderToBuffer = function renderToBuffer (qrData, options, cb) { + if (typeof cb === 'undefined') { + cb = options + options = undefined } - return segments + const png = exports.render(qrData, options) + const buffer = [] + + png.on('error', cb) + + png.on('data', function (data) { + buffer.push(data) + }) + + png.on('end', function () { + cb(null, Buffer.concat(buffer)) + }) + + png.pack() } -/** - * Extracts a series of segments with the appropriate - * modes from a string - * - * @param {String} dataStr Input string - * @return {Array} Array of object with segments data - */ -function getSegmentsFromString (dataStr) { - var numSegs = getSegments(Regex.NUMERIC, Mode.NUMERIC, dataStr) - var alphaNumSegs = getSegments(Regex.ALPHANUMERIC, Mode.ALPHANUMERIC, dataStr) - var byteSegs - var kanjiSegs +exports.renderToFile = function renderToFile (path, qrData, options, cb) { + if (typeof cb === 'undefined') { + cb = options + options = undefined + } - if (Utils.isKanjiModeEnabled()) { - byteSegs = getSegments(Regex.BYTE, Mode.BYTE, dataStr) - kanjiSegs = getSegments(Regex.KANJI, Mode.KANJI, dataStr) - } else { - byteSegs = getSegments(Regex.BYTE_KANJI, Mode.BYTE, dataStr) - kanjiSegs = [] + let called = false + const done = (...args) => { + if (called) return + called = true + cb.apply(null, args) } + const stream = fs.createWriteStream(path) - var segs = numSegs.concat(alphaNumSegs, byteSegs, kanjiSegs) + stream.on('error', done) + stream.on('close', done) - return segs - .sort(function (s1, s2) { - return s1.index - s2.index - }) - .map(function (obj) { - return { - data: obj.data, - mode: obj.mode, - length: obj.length - } - }) + exports.renderToFileStream(stream, qrData, options) } -/** - * Returns how many bits are needed to encode a string of - * specified length with the specified mode - * - * @param {Number} length String length - * @param {Mode} mode Segment mode - * @return {Number} Bit length - */ -function getSegmentBitsLength (length, mode) { - switch (mode) { - case Mode.NUMERIC: - return NumericData.getBitsLength(length) - case Mode.ALPHANUMERIC: - return AlphanumericData.getBitsLength(length) - case Mode.KANJI: - return KanjiData.getBitsLength(length) - case Mode.BYTE: - return ByteData.getBitsLength(length) - } +exports.renderToFileStream = function renderToFileStream (stream, qrData, options) { + const png = exports.render(qrData, options) + png.pack().pipe(stream) } -/** - * Merges adjacent segments which have the same mode - * - * @param {Array} segs Array of object with segments data - * @return {Array} Array of object with segments data - */ -function mergeSegments (segs) { - return segs.reduce(function (acc, curr) { - var prevSeg = acc.length - 1 >= 0 ? acc[acc.length - 1] : null - if (prevSeg && prevSeg.mode === curr.mode) { - acc[acc.length - 1].data += curr.data - return acc - } - acc.push(curr) - return acc - }, []) -} +/***/ }), -/** - * Generates a list of all possible nodes combination which - * will be used to build a segments graph. - * - * Nodes are divided by groups. Each group will contain a list of all the modes - * in which is possible to encode the given text. - * - * For example the text '12345' can be encoded as Numeric, Alphanumeric or Byte. - * The group for '12345' will contain then 3 objects, one for each - * possible encoding mode. - * - * Each node represents a possible segment. - * - * @param {Array} segs Array of object with segments data - * @return {Array} Array of object with segments data - */ -function buildNodes (segs) { - var nodes = [] - for (var i = 0; i < segs.length; i++) { - var seg = segs[i] +/***/ 8291: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - switch (seg.mode) { - case Mode.NUMERIC: - nodes.push([seg, - { data: seg.data, mode: Mode.ALPHANUMERIC, length: seg.length }, - { data: seg.data, mode: Mode.BYTE, length: seg.length } - ]) - break - case Mode.ALPHANUMERIC: - nodes.push([seg, - { data: seg.data, mode: Mode.BYTE, length: seg.length } - ]) - break - case Mode.KANJI: - nodes.push([seg, - { data: seg.data, mode: Mode.BYTE, length: getStringByteLength(seg.data) } - ]) - break - case Mode.BYTE: - nodes.push([ - { data: seg.data, mode: Mode.BYTE, length: getStringByteLength(seg.data) } - ]) - } - } +const Utils = __nccwpck_require__(8441) - return nodes +function getColorAttrib (color, attrib) { + const alpha = color.a / 255 + const str = attrib + '="' + color.hex + '"' + + return alpha < 1 + ? str + ' ' + attrib + '-opacity="' + alpha.toFixed(2).slice(1) + '"' + : str } -/** - * Builds a graph from a list of nodes. - * All segments in each node group will be connected with all the segments of - * the next group and so on. - * - * At each connection will be assigned a weight depending on the - * segment's byte length. - * - * @param {Array} nodes Array of object with segments data - * @param {Number} version QR Code version - * @return {Object} Graph of all possible segments - */ -function buildGraph (nodes, version) { - var table = {} - var graph = {'start': {}} - var prevNodeIds = ['start'] +function svgCmd (cmd, x, y) { + let str = cmd + x + if (typeof y !== 'undefined') str += ' ' + y - for (var i = 0; i < nodes.length; i++) { - var nodeGroup = nodes[i] - var currentNodeIds = [] + return str +} - for (var j = 0; j < nodeGroup.length; j++) { - var node = nodeGroup[j] - var key = '' + i + j +function qrToPath (data, size, margin) { + let path = '' + let moveBy = 0 + let newRow = false + let lineLength = 0 - currentNodeIds.push(key) - table[key] = { node: node, lastCount: 0 } - graph[key] = {} + for (let i = 0; i < data.length; i++) { + const col = Math.floor(i % size) + const row = Math.floor(i / size) - for (var n = 0; n < prevNodeIds.length; n++) { - var prevNodeId = prevNodeIds[n] + if (!col && !newRow) newRow = true - if (table[prevNodeId] && table[prevNodeId].node.mode === node.mode) { - graph[prevNodeId][key] = - getSegmentBitsLength(table[prevNodeId].lastCount + node.length, node.mode) - - getSegmentBitsLength(table[prevNodeId].lastCount, node.mode) + if (data[i]) { + lineLength++ - table[prevNodeId].lastCount += node.length - } else { - if (table[prevNodeId]) table[prevNodeId].lastCount = node.length + if (!(i > 0 && col > 0 && data[i - 1])) { + path += newRow + ? svgCmd('M', col + margin, 0.5 + row + margin) + : svgCmd('m', moveBy, 0) - graph[prevNodeId][key] = getSegmentBitsLength(node.length, node.mode) + - 4 + Mode.getCharCountIndicator(node.mode, version) // switch cost - } + moveBy = 0 + newRow = false } - } - - prevNodeIds = currentNodeIds - } - for (n = 0; n < prevNodeIds.length; n++) { - graph[prevNodeIds[n]]['end'] = 0 + if (!(col + 1 < size && data[i + 1])) { + path += svgCmd('h', lineLength) + lineLength = 0 + } + } else { + moveBy++ + } } - return { map: graph, table: table } + return path } -/** - * Builds a segment from a specified data and mode. - * If a mode is not specified, the more suitable will be used. - * - * @param {String} data Input data - * @param {Mode | String} modesHint Data mode - * @return {Segment} Segment - */ -function buildSingleSegment (data, modesHint) { - var mode - var bestMode = Mode.getBestModeForData(data) - - mode = Mode.from(modesHint, bestMode) +exports.render = function render (qrData, options, cb) { + const opts = Utils.getOptions(options) + const size = qrData.modules.size + const data = qrData.modules.data + const qrcodesize = size + opts.margin * 2 - // Make sure data can be encoded - if (mode !== Mode.BYTE && mode.bit < bestMode.bit) { - throw new Error('"' + data + '"' + - ' cannot be encoded with mode ' + Mode.toString(mode) + - '.\n Suggested mode is: ' + Mode.toString(bestMode)) - } + const bg = !opts.color.light.a + ? '' + : '' - // Use Mode.BYTE if Kanji support is disabled - if (mode === Mode.KANJI && !Utils.isKanjiModeEnabled()) { - mode = Mode.BYTE - } + const path = + '' - switch (mode) { - case Mode.NUMERIC: - return new NumericData(data) + const viewBox = 'viewBox="' + '0 0 ' + qrcodesize + ' ' + qrcodesize + '"' - case Mode.ALPHANUMERIC: - return new AlphanumericData(data) + const width = !opts.width ? '' : 'width="' + opts.width + '" height="' + opts.width + '" ' - case Mode.KANJI: - return new KanjiData(data) + const svgTag = '' + bg + path + '\n' - case Mode.BYTE: - return new ByteData(data) + if (typeof cb === 'function') { + cb(null, svgTag) } + + return svgTag } -/** - * Builds a list of segments from an array. - * Array can contain Strings or Objects with segment's info. - * - * For each item which is a string, will be generated a segment with the given - * string and the more appropriate encoding mode. - * - * For each item which is an object, will be generated a segment with the given - * data and mode. - * Objects must contain at least the property "data". - * If property "mode" is not present, the more suitable mode will be used. - * - * @param {Array} array Array of objects with segments data - * @return {Array} Array of Segments - */ -exports.fromArray = function fromArray (array) { - return array.reduce(function (acc, seg) { - if (typeof seg === 'string') { - acc.push(buildSingleSegment(seg, null)) - } else if (seg.data) { - acc.push(buildSingleSegment(seg.data, seg.mode)) - } - return acc - }, []) -} +/***/ }), -/** - * Builds an optimized sequence of segments from a string, - * which will produce the shortest possible bitstream. - * - * @param {String} data Input string - * @param {Number} version QR Code version - * @return {Array} Array of segments - */ -exports.fromString = function fromString (data, version) { - var segs = getSegmentsFromString(data, Utils.isKanjiModeEnabled()) +/***/ 3378: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - var nodes = buildNodes(segs) - var graph = buildGraph(nodes, version) - var path = dijkstra.find_path(graph.map, 'start', 'end') +const svgTagRenderer = __nccwpck_require__(8291) - var optimizedSegs = [] - for (var i = 1; i < path.length - 1; i++) { - optimizedSegs.push(graph.table[path[i]].node) +exports.render = svgTagRenderer.render + +exports.renderToFile = function renderToFile (path, qrData, options, cb) { + if (typeof cb === 'undefined') { + cb = options + options = undefined } - return exports.fromArray(mergeSegments(optimizedSegs)) -} + const fs = __nccwpck_require__(9896) + const svgTag = exports.render(qrData, options) -/** - * Splits a string in various segments with the modes which - * best represent their content. - * The produced segments are far from being optimized. - * The output of this function is only used to estimate a QR Code version - * which may contain the data. - * - * @param {string} data Input string - * @return {Array} Array of segments - */ -exports.rawSplit = function rawSplit (data) { - return exports.fromArray( - getSegmentsFromString(data, Utils.isKanjiModeEnabled()) - ) + const xmlStr = '' + + '' + + svgTag + + fs.writeFile(path, xmlStr, cb) } /***/ }), -/***/ 778: -/***/ (function(module) { +/***/ 6354: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// can-promise has a crash in some versions of react native that dont have -// standard global objects -// https://github.com/soldair/node-qrcode/issues/157 +const big = __nccwpck_require__(6309) +const small = __nccwpck_require__(9323) -module.exports = function () { - return typeof Promise === 'function' && Promise.prototype && Promise.prototype.then +exports.render = function (qrData, options, cb) { + if (options && options.small) { + return small.render(qrData, options, cb) + } + return big.render(qrData, options, cb) } /***/ }), -/***/ 794: -/***/ (function(module) { +/***/ 9323: +/***/ ((__unused_webpack_module, exports) => { -module.exports = require("stream"); - -/***/ }), - -/***/ 801: -/***/ (function(module, __unusedexports, __webpack_require__) { +const backgroundWhite = '\x1b[47m' +const backgroundBlack = '\x1b[40m' +const foregroundWhite = '\x1b[37m' +const foregroundBlack = '\x1b[30m' +const reset = '\x1b[0m' +const lineSetupNormal = backgroundWhite + foregroundBlack // setup colors +const lineSetupInverse = backgroundBlack + foregroundWhite // setup colors -var Mode = __webpack_require__(364) -var Utils = __webpack_require__(114) +const createPalette = function (lineSetup, foregroundWhite, foregroundBlack) { + return { + // 1 ... white, 2 ... black, 0 ... transparent (default) -function KanjiData (data) { - this.mode = Mode.KANJI - this.data = data + '00': reset + ' ' + lineSetup, + '01': reset + foregroundWhite + '▄' + lineSetup, + '02': reset + foregroundBlack + '▄' + lineSetup, + 10: reset + foregroundWhite + '▀' + lineSetup, + 11: ' ', + 12: '▄', + 20: reset + foregroundBlack + '▀' + lineSetup, + 21: '▀', + 22: '█' + } } -KanjiData.getBitsLength = function getBitsLength (length) { - return length * 13 +/** + * Returns code for QR pixel + * @param {boolean[][]} modules + * @param {number} size + * @param {number} x + * @param {number} y + * @return {'0' | '1' | '2'} + */ +const mkCodePixel = function (modules, size, x, y) { + const sizePlus = size + 1 + if ((x >= sizePlus) || (y >= sizePlus) || (y < -1) || (x < -1)) return '0' + if ((x >= size) || (y >= size) || (y < 0) || (x < 0)) return '1' + const idx = (y * size) + x + return modules[idx] ? '2' : '1' } -KanjiData.prototype.getLength = function getLength () { - return this.data.length +/** + * Returns code for four QR pixels. Suitable as key in palette. + * @param {boolean[][]} modules + * @param {number} size + * @param {number} x + * @param {number} y + * @return {keyof palette} + */ +const mkCode = function (modules, size, x, y) { + return ( + mkCodePixel(modules, size, x, y) + + mkCodePixel(modules, size, x, y + 1) + ) } -KanjiData.prototype.getBitsLength = function getBitsLength () { - return KanjiData.getBitsLength(this.data.length) -} +exports.render = function (qrData, options, cb) { + const size = qrData.modules.size + const data = qrData.modules.data -KanjiData.prototype.write = function (bitBuffer) { - var i + const inverse = !!(options && options.inverse) + const lineSetup = options && options.inverse ? lineSetupInverse : lineSetupNormal + const white = inverse ? foregroundBlack : foregroundWhite + const black = inverse ? foregroundWhite : foregroundBlack - // In the Shift JIS system, Kanji characters are represented by a two byte combination. - // These byte values are shifted from the JIS X 0208 values. - // JIS X 0208 gives details of the shift coded representation. - for (i = 0; i < this.data.length; i++) { - var value = Utils.toSJIS(this.data[i]) + const palette = createPalette(lineSetup, white, black) + const newLine = reset + '\n' + lineSetup - // For characters with Shift JIS values from 0x8140 to 0x9FFC: - if (value >= 0x8140 && value <= 0x9FFC) { - // Subtract 0x8140 from Shift JIS value - value -= 0x8140 + let output = lineSetup // setup colors - // For characters with Shift JIS values from 0xE040 to 0xEBBF - } else if (value >= 0xE040 && value <= 0xEBBF) { - // Subtract 0xC140 from Shift JIS value - value -= 0xC140 - } else { - throw new Error( - 'Invalid SJIS character: ' + this.data[i] + '\n' + - 'Make sure your charset is UTF-8') + for (let y = -1; y < size + 1; y += 2) { + for (let x = -1; x < size; x++) { + output += palette[mkCode(data, size, x, y)] } - // Multiply most significant byte of result by 0xC0 - // and add least significant byte to product - value = (((value >>> 8) & 0xff) * 0xC0) + (value & 0xff) - - // Convert result to a 13-bit binary string - bitBuffer.put(value, 13) + output += palette[mkCode(data, size, size, y)] + newLine } -} - -module.exports = KanjiData + output += reset -/***/ }), - -/***/ 810: -/***/ (function(__unusedmodule, exports, __webpack_require__) { + if (typeof cb === 'function') { + cb(null, output) + } -"use strict"; + return output +} -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = void 0; +/***/ }), -var _rng = _interopRequireDefault(__webpack_require__(506)); +/***/ 6309: +/***/ ((__unused_webpack_module, exports) => { -var _stringify = _interopRequireDefault(__webpack_require__(960)); +// let Utils = require('./utils') -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +exports.render = function (qrData, options, cb) { + const size = qrData.modules.size + const data = qrData.modules.data -// **`v1()` - Generate time-based UUID** -// -// Inspired by https://github.com/LiosK/UUID.js -// and http://docs.python.org/library/uuid.html -let _nodeId; + // let opts = Utils.getOptions(options) -let _clockseq; // Previous uuid creation time + // use same scheme as https://github.com/gtanner/qrcode-terminal because it actually works! =) + const black = '\x1b[40m \x1b[0m' + const white = '\x1b[47m \x1b[0m' + let output = '' + const hMargin = Array(size + 3).join(white) + const vMargin = Array(2).join(white) -let _lastMSecs = 0; -let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details + output += hMargin + '\n' + for (let i = 0; i < size; ++i) { + output += white + for (let j = 0; j < size; j++) { + // let topModule = data[i * size + j] + // let bottomModule = data[(i + 1) * size + j] -function v1(options, buf, offset) { - let i = buf && offset || 0; - const b = buf || new Array(16); - options = options || {}; - let node = options.node || _nodeId; - let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not - // specified. We do this lazily to minimize issues related to insufficient - // system entropy. See #189 + output += data[i * size + j] ? black : white// getBlockChar(topModule, bottomModule) + } + // output += white+'\n' + output += vMargin + '\n' + } - if (node == null || clockseq == null) { - const seedBytes = options.random || (options.rng || _rng.default)(); + output += hMargin + '\n' - if (node == null) { - // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) - node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; - } + if (typeof cb === 'function') { + cb(null, output) + } - if (clockseq == null) { - // Per 4.2.2, randomize (14 bit) clockseq - clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; - } - } // UUID timestamps are 100 nano-second units since the Gregorian epoch, - // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so - // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' - // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. + return output +} +/* +exports.renderToFile = function renderToFile (path, qrData, options, cb) { + if (typeof cb === 'undefined') { + cb = options + options = undefined + } + let fs = require('fs') + let utf8 = exports.render(qrData, options) + fs.writeFile(path, utf8, cb) +} +*/ - let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock - // cycle to simulate higher resolution clock - let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) +/***/ }), - const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression +/***/ 5565: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (dt < 0 && options.clockseq === undefined) { - clockseq = clockseq + 1 & 0x3fff; - } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new - // time interval +const Utils = __nccwpck_require__(8441) +const BLOCK_CHAR = { + WW: ' ', + WB: '▄', + BB: '█', + BW: '▀' +} - if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { - nsecs = 0; - } // Per 4.2.1.2 Throw error if too many uuids are requested +const INVERTED_BLOCK_CHAR = { + BB: ' ', + BW: '▄', + WW: '█', + WB: '▀' +} +function getBlockChar (top, bottom, blocks) { + if (top && bottom) return blocks.BB + if (top && !bottom) return blocks.BW + if (!top && bottom) return blocks.WB + return blocks.WW +} - if (nsecs >= 10000) { - throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); +exports.render = function (qrData, options, cb) { + const opts = Utils.getOptions(options) + let blocks = BLOCK_CHAR + if (opts.color.dark.hex === '#ffffff' || opts.color.light.hex === '#000000') { + blocks = INVERTED_BLOCK_CHAR } - _lastMSecs = msecs; - _lastNSecs = nsecs; - _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch - - msecs += 12219292800000; // `time_low` + const size = qrData.modules.size + const data = qrData.modules.data - const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; - b[i++] = tl >>> 24 & 0xff; - b[i++] = tl >>> 16 & 0xff; - b[i++] = tl >>> 8 & 0xff; - b[i++] = tl & 0xff; // `time_mid` + let output = '' + let hMargin = Array(size + (opts.margin * 2) + 1).join(blocks.WW) + hMargin = Array((opts.margin / 2) + 1).join(hMargin + '\n') - const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; - b[i++] = tmh >>> 8 & 0xff; - b[i++] = tmh & 0xff; // `time_high_and_version` + const vMargin = Array(opts.margin + 1).join(blocks.WW) - b[i++] = tmh >>> 24 & 0xf | 0x10; // include version + output += hMargin + for (let i = 0; i < size; i += 2) { + output += vMargin + for (let j = 0; j < size; j++) { + const topModule = data[i * size + j] + const bottomModule = data[(i + 1) * size + j] - b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + output += getBlockChar(topModule, bottomModule, blocks) + } - b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` + output += vMargin + '\n' + } - b[i++] = clockseq & 0xff; // `node` + output += hMargin.slice(0, -1) - for (let n = 0; n < 6; ++n) { - b[i + n] = node[n]; + if (typeof cb === 'function') { + cb(null, output) } - return buf || (0, _stringify.default)(b); + return output } -var _default = v1; -exports.default = _default; +exports.renderToFile = function renderToFile (path, qrData, options, cb) { + if (typeof cb === 'undefined') { + cb = options + options = undefined + } -/***/ }), + const fs = __nccwpck_require__(9896) + const utf8 = exports.render(qrData, options) + fs.writeFile(path, utf8, cb) +} -/***/ 847: -/***/ (function(__unusedmodule, exports, __webpack_require__) { -var BufferUtil = __webpack_require__(628) -var GF = __webpack_require__(526) +/***/ }), -/** - * Multiplies two polynomials inside Galois Field - * - * @param {Buffer} p1 Polynomial - * @param {Buffer} p2 Polynomial - * @return {Buffer} Product of p1 and p2 - */ -exports.mul = function mul (p1, p2) { - var coeff = BufferUtil.alloc(p1.length + p2.length - 1) +/***/ 8441: +/***/ ((__unused_webpack_module, exports) => { - for (var i = 0; i < p1.length; i++) { - for (var j = 0; j < p2.length; j++) { - coeff[i + j] ^= GF.mul(p1[i], p2[j]) - } +function hex2rgba (hex) { + if (typeof hex === 'number') { + hex = hex.toString() } - return coeff -} - -/** - * Calculate the remainder of polynomials division - * - * @param {Buffer} divident Polynomial - * @param {Buffer} divisor Polynomial - * @return {Buffer} Remainder - */ -exports.mod = function mod (divident, divisor) { - var result = BufferUtil.from(divident) - - while ((result.length - divisor.length) >= 0) { - var coeff = result[0] + if (typeof hex !== 'string') { + throw new Error('Color should be defined as hex string') + } - for (var i = 0; i < divisor.length; i++) { - result[i] ^= GF.mul(divisor[i], coeff) - } + let hexCode = hex.slice().replace('#', '').split('') + if (hexCode.length < 3 || hexCode.length === 5 || hexCode.length > 8) { + throw new Error('Invalid hex color: ' + hex) + } - // remove all zeros from buffer head - var offset = 0 - while (offset < result.length && result[offset] === 0) offset++ - result = result.slice(offset) + // Convert from short to long form (fff -> ffffff) + if (hexCode.length === 3 || hexCode.length === 4) { + hexCode = Array.prototype.concat.apply([], hexCode.map(function (c) { + return [c, c] + })) } - return result -} + // Add default alpha value + if (hexCode.length === 6) hexCode.push('F', 'F') -/** - * Generate an irreducible generator polynomial of specified degree - * (used by Reed-Solomon encoder) - * - * @param {Number} degree Degree of the generator polynomial - * @return {Buffer} Buffer containing polynomial coefficients - */ -exports.generateECPolynomial = function generateECPolynomial (degree) { - var poly = BufferUtil.from([1]) - for (var i = 0; i < degree; i++) { - poly = exports.mul(poly, [1, GF.exp(i)]) - } + const hexValue = parseInt(hexCode.join(''), 16) - return poly + return { + r: (hexValue >> 24) & 255, + g: (hexValue >> 16) & 255, + b: (hexValue >> 8) & 255, + a: hexValue & 255, + hex: '#' + hexCode.slice(0, 6).join('') + } } +exports.getOptions = function getOptions (options) { + if (!options) options = {} + if (!options.color) options.color = {} -/***/ }), + const margin = typeof options.margin === 'undefined' || + options.margin === null || + options.margin < 0 + ? 4 + : options.margin -/***/ 904: -/***/ (function(__unusedmodule, exports, __webpack_require__) { + const width = options.width && options.width >= 21 ? options.width : undefined + const scale = options.scale || 4 -"use strict"; + return { + width: width, + scale: width ? 4 : scale, + margin: margin, + color: { + dark: hex2rgba(options.color.dark || '#000000ff'), + light: hex2rgba(options.color.light || '#ffffffff') + }, + type: options.type, + rendererOpts: options.rendererOpts || {} + } +} +exports.getScale = function getScale (qrSize, opts) { + return opts.width && opts.width >= qrSize + opts.margin * 2 + ? opts.width / (qrSize + opts.margin * 2) + : opts.scale +} -var SyncReader = __webpack_require__(80); -var Filter = __webpack_require__(447); +exports.getImageWidth = function getImageWidth (qrSize, opts) { + const scale = exports.getScale(qrSize, opts) + return Math.floor((qrSize + opts.margin * 2) * scale) +} +exports.qrToImageData = function qrToImageData (imgData, qr, opts) { + const size = qr.modules.size + const data = qr.modules.data + const scale = exports.getScale(size, opts) + const symbolSize = Math.floor((size + opts.margin * 2) * scale) + const scaledMargin = opts.margin * scale + const palette = [opts.color.light, opts.color.dark] + + for (let i = 0; i < symbolSize; i++) { + for (let j = 0; j < symbolSize; j++) { + let posDst = (i * symbolSize + j) * 4 + let pxColor = opts.color.light -exports.process = function(inBuffer, bitmapInfo) { + if (i >= scaledMargin && j >= scaledMargin && + i < symbolSize - scaledMargin && j < symbolSize - scaledMargin) { + const iSrc = Math.floor((i - scaledMargin) / scale) + const jSrc = Math.floor((j - scaledMargin) / scale) + pxColor = palette[data[iSrc * size + jSrc] ? 1 : 0] + } - 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() { + imgData[posDst++] = pxColor.r + imgData[posDst++] = pxColor.g + imgData[posDst++] = pxColor.b + imgData[posDst] = pxColor.a } - }); - - filter.start(); - reader.process(); + } +} - return Buffer.concat(outBuffers); -}; /***/ }), -/***/ 927: -/***/ (function(__unusedmodule, exports, __webpack_require__) { +/***/ 2467: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -var canPromise = __webpack_require__(778) -var QRCode = __webpack_require__(702) -var PngRenderer = __webpack_require__(436) -var Utf8Renderer = __webpack_require__(355) -var TerminalRenderer = __webpack_require__(160) -var SvgRenderer = __webpack_require__(107) +const canPromise = __nccwpck_require__(5552) +const QRCode = __nccwpck_require__(4024) +const PngRenderer = __nccwpck_require__(4187) +const Utf8Renderer = __nccwpck_require__(5565) +const TerminalRenderer = __nccwpck_require__(6354) +const SvgRenderer = __nccwpck_require__(3378) function checkParams (text, opts, cb) { if (typeof text === 'undefined') { @@ -8611,7 +9210,7 @@ function render (renderFunc, text, params) { if (!params.cb) { return new Promise(function (resolve, reject) { try { - var data = QRCode.create(text, params.opts) + const data = QRCode.create(text, params.opts) return renderFunc(data, params.opts, function (err, data) { return err ? reject(err) : resolve(data) }) @@ -8622,7 +9221,7 @@ function render (renderFunc, text, params) { } try { - var data = QRCode.create(text, params.opts) + const data = QRCode.create(text, params.opts) return renderFunc(data, params.opts, params.cb) } catch (e) { params.cb(e) @@ -8631,23 +9230,24 @@ function render (renderFunc, text, params) { exports.create = QRCode.create -exports.toCanvas = __webpack_require__(769).toCanvas +exports.toCanvas = __nccwpck_require__(1462).toCanvas exports.toString = function toString (text, opts, cb) { - var params = checkParams(text, opts, cb) - var renderer = getStringRendererFromType(params.opts.type) + const params = checkParams(text, opts, cb) + const type = params.opts ? params.opts.type : undefined + const renderer = getStringRendererFromType(type) return render(renderer.render, text, params) } exports.toDataURL = function toDataURL (text, opts, cb) { - var params = checkParams(text, opts, cb) - var renderer = getRendererFromType(params.opts.type) + const params = checkParams(text, opts, cb) + const renderer = getRendererFromType(params.opts.type) return render(renderer.renderToDataURL, text, params) } exports.toBuffer = function toBuffer (text, opts, cb) { - var params = checkParams(text, opts, cb) - var renderer = getRendererFromType(params.opts.type) + const params = checkParams(text, opts, cb) + const renderer = getRendererFromType(params.opts.type) return render(renderer.renderToBuffer, text, params) } @@ -8660,10 +9260,10 @@ exports.toFile = function toFile (path, text, opts, cb) { throw new Error('Too few arguments provided') } - var params = checkParams(text, opts, cb) - var type = params.opts.type || getTypeFromFilename(path) - var renderer = getRendererFromType(type) - var renderToFile = renderer.renderToFile.bind(null, path) + const params = checkParams(text, opts, cb) + const type = params.opts.type || getTypeFromFilename(path) + const renderer = getRendererFromType(type) + const renderToFile = renderer.renderToFile.bind(null, path) return render(renderToFile, text, params) } @@ -8673,480 +9273,494 @@ exports.toFileStream = function toFileStream (stream, text, opts) { throw new Error('Too few arguments provided') } - var params = checkParams(text, opts, stream.emit.bind(stream, 'error')) - var renderer = getRendererFromType('png') // Only png support for now - var renderToFileStream = renderer.renderToFileStream.bind(null, stream) + const params = checkParams(text, opts, stream.emit.bind(stream, 'error')) + const renderer = getRendererFromType('png') // Only png support for now + const renderToFileStream = renderer.renderToFileStream.bind(null, stream) render(renderToFileStream, text, params) } /***/ }), -/***/ 932: -/***/ (function(module, __unusedexports, __webpack_require__) { +/***/ 770: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +module.exports = __nccwpck_require__(218); + + +/***/ }), + +/***/ 218: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +var net = __nccwpck_require__(9278); +var tls = __nccwpck_require__(4756); +var http = __nccwpck_require__(8611); +var https = __nccwpck_require__(5692); +var events = __nccwpck_require__(4434); +var assert = __nccwpck_require__(2613); +var util = __nccwpck_require__(9023); + + +exports.httpOverHttp = httpOverHttp; +exports.httpsOverHttp = httpsOverHttp; +exports.httpOverHttps = httpOverHttps; +exports.httpsOverHttps = httpsOverHttps; + + +function httpOverHttp(options) { + var agent = new TunnelingAgent(options); + agent.request = http.request; + return agent; +} -"use strict"; +function httpsOverHttp(options) { + var agent = new TunnelingAgent(options); + agent.request = http.request; + agent.createSocket = createSecureSocket; + agent.defaultPort = 443; + return agent; +} +function httpOverHttps(options) { + var agent = new TunnelingAgent(options); + agent.request = https.request; + return agent; +} -var constants = __webpack_require__(268); -var CrcCalculator = __webpack_require__(228); +function httpsOverHttps(options) { + var agent = new TunnelingAgent(options); + agent.request = https.request; + agent.createSocket = createSecureSocket; + agent.defaultPort = 443; + return agent; +} -var Parser = module.exports = function(options, dependencies) { +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 = []; - this._options = options; - options.checkCRC = options.checkCRC !== false; + 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); + }); +} +util.inherits(TunnelingAgent, events.EventEmitter); - this._hasIHDR = false; - this._hasIEND = false; - this._emittedHeadersFinished = false; +TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) { + var self = this; + var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress)); - // input flags/metadata - this._palette = []; - this._colorType = 0; + if (self.sockets.length >= this.maxSockets) { + // We are over limit so we'll add it to the queue. + self.requests.push(options); + return; + } - 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); + // 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); - 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() {}; -}; + function onFree() { + self.emit('free', socket, options); + } -Parser.prototype.start = function() { - this.read(constants.PNG_SIGNATURE.length, - this._parseSignature.bind(this) - ); + function onCloseOrRemove(err) { + self.removeSocket(socket); + socket.removeListener('free', onFree); + socket.removeListener('close', onCloseOrRemove); + socket.removeListener('agentRemove', onCloseOrRemove); + } + }); }; -Parser.prototype._parseSignature = function(data) { - - var signature = constants.PNG_SIGNATURE; +TunnelingAgent.prototype.createSocket = function createSocket(options, cb) { + var self = this; + var placeholder = {}; + self.sockets.push(placeholder); - for (var i = 0; i < signature.length; i++) { - if (data[i] !== signature[i]) { - this.error(new Error('Invalid file signature')); - return; + var connectOptions = mergeOptions({}, self.proxyOptions, { + method: 'CONNECT', + path: options.host + ':' + options.port, + agent: false, + headers: { + host: options.host + ':' + options.port } + }); + if (options.localAddress) { + connectOptions.localAddress = options.localAddress; } - 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]); + if (connectOptions.proxyAuth) { + connectOptions.headers = connectOptions.headers || {}; + connectOptions.headers['Proxy-Authorization'] = 'Basic ' + + new Buffer(connectOptions.proxyAuth).toString('base64'); } - //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 + debug('making CONNECT request'); + var connectReq = self.request(connectOptions); + connectReq.useChunkedEncodingByDefault = false; // for v0.6 + connectReq.once('response', onResponse); // for v0.6 + connectReq.once('upgrade', onUpgrade); // for v0.6 + connectReq.once('connect', onConnect); // for v0.7 or later + connectReq.once('error', onError); + connectReq.end(); - if (!this._hasIHDR && type !== constants.TYPE_IHDR) { - this.error(new Error('Expected IHDR on beggining')); - return; + function onResponse(res) { + // Very hacky. This is necessary to avoid http-parser leaks. + res.upgrade = true; } - this._crc = new CrcCalculator(); - this._crc.write(new Buffer(name)); - - if (this._chunks[type]) { - return this._chunks[type](length); + function onUpgrade(res, socket, head) { + // Hacky. + process.nextTick(function() { + onConnect(res, socket, head); + }); } - if (!ancillary) { - this.error(new Error('Unsupported critical chunk type ' + name)); - return; - } + function onConnect(res, socket, head) { + connectReq.removeAllListeners(); + socket.removeAllListeners(); - this.read(length + 4, this._skipChunk.bind(this)); -}; + if (res.statusCode !== 200) { + debug('tunneling socket could not be established, statusCode=%d', + res.statusCode); + socket.destroy(); + var error = new Error('tunneling socket could not be established, ' + + 'statusCode=' + res.statusCode); + error.code = 'ECONNRESET'; + options.request.emit('error', error); + self.removeSocket(placeholder); + return; + } + if (head.length > 0) { + debug('got illegal response body from proxy'); + socket.destroy(); + var error = new Error('got illegal response body from proxy'); + error.code = 'ECONNRESET'; + options.request.emit('error', error); + self.removeSocket(placeholder); + return; + } + debug('tunneling connection has established'); + self.sockets[self.sockets.indexOf(placeholder)] = socket; + return cb(socket); + } -Parser.prototype._skipChunk = function(/*data*/) { - this.read(8, this._parseChunkBegin.bind(this)); -}; + function onError(cause) { + connectReq.removeAllListeners(); -Parser.prototype._handleChunkEnd = function() { - this.read(4, this._parseChunkEnd.bind(this)); + debug('tunneling socket could not be established, cause=%s\n', + cause.message, cause.stack); + var error = new Error('tunneling socket could not be established, ' + + 'cause=' + cause.message); + error.code = 'ECONNRESET'; + options.request.emit('error', error); + self.removeSocket(placeholder); + } }; -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)); +TunnelingAgent.prototype.removeSocket = function removeSocket(socket) { + var pos = this.sockets.indexOf(socket) + if (pos === -1) { return; } + this.sockets.splice(pos, 1); - if (!this._hasIEND) { - this.read(8, this._parseChunkBegin.bind(this)); + var pending = this.requests.shift(); + if (pending) { + // If we have pending requests and a socket gets closed a new one + // needs to be created to take over in the pool for the one that closed. + this.createSocket(pending, function(socket) { + pending.request.onSocket(socket); + }); } }; -Parser.prototype._handleIHDR = function(length) { - this.read(length, this._parseIHDR.bind(this)); -}; -Parser.prototype._parseIHDR = function(data) { - - this._crc.write(data); +function createSecureSocket(options, cb) { + var self = this; + TunnelingAgent.prototype.createSocket.call(self, options, function(socket) { + var hostHeader = options.request.getHeader('host'); + var tlsOptions = mergeOptions({}, self.options, { + socket: socket, + servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host + }); - var 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]; + // 0 is dummy port for v0.6 + var secureSocket = tls.connect(0, tlsOptions); + self.sockets[self.sockets.indexOf(socket)] = secureSocket; + cb(secureSocket); + }); +} - // 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; +function toOptions(host, port, localAddress) { + if (typeof host === 'string') { // since v0.10 + return { + host: host, + port: port, + localAddress: localAddress + }; } + return host; // for v0.11 or later +} - this._colorType = colorType; - - var bpp = constants.COLORTYPE_TO_BPP_MAP[this._colorType]; - - this._hasIHDR = true; +function mergeOptions(target) { + for (var i = 1, len = arguments.length; i < len; ++i) { + var overrides = arguments[i]; + if (typeof overrides === 'object') { + var keys = Object.keys(overrides); + for (var j = 0, keyLen = keys.length; j < keyLen; ++j) { + var k = keys[j]; + if (overrides[k] !== undefined) { + target[k] = overrides[k]; + } + } + } + } + return target; +} - 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(); -}; +var debug; +if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) { + debug = function() { + var args = Array.prototype.slice.call(arguments); + if (typeof args[0] === 'string') { + args[0] = 'TUNNEL: ' + args[0]; + } else { + args.unshift('TUNNEL:'); + } + console.error.apply(console, args); + } +} else { + debug = function() {}; +} +exports.debug = debug; // for test -Parser.prototype._handlePLTE = function(length) { - this.read(length, this._parsePLTE.bind(this)); -}; -Parser.prototype._parsePLTE = function(data) { +/***/ }), - this._crc.write(data); +/***/ 2613: +/***/ ((module) => { - var entries = Math.floor(data.length / 3); - // console.log('Palette:', entries); +"use strict"; +module.exports = require("assert"); - 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); +/***/ 181: +/***/ ((module) => { - this._handleChunkEnd(); -}; +"use strict"; +module.exports = require("buffer"); -Parser.prototype._handleTRNS = function(length) { - this.simpleTransparency(); - this.read(length, this._parseTRNS.bind(this)); -}; -Parser.prototype._parseTRNS = function(data) { +/***/ }), - this._crc.write(data); +/***/ 5317: +/***/ ((module) => { - // 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); - } +"use strict"; +module.exports = require("child_process"); - // 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(); -}; +/***/ 6982: +/***/ ((module) => { -Parser.prototype._handleGAMA = function(length) { - this.read(length, this._parseGAMA.bind(this)); -}; -Parser.prototype._parseGAMA = function(data) { +"use strict"; +module.exports = require("crypto"); - this._crc.write(data); - this.gamma(data.readUInt32BE(0) / constants.GAMMA_DIVISION); +/***/ }), - this._handleChunkEnd(); -}; +/***/ 4434: +/***/ ((module) => { -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) { +"use strict"; +module.exports = require("events"); - this._crc.write(data); +/***/ }), - if (this._colorType === constants.COLORTYPE_PALETTE_COLOR && this._palette.length === 0) { - throw new Error('Expected palette not found'); - } +/***/ 9896: +/***/ ((module) => { - this.inflateData(data); - var leftOverLength = length - data.length; +"use strict"; +module.exports = require("fs"); - 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) { +/***/ 8611: +/***/ ((module) => { - this._crc.write(data); +"use strict"; +module.exports = require("http"); - this._hasIEND = true; - this._handleChunkEnd(); +/***/ }), - if (this.finished) { - this.finished(); - } -}; +/***/ 5692: +/***/ ((module) => { +"use strict"; +module.exports = require("https"); /***/ }), -/***/ 939: -/***/ (function(module, __unusedexports, __webpack_require__) { +/***/ 9278: +/***/ ((module) => { -/* -*copyright Ryan Day 2012 -* -* Licensed under the MIT license: -* http://www.opensource.org/licenses/mit-license.php -* -* this is the main server side application file for node-qrcode. -* these exports use serverside canvas api methods for file IO and buffers -* -*/ +"use strict"; +module.exports = require("net"); -module.exports = __webpack_require__(927) +/***/ }), + +/***/ 857: +/***/ ((module) => { +"use strict"; +module.exports = require("os"); /***/ }), -/***/ 960: -/***/ (function(__unusedmodule, exports, __webpack_require__) { +/***/ 6928: +/***/ ((module) => { "use strict"; +module.exports = require("path"); +/***/ }), -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = void 0; - -var _validate = _interopRequireDefault(__webpack_require__(634)); +/***/ 2203: +/***/ ((module) => { -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +"use strict"; +module.exports = require("stream"); -/** - * Convert array of 16 byte values to UUID string format of the form: - * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX - */ -const byteToHex = []; +/***/ }), -for (let i = 0; i < 256; ++i) { - byteToHex.push((i + 0x100).toString(16).substr(1)); -} +/***/ 3193: +/***/ ((module) => { -function stringify(arr, offset = 0) { - // Note: Be careful editing this code! It's been tuned for performance - // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 - const uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one - // of the following: - // - One or more input array values don't map to a hex octet (leading to - // "undefined" in the uuid) - // - Invalid input values for the RFC `version` or `variant` fields +"use strict"; +module.exports = require("string_decoder"); - if (!(0, _validate.default)(uuid)) { - throw TypeError('Stringified UUID is invalid'); - } +/***/ }), - return uuid; -} +/***/ 3557: +/***/ ((module) => { -var _default = stringify; -exports.default = _default; +"use strict"; +module.exports = require("timers"); /***/ }), -/***/ 994: -/***/ (function(module) { +/***/ 4756: +/***/ ((module) => { "use strict"; +module.exports = require("tls"); +/***/ }), -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'); - } +/***/ 9023: +/***/ ((module) => { - for (var i = 0; i < 4; i++) { - outdata[pxPos + i] = color[i]; - } - pxPos += 4; - } - } -} +"use strict"; +module.exports = require("util"); -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; - } - } -} +/***/ 3106: +/***/ ((module) => { -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; - } - } -} +"use strict"; +module.exports = require("zlib"); -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; +/******/ }); +/************************************************************************/ +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; +/******/ +/******/ // The require function +/******/ function __nccwpck_require__(moduleId) { +/******/ // Check if module is in cache +/******/ var cachedModule = __webpack_module_cache__[moduleId]; +/******/ if (cachedModule !== undefined) { +/******/ return cachedModule.exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = __webpack_module_cache__[moduleId] = { +/******/ // no module.id needed +/******/ // no module.loaded needed +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ var threw = true; +/******/ try { +/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __nccwpck_require__); +/******/ threw = false; +/******/ } finally { +/******/ if(threw) delete __webpack_module_cache__[moduleId]; +/******/ } +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/compat */ +/******/ +/******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = __dirname + "/"; +/******/ +/************************************************************************/ +var __webpack_exports__ = {}; +const core = __nccwpck_require__(7484); +const QRCode = __nccwpck_require__(1302); - 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); - } +async function run() { + try { + const text = core.getInput('text'); + const path = core.getInput('path'); + QRCode.toString(text, { type: 'terminal' }, function (err, string) { + if (err) throw err + console.log(string) + }) + QRCode.toFile( + path, + text + ) + } + catch (error) { + core.setFailed(error.message); } - return outdata; -}; - +} -/***/ }) +run() -/******/ }); \ No newline at end of file +module.exports = __webpack_exports__; +/******/ })() +; \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index ed943d4..4217ac1 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "javascript-action", - "version": "1.0.0", + "version": "1.1.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "javascript-action", - "version": "1.0.0", + "version": "1.1.0", "license": "MIT", "dependencies": { "@actions/core": "^1.10.0", diff --git a/package.json b/package.json index 4722123..d126e25 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "javascript-action", - "version": "1.0.0", + "version": "1.1.0", "description": "JavaScript Action Template", "main": "index.js", "scripts": {