diff --git a/action/index.js b/action/index.js index 81522520..2c108b22 100644 --- a/action/index.js +++ b/action/index.js @@ -50,357 +50,863 @@ module.exports = /******/ }) /************************************************************************/ /******/ ([ -/* 0 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -var cloneArrayBuffer = __webpack_require__(600); - -/** - * Creates a clone of `dataView`. - * - * @private - * @param {Object} dataView The data view to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned data view. - */ -function cloneDataView(dataView, isDeep) { - var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; - return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); -} - -module.exports = cloneDataView; - - -/***/ }), +/* 0 */, /* 1 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +/***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; +var Buffer = __webpack_require__(215).Buffer; -var BottleneckError, States; -BottleneckError = __webpack_require__(212); -States = class States { - constructor(status1) { - this.status = status1; - this._jobs = {}; - this.counts = this.status.map(function () { - return 0; - }); - } +// Multibyte codec. In this scheme, a character is represented by 1 or more bytes. +// Our codec supports UTF-16 surrogates, extensions for GB18030 and unicode sequences. +// To save memory and loading time, we read table files only when requested. - next(id) { - var current, next; - current = this._jobs[id]; - next = current + 1; +exports._dbcs = DBCSCodec; - if (current != null && next < this.status.length) { - this.counts[current]--; - this.counts[next]++; - return this._jobs[id]++; - } else if (current != null) { - this.counts[current]--; - return delete this._jobs[id]; - } - } +var UNASSIGNED = -1, + GB18030_CODE = -2, + SEQ_START = -10, + NODE_START = -1000, + UNASSIGNED_NODE = new Array(0x100), + DEF_CHAR = -1; - start(id) { - var initial; - initial = 0; - this._jobs[id] = initial; - return this.counts[initial]++; - } +for (var i = 0; i < 0x100; i++) + UNASSIGNED_NODE[i] = UNASSIGNED; - remove(id) { - var current; - current = this._jobs[id]; - if (current != null) { - this.counts[current]--; - delete this._jobs[id]; - } +// Class DBCSCodec reads and initializes mapping tables. +function DBCSCodec(codecOptions, iconv) { + this.encodingName = codecOptions.encodingName; + if (!codecOptions) + throw new Error("DBCS codec is called without the data.") + if (!codecOptions.table) + throw new Error("Encoding '" + this.encodingName + "' has no data."); - return current != null; - } + // Load tables. + var mappingTable = codecOptions.table(); - jobStatus(id) { - var ref; - return (ref = this.status[this._jobs[id]]) != null ? ref : null; - } - statusJobs(status) { - var k, pos, ref, results, v; + // Decode tables: MBCS -> Unicode. - if (status != null) { - pos = this.status.indexOf(status); + // decodeTables is a trie, encoded as an array of arrays of integers. Internal arrays are trie nodes and all have len = 256. + // Trie root is decodeTables[0]. + // Values: >= 0 -> unicode character code. can be > 0xFFFF + // == UNASSIGNED -> unknown/unassigned sequence. + // == GB18030_CODE -> this is the end of a GB18030 4-byte sequence. + // <= NODE_START -> index of the next node in our trie to process next byte. + // <= SEQ_START -> index of the start of a character code sequence, in decodeTableSeq. + this.decodeTables = []; + this.decodeTables[0] = UNASSIGNED_NODE.slice(0); // Create root node. - if (pos < 0) { - throw new BottleneckError(`status must be one of ${this.status.join(', ')}`); - } + // Sometimes a MBCS char corresponds to a sequence of unicode chars. We store them as arrays of integers here. + this.decodeTableSeq = []; - ref = this._jobs; - results = []; + // Actual mapping tables consist of chunks. Use them to fill up decode tables. + for (var i = 0; i < mappingTable.length; i++) + this._addDecodeChunk(mappingTable[i]); - for (k in ref) { - v = ref[k]; + this.defaultCharUnicode = iconv.defaultCharUnicode; - if (v === pos) { - results.push(k); + + // Encode tables: Unicode -> DBCS. + + // `encodeTable` is array mapping from unicode char to encoded char. All its values are integers for performance. + // Because it can be sparse, it is represented as array of buckets by 256 chars each. Bucket can be null. + // Values: >= 0 -> it is a normal char. Write the value (if <=256 then 1 byte, if <=65536 then 2 bytes, etc.). + // == UNASSIGNED -> no conversion found. Output a default char. + // <= SEQ_START -> it's an index in encodeTableSeq, see below. The character starts a sequence. + this.encodeTable = []; + + // `encodeTableSeq` is used when a sequence of unicode characters is encoded as a single code. We use a tree of + // objects where keys correspond to characters in sequence and leafs are the encoded dbcs values. A special DEF_CHAR key + // means end of sequence (needed when one sequence is a strict subsequence of another). + // Objects are kept separately from encodeTable to increase performance. + this.encodeTableSeq = []; + + // Some chars can be decoded, but need not be encoded. + var skipEncodeChars = {}; + if (codecOptions.encodeSkipVals) + for (var i = 0; i < codecOptions.encodeSkipVals.length; i++) { + var val = codecOptions.encodeSkipVals[i]; + if (typeof val === 'number') + skipEncodeChars[val] = true; + else + for (var j = val.from; j <= val.to; j++) + skipEncodeChars[j] = true; } - } + + // Use decode trie to recursively fill out encode tables. + this._fillEncodeTable(0, 0, skipEncodeChars); - return results; - } else { - return Object.keys(this._jobs); + // Add more encoding pairs when needed. + if (codecOptions.encodeAdd) { + for (var uChar in codecOptions.encodeAdd) + if (Object.prototype.hasOwnProperty.call(codecOptions.encodeAdd, uChar)) + this._setEncodeChar(uChar.charCodeAt(0), codecOptions.encodeAdd[uChar]); } - } - statusCounts() { - return this.counts.reduce((acc, v, i) => { - acc[this.status[i]] = v; - return acc; - }, {}); - } + this.defCharSB = this.encodeTable[0][iconv.defaultCharSingleByte.charCodeAt(0)]; + if (this.defCharSB === UNASSIGNED) this.defCharSB = this.encodeTable[0]['?']; + if (this.defCharSB === UNASSIGNED) this.defCharSB = "?".charCodeAt(0); -}; -module.exports = States; -/***/ }), -/* 2 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + // Load & create GB18030 tables when needed. + if (typeof codecOptions.gb18030 === 'function') { + this.gb18030 = codecOptions.gb18030(); // Load GB18030 ranges. -"use strict"; + // Add GB18030 decode tables. + var thirdByteNodeIdx = this.decodeTables.length; + var thirdByteNode = this.decodeTables[thirdByteNodeIdx] = UNASSIGNED_NODE.slice(0); -const os = __webpack_require__(87); -const macosRelease = __webpack_require__(118); -const winRelease = __webpack_require__(49); + var fourthByteNodeIdx = this.decodeTables.length; + var fourthByteNode = this.decodeTables[fourthByteNodeIdx] = UNASSIGNED_NODE.slice(0); -const osName = (platform, release) => { - if (!platform && release) { - throw new Error('You can\'t specify a `release` without specifying `platform`'); - } + for (var i = 0x81; i <= 0xFE; i++) { + var secondByteNodeIdx = NODE_START - this.decodeTables[0][i]; + var secondByteNode = this.decodeTables[secondByteNodeIdx]; + for (var j = 0x30; j <= 0x39; j++) + secondByteNode[j] = NODE_START - thirdByteNodeIdx; + } + for (var i = 0x81; i <= 0xFE; i++) + thirdByteNode[i] = NODE_START - fourthByteNodeIdx; + for (var i = 0x30; i <= 0x39; i++) + fourthByteNode[i] = GB18030_CODE + } +} - platform = platform || os.platform(); +DBCSCodec.prototype.encoder = DBCSEncoder; +DBCSCodec.prototype.decoder = DBCSDecoder; - let id; +// Decoder helpers +DBCSCodec.prototype._getDecodeTrieNode = function(addr) { + var bytes = []; + for (; addr > 0; addr >>= 8) + bytes.push(addr & 0xFF); + if (bytes.length == 0) + bytes.push(0); - if (platform === 'darwin') { - if (!release && os.platform() === 'darwin') { - release = os.release(); - } + var node = this.decodeTables[0]; + for (var i = bytes.length-1; i > 0; i--) { // Traverse nodes deeper into the trie. + var val = node[bytes[i]]; - const prefix = release ? (Number(release.split('.')[0]) > 15 ? 'macOS' : 'OS X') : 'macOS'; - id = release ? macosRelease(release).name : ''; - return prefix + (id ? ' ' + id : ''); - } + if (val == UNASSIGNED) { // Create new node. + node[bytes[i]] = NODE_START - this.decodeTables.length; + this.decodeTables.push(node = UNASSIGNED_NODE.slice(0)); + } + else if (val <= NODE_START) { // Existing node. + node = this.decodeTables[NODE_START - val]; + } + else + throw new Error("Overwrite byte in " + this.encodingName + ", addr: " + addr.toString(16)); + } + return node; +} - if (platform === 'linux') { - if (!release && os.platform() === 'linux') { - release = os.release(); - } - id = release ? release.replace(/^(\d+\.\d+).*/, '$1') : ''; - return 'Linux' + (id ? ' ' + id : ''); - } +DBCSCodec.prototype._addDecodeChunk = function(chunk) { + // First element of chunk is the hex mbcs code where we start. + var curAddr = parseInt(chunk[0], 16); - if (platform === 'win32') { - if (!release && os.platform() === 'win32') { - release = os.release(); - } + // Choose the decoding node where we'll write our chars. + var writeTable = this._getDecodeTrieNode(curAddr); + curAddr = curAddr & 0xFF; - id = release ? winRelease(release) : ''; - return 'Windows' + (id ? ' ' + id : ''); - } + // Write all other elements of the chunk to the table. + for (var k = 1; k < chunk.length; k++) { + var part = chunk[k]; + if (typeof part === "string") { // String, write as-is. + for (var l = 0; l < part.length;) { + var code = part.charCodeAt(l++); + if (0xD800 <= code && code < 0xDC00) { // Decode surrogate + var codeTrail = part.charCodeAt(l++); + if (0xDC00 <= codeTrail && codeTrail < 0xE000) + writeTable[curAddr++] = 0x10000 + (code - 0xD800) * 0x400 + (codeTrail - 0xDC00); + else + throw new Error("Incorrect surrogate pair in " + this.encodingName + " at chunk " + chunk[0]); + } + else if (0x0FF0 < code && code <= 0x0FFF) { // Character sequence (our own encoding used) + var len = 0xFFF - code + 2; + var seq = []; + for (var m = 0; m < len; m++) + seq.push(part.charCodeAt(l++)); // Simple variation: don't support surrogates or subsequences in seq. - return platform; -}; + writeTable[curAddr++] = SEQ_START - this.decodeTableSeq.length; + this.decodeTableSeq.push(seq); + } + else + writeTable[curAddr++] = code; // Basic char + } + } + else if (typeof part === "number") { // Integer, meaning increasing sequence starting with prev character. + var charCode = writeTable[curAddr - 1] + 1; + for (var l = 0; l < part; l++) + writeTable[curAddr++] = charCode++; + } + else + throw new Error("Incorrect type '" + typeof part + "' given in " + this.encodingName + " at chunk " + chunk[0]); + } + if (curAddr > 0xFF) + throw new Error("Incorrect chunk in " + this.encodingName + " at addr " + chunk[0] + ": too long" + curAddr); +} -module.exports = osName; +// Encoder helpers +DBCSCodec.prototype._getEncodeBucket = function(uCode) { + var high = uCode >> 8; // This could be > 0xFF because of astral characters. + if (this.encodeTable[high] === undefined) + this.encodeTable[high] = UNASSIGNED_NODE.slice(0); // Create bucket on demand. + return this.encodeTable[high]; +} +DBCSCodec.prototype._setEncodeChar = function(uCode, dbcsCode) { + var bucket = this._getEncodeBucket(uCode); + var low = uCode & 0xFF; + if (bucket[low] <= SEQ_START) + this.encodeTableSeq[SEQ_START-bucket[low]][DEF_CHAR] = dbcsCode; // There's already a sequence, set a single-char subsequence of it. + else if (bucket[low] == UNASSIGNED) + bucket[low] = dbcsCode; +} -/***/ }), -/* 3 */ -/***/ (function(module) { +DBCSCodec.prototype._setEncodeSequence = function(seq, dbcsCode) { + + // Get the root of character tree according to first character of the sequence. + var uCode = seq[0]; + var bucket = this._getEncodeBucket(uCode); + var low = uCode & 0xFF; -module.exports = require("console"); + var node; + if (bucket[low] <= SEQ_START) { + // There's already a sequence with - use it. + node = this.encodeTableSeq[SEQ_START-bucket[low]]; + } + else { + // There was no sequence object - allocate a new one. + node = {}; + if (bucket[low] !== UNASSIGNED) node[DEF_CHAR] = bucket[low]; // If a char was set before - make it a single-char subsequence. + bucket[low] = SEQ_START - this.encodeTableSeq.length; + this.encodeTableSeq.push(node); + } -/***/ }), -/* 4 */ -/***/ (function(module) { + // Traverse the character tree, allocating new nodes as needed. + for (var j = 1; j < seq.length-1; j++) { + var oldVal = node[uCode]; + if (typeof oldVal === 'object') + node = oldVal; + else { + node = node[uCode] = {} + if (oldVal !== undefined) + node[DEF_CHAR] = oldVal + } + } -"use strict"; -/*! - * depd - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ + // Set the leaf to given dbcsCode. + uCode = seq[seq.length-1]; + node[uCode] = dbcsCode; +} +DBCSCodec.prototype._fillEncodeTable = function(nodeIdx, prefix, skipEncodeChars) { + var node = this.decodeTables[nodeIdx]; + for (var i = 0; i < 0x100; i++) { + var uCode = node[i]; + var mbCode = prefix + i; + if (skipEncodeChars[mbCode]) + continue; + if (uCode >= 0) + this._setEncodeChar(uCode, mbCode); + else if (uCode <= NODE_START) + this._fillEncodeTable(NODE_START - uCode, mbCode << 8, skipEncodeChars); + else if (uCode <= SEQ_START) + this._setEncodeSequence(this.decodeTableSeq[SEQ_START - uCode], mbCode); + } +} -/** - * Module exports. - * @public - */ -module.exports = eventListenerCount -/** - * Get the count of listeners on an event emitter of a specific type. - */ +// == Encoder ================================================================== -function eventListenerCount (emitter, type) { - return emitter.listeners(type).length +function DBCSEncoder(options, codec) { + // Encoder state + this.leadSurrogate = -1; + this.seqObj = undefined; + + // Static data + this.encodeTable = codec.encodeTable; + this.encodeTableSeq = codec.encodeTableSeq; + this.defaultCharSingleByte = codec.defCharSB; + this.gb18030 = codec.gb18030; } +DBCSEncoder.prototype.write = function(str) { + var newBuf = Buffer.alloc(str.length * (this.gb18030 ? 4 : 3)), + leadSurrogate = this.leadSurrogate, + seqObj = this.seqObj, nextChar = -1, + i = 0, j = 0; -/***/ }), -/* 5 */, -/* 6 */, -/* 7 */, -/* 8 */, -/* 9 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -var once = __webpack_require__(969); + while (true) { + // 0. Get next character. + if (nextChar === -1) { + if (i == str.length) break; + var uCode = str.charCodeAt(i++); + } + else { + var uCode = nextChar; + nextChar = -1; + } -var noop = function() {}; + // 1. Handle surrogates. + if (0xD800 <= uCode && uCode < 0xE000) { // Char is one of surrogates. + if (uCode < 0xDC00) { // We've got lead surrogate. + if (leadSurrogate === -1) { + leadSurrogate = uCode; + continue; + } else { + leadSurrogate = uCode; + // Double lead surrogate found. + uCode = UNASSIGNED; + } + } else { // We've got trail surrogate. + if (leadSurrogate !== -1) { + uCode = 0x10000 + (leadSurrogate - 0xD800) * 0x400 + (uCode - 0xDC00); + leadSurrogate = -1; + } else { + // Incomplete surrogate pair - only trail surrogate found. + uCode = UNASSIGNED; + } + + } + } + else if (leadSurrogate !== -1) { + // Incomplete surrogate pair - only lead surrogate found. + nextChar = uCode; uCode = UNASSIGNED; // Write an error, then current char. + leadSurrogate = -1; + } -var isRequest = function(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -}; + // 2. Convert uCode character. + var dbcsCode = UNASSIGNED; + if (seqObj !== undefined && uCode != UNASSIGNED) { // We are in the middle of the sequence + var resCode = seqObj[uCode]; + if (typeof resCode === 'object') { // Sequence continues. + seqObj = resCode; + continue; -var isChildProcess = function(stream) { - return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3 -}; + } else if (typeof resCode == 'number') { // Sequence finished. Write it. + dbcsCode = resCode; -var eos = function(stream, opts, callback) { - if (typeof opts === 'function') return eos(stream, null, opts); - if (!opts) opts = {}; + } else if (resCode == undefined) { // Current character is not part of the sequence. - callback = once(callback || noop); + // Try default character for this sequence + resCode = seqObj[DEF_CHAR]; + if (resCode !== undefined) { + dbcsCode = resCode; // Found. Write it. + nextChar = uCode; // Current character will be written too in the next iteration. - var ws = stream._writableState; - var rs = stream._readableState; - var readable = opts.readable || (opts.readable !== false && stream.readable); - var writable = opts.writable || (opts.writable !== false && stream.writable); - var cancelled = false; + } else { + // TODO: What if we have no default? (resCode == undefined) + // Then, we should write first char of the sequence as-is and try the rest recursively. + // Didn't do it for now because no encoding has this situation yet. + // Currently, just skip the sequence and write current char. + } + } + seqObj = undefined; + } + else if (uCode >= 0) { // Regular character + var subtable = this.encodeTable[uCode >> 8]; + if (subtable !== undefined) + dbcsCode = subtable[uCode & 0xFF]; + + if (dbcsCode <= SEQ_START) { // Sequence start + seqObj = this.encodeTableSeq[SEQ_START-dbcsCode]; + continue; + } - var onlegacyfinish = function() { - if (!stream.writable) onfinish(); - }; + if (dbcsCode == UNASSIGNED && this.gb18030) { + // Use GB18030 algorithm to find character(s) to write. + var idx = findIdx(this.gb18030.uChars, uCode); + if (idx != -1) { + var dbcsCode = this.gb18030.gbChars[idx] + (uCode - this.gb18030.uChars[idx]); + newBuf[j++] = 0x81 + Math.floor(dbcsCode / 12600); dbcsCode = dbcsCode % 12600; + newBuf[j++] = 0x30 + Math.floor(dbcsCode / 1260); dbcsCode = dbcsCode % 1260; + newBuf[j++] = 0x81 + Math.floor(dbcsCode / 10); dbcsCode = dbcsCode % 10; + newBuf[j++] = 0x30 + dbcsCode; + continue; + } + } + } - var onfinish = function() { - writable = false; - if (!readable) callback.call(stream); - }; + // 3. Write dbcsCode character. + if (dbcsCode === UNASSIGNED) + dbcsCode = this.defaultCharSingleByte; + + if (dbcsCode < 0x100) { + newBuf[j++] = dbcsCode; + } + else if (dbcsCode < 0x10000) { + newBuf[j++] = dbcsCode >> 8; // high byte + newBuf[j++] = dbcsCode & 0xFF; // low byte + } + else { + newBuf[j++] = dbcsCode >> 16; + newBuf[j++] = (dbcsCode >> 8) & 0xFF; + newBuf[j++] = dbcsCode & 0xFF; + } + } - var onend = function() { - readable = false; - if (!writable) callback.call(stream); - }; + this.seqObj = seqObj; + this.leadSurrogate = leadSurrogate; + return newBuf.slice(0, j); +} - var onexit = function(exitCode) { - callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null); - }; +DBCSEncoder.prototype.end = function() { + if (this.leadSurrogate === -1 && this.seqObj === undefined) + return; // All clean. Most often case. - var onerror = function(err) { - callback.call(stream, err); - }; + var newBuf = Buffer.alloc(10), j = 0; - var onclose = function() { - process.nextTick(onclosenexttick); - }; + if (this.seqObj) { // We're in the sequence. + var dbcsCode = this.seqObj[DEF_CHAR]; + if (dbcsCode !== undefined) { // Write beginning of the sequence. + if (dbcsCode < 0x100) { + newBuf[j++] = dbcsCode; + } + else { + newBuf[j++] = dbcsCode >> 8; // high byte + newBuf[j++] = dbcsCode & 0xFF; // low byte + } + } else { + // See todo above. + } + this.seqObj = undefined; + } - var onclosenexttick = function() { - if (cancelled) return; - if (readable && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream, new Error('premature close')); - if (writable && !(ws && (ws.ended && !ws.destroyed))) return callback.call(stream, new Error('premature close')); - }; + if (this.leadSurrogate !== -1) { + // Incomplete surrogate pair - only lead surrogate found. + newBuf[j++] = this.defaultCharSingleByte; + this.leadSurrogate = -1; + } + + return newBuf.slice(0, j); +} - var onrequest = function() { - stream.req.on('finish', onfinish); - }; +// Export for testing +DBCSEncoder.prototype.findIdx = findIdx; - if (isRequest(stream)) { - stream.on('complete', onfinish); - stream.on('abort', onclose); - if (stream.req) onrequest(); - else stream.on('request', onrequest); - } else if (writable && !ws) { // legacy streams - stream.on('end', onlegacyfinish); - stream.on('close', onlegacyfinish); - } - if (isChildProcess(stream)) stream.on('exit', onexit); +// == Decoder ================================================================== - stream.on('end', onend); - stream.on('finish', onfinish); - if (opts.error !== false) stream.on('error', onerror); - stream.on('close', onclose); +function DBCSDecoder(options, codec) { + // Decoder state + this.nodeIdx = 0; + this.prevBuf = Buffer.alloc(0); - return function() { - cancelled = true; - stream.removeListener('complete', onfinish); - stream.removeListener('abort', onclose); - stream.removeListener('request', onrequest); - if (stream.req) stream.req.removeListener('finish', onfinish); - stream.removeListener('end', onlegacyfinish); - stream.removeListener('close', onlegacyfinish); - stream.removeListener('finish', onfinish); - stream.removeListener('exit', onexit); - stream.removeListener('end', onend); - stream.removeListener('error', onerror); - stream.removeListener('close', onclose); - }; -}; + // Static data + this.decodeTables = codec.decodeTables; + this.decodeTableSeq = codec.decodeTableSeq; + this.defaultCharUnicode = codec.defaultCharUnicode; + this.gb18030 = codec.gb18030; +} + +DBCSDecoder.prototype.write = function(buf) { + var newBuf = Buffer.alloc(buf.length*2), + nodeIdx = this.nodeIdx, + prevBuf = this.prevBuf, prevBufOffset = this.prevBuf.length, + seqStart = -this.prevBuf.length, // idx of the start of current parsed sequence. + uCode; + + if (prevBufOffset > 0) // Make prev buf overlap a little to make it easier to slice later. + prevBuf = Buffer.concat([prevBuf, buf.slice(0, 10)]); + + for (var i = 0, j = 0; i < buf.length; i++) { + var curByte = (i >= 0) ? buf[i] : prevBuf[i + prevBufOffset]; + + // Lookup in current trie node. + var uCode = this.decodeTables[nodeIdx][curByte]; + + if (uCode >= 0) { + // Normal character, just use it. + } + else if (uCode === UNASSIGNED) { // Unknown char. + // TODO: Callback with seq. + //var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset); + i = seqStart; // Try to parse again, after skipping first byte of the sequence ('i' will be incremented by 'for' cycle). + uCode = this.defaultCharUnicode.charCodeAt(0); + } + else if (uCode === GB18030_CODE) { + var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset); + var ptr = (curSeq[0]-0x81)*12600 + (curSeq[1]-0x30)*1260 + (curSeq[2]-0x81)*10 + (curSeq[3]-0x30); + var idx = findIdx(this.gb18030.gbChars, ptr); + uCode = this.gb18030.uChars[idx] + ptr - this.gb18030.gbChars[idx]; + } + else if (uCode <= NODE_START) { // Go to next trie node. + nodeIdx = NODE_START - uCode; + continue; + } + else if (uCode <= SEQ_START) { // Output a sequence of chars. + var seq = this.decodeTableSeq[SEQ_START - uCode]; + for (var k = 0; k < seq.length - 1; k++) { + uCode = seq[k]; + newBuf[j++] = uCode & 0xFF; + newBuf[j++] = uCode >> 8; + } + uCode = seq[seq.length-1]; + } + else + throw new Error("iconv-lite internal error: invalid decoding table value " + uCode + " at " + nodeIdx + "/" + curByte); + + // Write the character to buffer, handling higher planes using surrogate pair. + if (uCode > 0xFFFF) { + uCode -= 0x10000; + var uCodeLead = 0xD800 + Math.floor(uCode / 0x400); + newBuf[j++] = uCodeLead & 0xFF; + newBuf[j++] = uCodeLead >> 8; + + uCode = 0xDC00 + uCode % 0x400; + } + newBuf[j++] = uCode & 0xFF; + newBuf[j++] = uCode >> 8; + + // Reset trie node. + nodeIdx = 0; seqStart = i+1; + } + + this.nodeIdx = nodeIdx; + this.prevBuf = (seqStart >= 0) ? buf.slice(seqStart) : prevBuf.slice(seqStart + prevBufOffset); + return newBuf.slice(0, j).toString('ucs2'); +} + +DBCSDecoder.prototype.end = function() { + var ret = ''; + + // Try to parse all remaining chars. + while (this.prevBuf.length > 0) { + // Skip 1 character in the buffer. + ret += this.defaultCharUnicode; + var buf = this.prevBuf.slice(1); + + // Parse remaining as usual. + this.prevBuf = Buffer.alloc(0); + this.nodeIdx = 0; + if (buf.length > 0) + ret += this.write(buf); + } + + this.nodeIdx = 0; + return ret; +} + +// Binary search for GB18030. Returns largest i such that table[i] <= val. +function findIdx(table, val) { + if (table[0] > val) + return -1; + + var l = 0, r = table.length; + while (l < r-1) { // always table[l] <= val < table[r] + var mid = l + Math.floor((r-l+1)/2); + if (table[mid] <= val) + l = mid; + else + r = mid; + } + return l; +} -module.exports = eos; /***/ }), -/* 10 */ +/* 2 */ /***/ (function(module, __unusedexports, __webpack_require__) { -var baseGetTag = __webpack_require__(51), - isObject = __webpack_require__(398); +"use strict"; + +const os = __webpack_require__(87); +const macosRelease = __webpack_require__(118); +const winRelease = __webpack_require__(494); -/** `Object#toString` result references. */ -var asyncTag = '[object AsyncFunction]', - funcTag = '[object Function]', - genTag = '[object GeneratorFunction]', - proxyTag = '[object Proxy]'; +const osName = (platform, release) => { + if (!platform && release) { + throw new Error('You can\'t specify a `release` without specifying `platform`'); + } + + platform = platform || os.platform(); + + let id; + + if (platform === 'darwin') { + if (!release && os.platform() === 'darwin') { + release = os.release(); + } + + const prefix = release ? (Number(release.split('.')[0]) > 15 ? 'macOS' : 'OS X') : 'macOS'; + id = release ? macosRelease(release).name : ''; + return prefix + (id ? ' ' + id : ''); + } + if (platform === 'linux') { + if (!release && os.platform() === 'linux') { + release = os.release(); + } + + id = release ? release.replace(/^(\d+\.\d+).*/, '$1') : ''; + return 'Linux' + (id ? ' ' + id : ''); + } + + if (platform === 'win32') { + if (!release && os.platform() === 'win32') { + release = os.release(); + } + + id = release ? winRelease(release) : ''; + return 'Windows' + (id ? ' ' + id : ''); + } + + return platform; +}; + +module.exports = osName; + + +/***/ }), +/* 3 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +Object.defineProperty(exports, "__esModule", { value: true }); +var hub_1 = __webpack_require__(698); +exports.TRACEPARENT_REGEXP = new RegExp('^[ \\t]*' + // whitespace + '([0-9a-f]{32})?' + // trace_id + '-?([0-9a-f]{16})?' + // span_id + '-?([01])?' + // sampled + '[ \\t]*$'); /** - * Checks if `value` is classified as a `Function` object. + * Determines if tracing is currently enabled. * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example + * Tracing is enabled when at least one of `tracesSampleRate` and `tracesSampler` is defined in the SDK config. + */ +function hasTracingEnabled(options) { + return 'tracesSampleRate' in options || 'tracesSampler' in options; +} +exports.hasTracingEnabled = hasTracingEnabled; +/** + * Extract transaction context data from a `sentry-trace` header. * - * _.isFunction(_); - * // => true + * @param traceparent Traceparent string * - * _.isFunction(/abc/); - * // => false + * @returns Object containing data from the header, or undefined if traceparent string is malformed */ -function isFunction(value) { - if (!isObject(value)) { - return false; +function extractTraceparentData(traceparent) { + var matches = traceparent.match(exports.TRACEPARENT_REGEXP); + if (matches) { + var parentSampled = void 0; + if (matches[3] === '1') { + parentSampled = true; + } + else if (matches[3] === '0') { + parentSampled = false; + } + return { + traceId: matches[1], + parentSampled: parentSampled, + parentSpanId: matches[2], + }; + } + return undefined; +} +exports.extractTraceparentData = extractTraceparentData; +/** Grabs active transaction off scope, if any */ +function getActiveTransaction(hub) { + if (hub === void 0) { hub = hub_1.getCurrentHub(); } + var _a, _b; + return (_b = (_a = hub) === null || _a === void 0 ? void 0 : _a.getScope()) === null || _b === void 0 ? void 0 : _b.getTransaction(); +} +exports.getActiveTransaction = getActiveTransaction; +/** + * Converts from milliseconds to seconds + * @param time time in ms + */ +function msToSec(time) { + return time / 1000; +} +exports.msToSec = msToSec; +/** + * Converts from seconds to milliseconds + * @param time time in seconds + */ +function secToMs(time) { + return time * 1000; +} +exports.secToMs = secToMs; +// so it can be used in manual instrumentation without necessitating a hard dependency on @sentry/utils +var utils_1 = __webpack_require__(657); +exports.stripUrlQueryAndFragment = utils_1.stripUrlQueryAndFragment; +//# sourceMappingURL=utils.js.map + +/***/ }), +/* 4 */ +/***/ (function(module) { + +"use strict"; +/*! + * depd + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + + + +/** + * Module exports. + * @public + */ + +module.exports = eventListenerCount + +/** + * Get the count of listeners on an event emitter of a specific type. + */ + +function eventListenerCount (emitter, type) { + return emitter.listeners(type).length +} + + +/***/ }), +/* 5 */, +/* 6 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getOctokitThrottleOptions = void 0; +const bottleneck_1 = __importDefault(__webpack_require__(76)); +const ioredis_1 = __importDefault(__webpack_require__(545)); +function getOctokitThrottleOptions(options) { + if (!options.redisConfig && !process.env.REDIS_URL) + return; + const connection = new bottleneck_1.default.IORedisConnection({ + client: getRedisClient(options.redisConfig), + }); + connection.on("error", (error) => { + options.log.error(Object.assign(error, { source: "bottleneck" })); + }); + return { + Bottleneck: bottleneck_1.default, + connection, + }; +} +exports.getOctokitThrottleOptions = getOctokitThrottleOptions; +function getRedisClient(redisConfig) { + if (redisConfig) + return new ioredis_1.default(redisConfig); + if (process.env.REDIS_URL) + return new ioredis_1.default(process.env.REDIS_URL); +} +//# sourceMappingURL=get-octokit-throttle-options.js.map + +/***/ }), +/* 7 */ +/***/ (function(__unusedmodule, exports) { + +Object.defineProperty(exports, "__esModule", { value: true }); +exports.setPrototypeOf = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array ? setProtoOf : mixinProperties); +/** + * setPrototypeOf polyfill using __proto__ + */ +// eslint-disable-next-line @typescript-eslint/ban-types +function setProtoOf(obj, proto) { + // @ts-ignore __proto__ does not exist on obj + obj.__proto__ = proto; + return obj; +} +/** + * setPrototypeOf polyfill using mixin + */ +// eslint-disable-next-line @typescript-eslint/ban-types +function mixinProperties(obj, proto) { + for (var prop in proto) { + // eslint-disable-next-line no-prototype-builtins + if (!obj.hasOwnProperty(prop)) { + // @ts-ignore typescript complains about indexing so we remove + obj[prop] = proto[prop]; + } + } + return obj; +} +//# sourceMappingURL=polyfill.js.map + +/***/ }), +/* 8 */, +/* 9 */ +/***/ (function(module, exports, __webpack_require__) { + +/* eslint-disable node/no-deprecated-api */ +var buffer = __webpack_require__(293) +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] } - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 9 which returns 'object' for typed arrays and other constructors. - var tag = baseGetTag(value); - return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf } -module.exports = isFunction; +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} /***/ }), +/* 10 */, /* 11 */ /***/ (function(module) { @@ -466,8 +972,98 @@ module.exports = { /***/ }), -/* 14 */, -/* 15 */, +/* 14 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getLoggingMiddleware = void 0; +const pino_http_1 = __importDefault(__webpack_require__(627)); +const uuid_1 = __webpack_require__(699); +function getLoggingMiddleware(logger) { + return pino_http_1.default({ + logger: logger.child({ name: "http" }), + customSuccessMessage(res) { + const responseTime = Date.now() - res[pino_http_1.default.startTime]; + // @ts-ignore + const route = `${res.req.method} ${res.req.url} ${res.statusCode} - ${responseTime}ms`; + return route; + }, + genReqId: (req) => req.headers["x-request-id"] || + req.headers["x-github-delivery"] || + uuid_1.v4(), + }); +} +exports.getLoggingMiddleware = getLoggingMiddleware; +//# sourceMappingURL=logging-middleware.js.map + +/***/ }), +/* 15 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, '__esModule', { value: true }); + +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } + +var deprecation = __webpack_require__(692); +var once = _interopDefault(__webpack_require__(49)); + +const logOnce = once(deprecation => console.warn(deprecation)); +/** + * Error with extra properties to help with debugging + */ + +class RequestError extends Error { + constructor(message, statusCode, options) { + super(message); // Maintains proper stack trace (only available on V8) + + /* istanbul ignore next */ + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + + this.name = "HttpError"; + this.status = statusCode; + Object.defineProperty(this, "code", { + get() { + logOnce(new deprecation.Deprecation("[@octokit/request-error] `error.code` is deprecated, use `error.status`.")); + return statusCode; + } + + }); + this.headers = options.headers || {}; // redact request credentials without mutating original request options + + const requestCopy = Object.assign({}, options.request); + + if (options.request.headers.authorization) { + requestCopy.headers = Object.assign({}, options.request.headers, { + authorization: options.request.headers.authorization.replace(/ .*$/, " [REDACTED]") + }); + } + + requestCopy.url = requestCopy.url // client_id & client_secret can be passed as URL query parameters to increase rate limit + // see https://developer.github.com/v3/#increasing-the-unauthenticated-rate-limit-for-oauth-applications + .replace(/\bclient_secret=\w+/g, "client_secret=[REDACTED]") // OAuth tokens can be passed as URL query parameters, although it is not recommended + // see https://developer.github.com/v3/#oauth2-token-sent-in-a-header + .replace(/\baccess_token=\w+/g, "access_token=[REDACTED]"); + this.request = requestCopy; + } + +} + +exports.RequestError = RequestError; +//# sourceMappingURL=index.js.map + + +/***/ }), /* 16 */ /***/ (function(module) { @@ -482,7 +1078,12 @@ module.exports = eval("require")("encoding"); /***/ }), -/* 19 */, +/* 19 */ +/***/ (function(module) { + +module.exports = {"blacklist_client.lua":"local blacklist = ARGV[num_static_argv + 1]\n\nif redis.call('zscore', client_last_seen_key, blacklist) then\n redis.call('zadd', client_last_seen_key, 0, blacklist)\nend\n\n\nreturn {}\n","check.lua":"local weight = tonumber(ARGV[num_static_argv + 1])\n\nlocal capacity = process_tick(now, false)['capacity']\nlocal nextRequest = tonumber(redis.call('hget', settings_key, 'nextRequest'))\n\nreturn conditions_check(capacity, weight) and nextRequest - now <= 0\n","conditions_check.lua":"local conditions_check = function (capacity, weight)\n return capacity == nil or weight <= capacity\nend\n","current_reservoir.lua":"return process_tick(now, false)['reservoir']\n","done.lua":"process_tick(now, false)\n\nreturn tonumber(redis.call('hget', settings_key, 'done'))\n","free.lua":"local index = ARGV[num_static_argv + 1]\n\nredis.call('zadd', job_expirations_key, 0, index)\n\nreturn process_tick(now, false)['running']\n","get_time.lua":"redis.replicate_commands()\n\nlocal get_time = function ()\n local time = redis.call('time')\n\n return tonumber(time[1]..string.sub(time[2], 1, 3))\nend\n","group_check.lua":"return not (redis.call('exists', settings_key) == 1)\n","heartbeat.lua":"process_tick(now, true)\n","increment_reservoir.lua":"local incr = tonumber(ARGV[num_static_argv + 1])\n\nredis.call('hincrby', settings_key, 'reservoir', incr)\n\nlocal reservoir = process_tick(now, true)['reservoir']\n\nlocal groupTimeout = tonumber(redis.call('hget', settings_key, 'groupTimeout'))\nrefresh_expiration(0, 0, groupTimeout)\n\nreturn reservoir\n","init.lua":"local clear = tonumber(ARGV[num_static_argv + 1])\nlocal limiter_version = ARGV[num_static_argv + 2]\nlocal num_local_argv = num_static_argv + 2\n\nif clear == 1 then\n redis.call('del', unpack(KEYS))\nend\n\nif redis.call('exists', settings_key) == 0 then\n -- Create\n local args = {'hmset', settings_key}\n\n for i = num_local_argv + 1, #ARGV do\n table.insert(args, ARGV[i])\n end\n\n redis.call(unpack(args))\n redis.call('hmset', settings_key,\n 'nextRequest', now,\n 'lastReservoirRefresh', now,\n 'lastReservoirIncrease', now,\n 'running', 0,\n 'done', 0,\n 'unblockTime', 0,\n 'capacityPriorityCounter', 0\n )\n\nelse\n -- Apply migrations\n local settings = redis.call('hmget', settings_key,\n 'id',\n 'version'\n )\n local id = settings[1]\n local current_version = settings[2]\n\n if current_version ~= limiter_version then\n local version_digits = {}\n for k, v in string.gmatch(current_version, \"([^.]+)\") do\n table.insert(version_digits, tonumber(k))\n end\n\n -- 2.10.0\n if version_digits[2] < 10 then\n redis.call('hsetnx', settings_key, 'reservoirRefreshInterval', '')\n redis.call('hsetnx', settings_key, 'reservoirRefreshAmount', '')\n redis.call('hsetnx', settings_key, 'lastReservoirRefresh', '')\n redis.call('hsetnx', settings_key, 'done', 0)\n redis.call('hset', settings_key, 'version', '2.10.0')\n end\n\n -- 2.11.1\n if version_digits[2] < 11 or (version_digits[2] == 11 and version_digits[3] < 1) then\n if redis.call('hstrlen', settings_key, 'lastReservoirRefresh') == 0 then\n redis.call('hmset', settings_key,\n 'lastReservoirRefresh', now,\n 'version', '2.11.1'\n )\n end\n end\n\n -- 2.14.0\n if version_digits[2] < 14 then\n local old_running_key = 'b_'..id..'_running'\n local old_executing_key = 'b_'..id..'_executing'\n\n if redis.call('exists', old_running_key) == 1 then\n redis.call('rename', old_running_key, job_weights_key)\n end\n if redis.call('exists', old_executing_key) == 1 then\n redis.call('rename', old_executing_key, job_expirations_key)\n end\n redis.call('hset', settings_key, 'version', '2.14.0')\n end\n\n -- 2.15.2\n if version_digits[2] < 15 or (version_digits[2] == 15 and version_digits[3] < 2) then\n redis.call('hsetnx', settings_key, 'capacityPriorityCounter', 0)\n redis.call('hset', settings_key, 'version', '2.15.2')\n end\n\n -- 2.17.0\n if version_digits[2] < 17 then\n redis.call('hsetnx', settings_key, 'clientTimeout', 10000)\n redis.call('hset', settings_key, 'version', '2.17.0')\n end\n\n -- 2.18.0\n if version_digits[2] < 18 then\n redis.call('hsetnx', settings_key, 'reservoirIncreaseInterval', '')\n redis.call('hsetnx', settings_key, 'reservoirIncreaseAmount', '')\n redis.call('hsetnx', settings_key, 'reservoirIncreaseMaximum', '')\n redis.call('hsetnx', settings_key, 'lastReservoirIncrease', now)\n redis.call('hset', settings_key, 'version', '2.18.0')\n end\n\n end\n\n process_tick(now, false)\nend\n\nlocal groupTimeout = tonumber(redis.call('hget', settings_key, 'groupTimeout'))\nrefresh_expiration(0, 0, groupTimeout)\n\nreturn {}\n","process_tick.lua":"local process_tick = function (now, always_publish)\n\n local compute_capacity = function (maxConcurrent, running, reservoir)\n if maxConcurrent ~= nil and reservoir ~= nil then\n return math.min((maxConcurrent - running), reservoir)\n elseif maxConcurrent ~= nil then\n return maxConcurrent - running\n elseif reservoir ~= nil then\n return reservoir\n else\n return nil\n end\n end\n\n local settings = redis.call('hmget', settings_key,\n 'id',\n 'maxConcurrent',\n 'running',\n 'reservoir',\n 'reservoirRefreshInterval',\n 'reservoirRefreshAmount',\n 'lastReservoirRefresh',\n 'reservoirIncreaseInterval',\n 'reservoirIncreaseAmount',\n 'reservoirIncreaseMaximum',\n 'lastReservoirIncrease',\n 'capacityPriorityCounter',\n 'clientTimeout'\n )\n local id = settings[1]\n local maxConcurrent = tonumber(settings[2])\n local running = tonumber(settings[3])\n local reservoir = tonumber(settings[4])\n local reservoirRefreshInterval = tonumber(settings[5])\n local reservoirRefreshAmount = tonumber(settings[6])\n local lastReservoirRefresh = tonumber(settings[7])\n local reservoirIncreaseInterval = tonumber(settings[8])\n local reservoirIncreaseAmount = tonumber(settings[9])\n local reservoirIncreaseMaximum = tonumber(settings[10])\n local lastReservoirIncrease = tonumber(settings[11])\n local capacityPriorityCounter = tonumber(settings[12])\n local clientTimeout = tonumber(settings[13])\n\n local initial_capacity = compute_capacity(maxConcurrent, running, reservoir)\n\n --\n -- Process 'running' changes\n --\n local expired = redis.call('zrangebyscore', job_expirations_key, '-inf', '('..now)\n\n if #expired > 0 then\n redis.call('zremrangebyscore', job_expirations_key, '-inf', '('..now)\n\n local flush_batch = function (batch, acc)\n local weights = redis.call('hmget', job_weights_key, unpack(batch))\n redis.call('hdel', job_weights_key, unpack(batch))\n local clients = redis.call('hmget', job_clients_key, unpack(batch))\n redis.call('hdel', job_clients_key, unpack(batch))\n\n -- Calculate sum of removed weights\n for i = 1, #weights do\n acc['total'] = acc['total'] + (tonumber(weights[i]) or 0)\n end\n\n -- Calculate sum of removed weights by client\n local client_weights = {}\n for i = 1, #clients do\n local removed = tonumber(weights[i]) or 0\n if removed > 0 then\n acc['client_weights'][clients[i]] = (acc['client_weights'][clients[i]] or 0) + removed\n end\n end\n end\n\n local acc = {\n ['total'] = 0,\n ['client_weights'] = {}\n }\n local batch_size = 1000\n\n -- Compute changes to Zsets and apply changes to Hashes\n for i = 1, #expired, batch_size do\n local batch = {}\n for j = i, math.min(i + batch_size - 1, #expired) do\n table.insert(batch, expired[j])\n end\n\n flush_batch(batch, acc)\n end\n\n -- Apply changes to Zsets\n if acc['total'] > 0 then\n redis.call('hincrby', settings_key, 'done', acc['total'])\n running = tonumber(redis.call('hincrby', settings_key, 'running', -acc['total']))\n end\n\n for client, weight in pairs(acc['client_weights']) do\n redis.call('zincrby', client_running_key, -weight, client)\n end\n end\n\n --\n -- Process 'reservoir' changes\n --\n local reservoirRefreshActive = reservoirRefreshInterval ~= nil and reservoirRefreshAmount ~= nil\n if reservoirRefreshActive and now >= lastReservoirRefresh + reservoirRefreshInterval then\n reservoir = reservoirRefreshAmount\n redis.call('hmset', settings_key,\n 'reservoir', reservoir,\n 'lastReservoirRefresh', now\n )\n end\n\n local reservoirIncreaseActive = reservoirIncreaseInterval ~= nil and reservoirIncreaseAmount ~= nil\n if reservoirIncreaseActive and now >= lastReservoirIncrease + reservoirIncreaseInterval then\n local num_intervals = math.floor((now - lastReservoirIncrease) / reservoirIncreaseInterval)\n local incr = reservoirIncreaseAmount * num_intervals\n if reservoirIncreaseMaximum ~= nil then\n incr = math.min(incr, reservoirIncreaseMaximum - (reservoir or 0))\n end\n if incr > 0 then\n reservoir = (reservoir or 0) + incr\n end\n redis.call('hmset', settings_key,\n 'reservoir', reservoir,\n 'lastReservoirIncrease', lastReservoirIncrease + (num_intervals * reservoirIncreaseInterval)\n )\n end\n\n --\n -- Clear unresponsive clients\n --\n local unresponsive = redis.call('zrangebyscore', client_last_seen_key, '-inf', (now - clientTimeout))\n local unresponsive_lookup = {}\n local terminated_clients = {}\n for i = 1, #unresponsive do\n unresponsive_lookup[unresponsive[i]] = true\n if tonumber(redis.call('zscore', client_running_key, unresponsive[i])) == 0 then\n table.insert(terminated_clients, unresponsive[i])\n end\n end\n if #terminated_clients > 0 then\n redis.call('zrem', client_running_key, unpack(terminated_clients))\n redis.call('hdel', client_num_queued_key, unpack(terminated_clients))\n redis.call('zrem', client_last_registered_key, unpack(terminated_clients))\n redis.call('zrem', client_last_seen_key, unpack(terminated_clients))\n end\n\n --\n -- Broadcast capacity changes\n --\n local final_capacity = compute_capacity(maxConcurrent, running, reservoir)\n\n if always_publish or (initial_capacity ~= nil and final_capacity == nil) then\n -- always_publish or was not unlimited, now unlimited\n redis.call('publish', 'b_'..id, 'capacity:'..(final_capacity or ''))\n\n elseif initial_capacity ~= nil and final_capacity ~= nil and final_capacity > initial_capacity then\n -- capacity was increased\n -- send the capacity message to the limiter having the lowest number of running jobs\n -- the tiebreaker is the limiter having not registered a job in the longest time\n\n local lowest_concurrency_value = nil\n local lowest_concurrency_clients = {}\n local lowest_concurrency_last_registered = {}\n local client_concurrencies = redis.call('zrange', client_running_key, 0, -1, 'withscores')\n\n for i = 1, #client_concurrencies, 2 do\n local client = client_concurrencies[i]\n local concurrency = tonumber(client_concurrencies[i+1])\n\n if (\n lowest_concurrency_value == nil or lowest_concurrency_value == concurrency\n ) and (\n not unresponsive_lookup[client]\n ) and (\n tonumber(redis.call('hget', client_num_queued_key, client)) > 0\n ) then\n lowest_concurrency_value = concurrency\n table.insert(lowest_concurrency_clients, client)\n local last_registered = tonumber(redis.call('zscore', client_last_registered_key, client))\n table.insert(lowest_concurrency_last_registered, last_registered)\n end\n end\n\n if #lowest_concurrency_clients > 0 then\n local position = 1\n local earliest = lowest_concurrency_last_registered[1]\n\n for i,v in ipairs(lowest_concurrency_last_registered) do\n if v < earliest then\n position = i\n earliest = v\n end\n end\n\n local next_client = lowest_concurrency_clients[position]\n redis.call('publish', 'b_'..id,\n 'capacity-priority:'..(final_capacity or '')..\n ':'..next_client..\n ':'..capacityPriorityCounter\n )\n redis.call('hincrby', settings_key, 'capacityPriorityCounter', '1')\n else\n redis.call('publish', 'b_'..id, 'capacity:'..(final_capacity or ''))\n end\n end\n\n return {\n ['capacity'] = final_capacity,\n ['running'] = running,\n ['reservoir'] = reservoir\n }\nend\n","queued.lua":"local clientTimeout = tonumber(redis.call('hget', settings_key, 'clientTimeout'))\nlocal valid_clients = redis.call('zrangebyscore', client_last_seen_key, (now - clientTimeout), 'inf')\nlocal client_queued = redis.call('hmget', client_num_queued_key, unpack(valid_clients))\n\nlocal sum = 0\nfor i = 1, #client_queued do\n sum = sum + tonumber(client_queued[i])\nend\n\nreturn sum\n","refresh_expiration.lua":"local refresh_expiration = function (now, nextRequest, groupTimeout)\n\n if groupTimeout ~= nil then\n local ttl = (nextRequest + groupTimeout) - now\n\n for i = 1, #KEYS do\n redis.call('pexpire', KEYS[i], ttl)\n end\n end\n\nend\n","refs.lua":"local settings_key = KEYS[1]\nlocal job_weights_key = KEYS[2]\nlocal job_expirations_key = KEYS[3]\nlocal job_clients_key = KEYS[4]\nlocal client_running_key = KEYS[5]\nlocal client_num_queued_key = KEYS[6]\nlocal client_last_registered_key = KEYS[7]\nlocal client_last_seen_key = KEYS[8]\n\nlocal now = tonumber(ARGV[1])\nlocal client = ARGV[2]\n\nlocal num_static_argv = 2\n","register.lua":"local index = ARGV[num_static_argv + 1]\nlocal weight = tonumber(ARGV[num_static_argv + 2])\nlocal expiration = tonumber(ARGV[num_static_argv + 3])\n\nlocal state = process_tick(now, false)\nlocal capacity = state['capacity']\nlocal reservoir = state['reservoir']\n\nlocal settings = redis.call('hmget', settings_key,\n 'nextRequest',\n 'minTime',\n 'groupTimeout'\n)\nlocal nextRequest = tonumber(settings[1])\nlocal minTime = tonumber(settings[2])\nlocal groupTimeout = tonumber(settings[3])\n\nif conditions_check(capacity, weight) then\n\n redis.call('hincrby', settings_key, 'running', weight)\n redis.call('hset', job_weights_key, index, weight)\n if expiration ~= nil then\n redis.call('zadd', job_expirations_key, now + expiration, index)\n end\n redis.call('hset', job_clients_key, index, client)\n redis.call('zincrby', client_running_key, weight, client)\n redis.call('hincrby', client_num_queued_key, client, -1)\n redis.call('zadd', client_last_registered_key, now, client)\n\n local wait = math.max(nextRequest - now, 0)\n local newNextRequest = now + wait + minTime\n\n if reservoir == nil then\n redis.call('hset', settings_key,\n 'nextRequest', newNextRequest\n )\n else\n reservoir = reservoir - weight\n redis.call('hmset', settings_key,\n 'reservoir', reservoir,\n 'nextRequest', newNextRequest\n )\n end\n\n refresh_expiration(now, newNextRequest, groupTimeout)\n\n return {true, wait, reservoir}\n\nelse\n return {false}\nend\n","register_client.lua":"local queued = tonumber(ARGV[num_static_argv + 1])\n\n-- Could have been re-registered concurrently\nif not redis.call('zscore', client_last_seen_key, client) then\n redis.call('zadd', client_running_key, 0, client)\n redis.call('hset', client_num_queued_key, client, queued)\n redis.call('zadd', client_last_registered_key, 0, client)\nend\n\nredis.call('zadd', client_last_seen_key, now, client)\n\nreturn {}\n","running.lua":"return process_tick(now, false)['running']\n","submit.lua":"local queueLength = tonumber(ARGV[num_static_argv + 1])\nlocal weight = tonumber(ARGV[num_static_argv + 2])\n\nlocal capacity = process_tick(now, false)['capacity']\n\nlocal settings = redis.call('hmget', settings_key,\n 'id',\n 'maxConcurrent',\n 'highWater',\n 'nextRequest',\n 'strategy',\n 'unblockTime',\n 'penalty',\n 'minTime',\n 'groupTimeout'\n)\nlocal id = settings[1]\nlocal maxConcurrent = tonumber(settings[2])\nlocal highWater = tonumber(settings[3])\nlocal nextRequest = tonumber(settings[4])\nlocal strategy = tonumber(settings[5])\nlocal unblockTime = tonumber(settings[6])\nlocal penalty = tonumber(settings[7])\nlocal minTime = tonumber(settings[8])\nlocal groupTimeout = tonumber(settings[9])\n\nif maxConcurrent ~= nil and weight > maxConcurrent then\n return redis.error_reply('OVERWEIGHT:'..weight..':'..maxConcurrent)\nend\n\nlocal reachedHWM = (highWater ~= nil and queueLength == highWater\n and not (\n conditions_check(capacity, weight)\n and nextRequest - now <= 0\n )\n)\n\nlocal blocked = strategy == 3 and (reachedHWM or unblockTime >= now)\n\nif blocked then\n local computedPenalty = penalty\n if computedPenalty == nil then\n if minTime == 0 then\n computedPenalty = 5000\n else\n computedPenalty = 15 * minTime\n end\n end\n\n local newNextRequest = now + computedPenalty + minTime\n\n redis.call('hmset', settings_key,\n 'unblockTime', now + computedPenalty,\n 'nextRequest', newNextRequest\n )\n\n local clients_queued_reset = redis.call('hkeys', client_num_queued_key)\n local queued_reset = {}\n for i = 1, #clients_queued_reset do\n table.insert(queued_reset, clients_queued_reset[i])\n table.insert(queued_reset, 0)\n end\n redis.call('hmset', client_num_queued_key, unpack(queued_reset))\n\n redis.call('publish', 'b_'..id, 'blocked:')\n\n refresh_expiration(now, newNextRequest, groupTimeout)\nend\n\nif not blocked and not reachedHWM then\n redis.call('hincrby', client_num_queued_key, client, 1)\nend\n\nreturn {reachedHWM, blocked, strategy}\n","update_settings.lua":"local args = {'hmset', settings_key}\n\nfor i = num_static_argv + 1, #ARGV do\n table.insert(args, ARGV[i])\nend\n\nredis.call(unpack(args))\n\nprocess_tick(now, true)\n\nlocal groupTimeout = tonumber(redis.call('hget', settings_key, 'groupTimeout'))\nrefresh_expiration(0, 0, groupTimeout)\n\nreturn {}\n","validate_client.lua":"if not redis.call('zscore', client_last_seen_key, client) then\n return redis.error_reply('UNKNOWN_CLIENT')\nend\n\nredis.call('zadd', client_last_seen_key, now, client)\n","validate_keys.lua":"if not (redis.call('exists', settings_key) == 1) then\n return redis.error_reply('SETTINGS_KEY_NOT_FOUND')\nend\n"}; + +/***/ }), /* 20 */ /***/ (function(module, __unusedexports, __webpack_require__) { @@ -529,111 +1130,29 @@ module.exports._enoent = enoent; /***/ }), -/* 21 */ -/***/ (function(module, exports) { +/* 21 */, +/* 22 */ +/***/ (function(module, __unusedexports, __webpack_require__) { -"use strict"; +/** + * For Node.js, simply re-export the core `util.deprecate` function. + */ -/* - json-stringify-safe - Like JSON.stringify, but doesn't throw on circular references. +module.exports = __webpack_require__(669).deprecate; - Originally forked from https://github.com/isaacs/json-stringify-safe - version 5.0.1 on 2017-09-21 and modified to handle Errors serialization. - Tests for this are in test/vendor. - ISC license: https://github.com/isaacs/json-stringify-safe/blob/master/LICENSE - */ +/***/ }), +/* 23 */ +/***/ (function(module, __unusedexports, __webpack_require__) { -exports = module.exports = stringify; -exports.getSerialize = serializer; - -function stringify(obj, replacer, spaces, cycleReplacer) { - return JSON.stringify(obj, serializer(replacer, cycleReplacer), spaces); -} - -// https://github.com/ftlabs/js-abbreviate/blob/fa709e5f139e7770a71827b1893f22418097fbda/index.js#L95-L106 -function stringifyError(value) { - var err = { - // These properties are implemented as magical getters and don't show up in for in - stack: value.stack, - message: value.message, - name: value.name - }; - - for (var i in value) { - if (Object.prototype.hasOwnProperty.call(value, i)) { - err[i] = value[i]; - } - } - - return err; -} - -function serializer(replacer, cycleReplacer) { - var stack = []; - var keys = []; - - if (cycleReplacer == null) { - cycleReplacer = function(key, value) { - if (stack[0] === value) { - return '[Circular ~]'; - } - return '[Circular ~.' + keys.slice(0, stack.indexOf(value)).join('.') + ']'; - }; - } - - return function(key, value) { - if (stack.length > 0) { - var thisPos = stack.indexOf(this); - ~thisPos ? stack.splice(thisPos + 1) : stack.push(this); - ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key); - - if (~stack.indexOf(value)) { - value = cycleReplacer.call(this, key, value); - } - } else { - stack.push(value); - } - - return replacer == null - ? value instanceof Error ? stringifyError(value) : value - : replacer.call(this, key, value); - }; -} - - -/***/ }), -/* 22 */ -/***/ (function(module) { - -/** - * Removes all key-value entries from the list cache. - * - * @private - * @name clear - * @memberOf ListCache - */ -function listCacheClear() { - this.__data__ = []; - this.size = 0; -} - -module.exports = listCacheClear; - - -/***/ }), -/* 23 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; -// Standard YAML's JSON schema. -// http://www.yaml.org/spec/1.2/spec.html#id2803231 -// -// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. -// So, this schema is not such strict as defined in the YAML specification. -// It allows numbers in binary notaion, use `Null` and `NULL` as `null`, etc. +"use strict"; +// Standard YAML's JSON schema. +// http://www.yaml.org/spec/1.2/spec.html#id2803231 +// +// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. +// So, this schema is not such strict as defined in the YAML specification. +// It allows numbers in binary notaion, use `Null` and `NULL` as `null`, etc. @@ -644,7 +1163,7 @@ var Schema = __webpack_require__(43); module.exports = new Schema({ include: [ - __webpack_require__(468) + __webpack_require__(795) ], implicit: [ __webpack_require__(787), @@ -656,7 +1175,21 @@ module.exports = new Schema({ /***/ }), -/* 24 */, +/* 24 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + + +var Type = __webpack_require__(945); + +module.exports = new Type('tag:yaml.org,2002:map', { + kind: 'mapping', + construct: function (data) { return data !== null ? data : {}; } +}); + + +/***/ }), /* 25 */ /***/ (function(module, __unusedexports, __webpack_require__) { @@ -668,13 +1201,31 @@ module.exports = new Schema({ if (typeof process !== 'undefined' && process.type === 'renderer') { module.exports = __webpack_require__(978); } else { - module.exports = __webpack_require__(620); + module.exports = __webpack_require__(77); } /***/ }), /* 26 */, -/* 27 */, +/* 27 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +Object.defineProperty(exports, "__esModule", { value: true }); +var console_1 = __webpack_require__(834); +exports.Console = console_1.Console; +var http_1 = __webpack_require__(268); +exports.Http = http_1.Http; +var onuncaughtexception_1 = __webpack_require__(733); +exports.OnUncaughtException = onuncaughtexception_1.OnUncaughtException; +var onunhandledrejection_1 = __webpack_require__(271); +exports.OnUnhandledRejection = onunhandledrejection_1.OnUnhandledRejection; +var linkederrors_1 = __webpack_require__(859); +exports.LinkedErrors = linkederrors_1.LinkedErrors; +var modules_1 = __webpack_require__(429); +exports.Modules = modules_1.Modules; +//# sourceMappingURL=index.js.map + +/***/ }), /* 28 */ /***/ (function(module) { @@ -1134,77 +1685,7 @@ module.exports = { /***/ }), /* 29 */, /* 30 */, -/* 31 */ -/***/ (function(module) { - -"use strict"; - - -/** - * Expose `arrayFlatten`. - */ -module.exports = arrayFlatten - -/** - * Recursive flatten function with depth. - * - * @param {Array} array - * @param {Array} result - * @param {Number} depth - * @return {Array} - */ -function flattenWithDepth (array, result, depth) { - for (var i = 0; i < array.length; i++) { - var value = array[i] - - if (depth > 0 && Array.isArray(value)) { - flattenWithDepth(value, result, depth - 1) - } else { - result.push(value) - } - } - - return result -} - -/** - * Recursive flatten function. Omitting depth is slightly faster. - * - * @param {Array} array - * @param {Array} result - * @return {Array} - */ -function flattenForever (array, result) { - for (var i = 0; i < array.length; i++) { - var value = array[i] - - if (Array.isArray(value)) { - flattenForever(value, result) - } else { - result.push(value) - } - } - - return result -} - -/** - * Flatten an array, with the ability to define a depth. - * - * @param {Array} array - * @param {Number} depth - * @return {Array} - */ -function arrayFlatten (array, depth) { - if (depth == null) { - return flattenForever(array, []) - } - - return flattenWithDepth(array, [], depth) -} - - -/***/ }), +/* 31 */, /* 32 */ /***/ (function(module, __unusedexports, __webpack_require__) { @@ -1398,354 +1879,459 @@ function loadModule(moduleName) { /***/ }), -/* 35 */, -/* 36 */ -/***/ (function(module, exports, __webpack_require__) { +/* 35 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { -/** - * Module dependencies. - */ +Object.defineProperty(exports, "__esModule", { value: true }); +var tslib_1 = __webpack_require__(422); +var hub_1 = __webpack_require__(698); +var utils_1 = __webpack_require__(657); +// "Script error." is hard coded into browsers for errors that it can't read. +// this is the result of a script being pulled in from an external domain and CORS. +var DEFAULT_IGNORE_ERRORS = [/^Script error\.?$/, /^Javascript error: Script error\.? on line 0$/]; +/** Inbound filters configurable by the user */ +var InboundFilters = /** @class */ (function () { + function InboundFilters(_options) { + if (_options === void 0) { _options = {}; } + this._options = _options; + /** + * @inheritDoc + */ + this.name = InboundFilters.id; + } + /** + * @inheritDoc + */ + InboundFilters.prototype.setupOnce = function () { + hub_1.addGlobalEventProcessor(function (event) { + var hub = hub_1.getCurrentHub(); + if (!hub) { + return event; + } + var self = hub.getIntegration(InboundFilters); + if (self) { + var client = hub.getClient(); + var clientOptions = client ? client.getOptions() : {}; + var options = self._mergeOptions(clientOptions); + if (self._shouldDropEvent(event, options)) { + return null; + } + } + return event; + }); + }; + /** JSDoc */ + InboundFilters.prototype._shouldDropEvent = function (event, options) { + if (this._isSentryError(event, options)) { + utils_1.logger.warn("Event dropped due to being internal Sentry Error.\nEvent: " + utils_1.getEventDescription(event)); + return true; + } + if (this._isIgnoredError(event, options)) { + utils_1.logger.warn("Event dropped due to being matched by `ignoreErrors` option.\nEvent: " + utils_1.getEventDescription(event)); + return true; + } + if (this._isDeniedUrl(event, options)) { + utils_1.logger.warn("Event dropped due to being matched by `denyUrls` option.\nEvent: " + utils_1.getEventDescription(event) + ".\nUrl: " + this._getEventFilterUrl(event)); + return true; + } + if (!this._isAllowedUrl(event, options)) { + utils_1.logger.warn("Event dropped due to not being matched by `allowUrls` option.\nEvent: " + utils_1.getEventDescription(event) + ".\nUrl: " + this._getEventFilterUrl(event)); + return true; + } + return false; + }; + /** JSDoc */ + InboundFilters.prototype._isSentryError = function (event, options) { + if (!options.ignoreInternal) { + return false; + } + try { + return ((event && + event.exception && + event.exception.values && + event.exception.values[0] && + event.exception.values[0].type === 'SentryError') || + false); + } + catch (_oO) { + return false; + } + }; + /** JSDoc */ + InboundFilters.prototype._isIgnoredError = function (event, options) { + if (!options.ignoreErrors || !options.ignoreErrors.length) { + return false; + } + return this._getPossibleEventMessages(event).some(function (message) { + // Not sure why TypeScript complains here... + return options.ignoreErrors.some(function (pattern) { return utils_1.isMatchingPattern(message, pattern); }); + }); + }; + /** JSDoc */ + InboundFilters.prototype._isDeniedUrl = function (event, options) { + // TODO: Use Glob instead? + if (!options.denyUrls || !options.denyUrls.length) { + return false; + } + var url = this._getEventFilterUrl(event); + return !url ? false : options.denyUrls.some(function (pattern) { return utils_1.isMatchingPattern(url, pattern); }); + }; + /** JSDoc */ + InboundFilters.prototype._isAllowedUrl = function (event, options) { + // TODO: Use Glob instead? + if (!options.allowUrls || !options.allowUrls.length) { + return true; + } + var url = this._getEventFilterUrl(event); + return !url ? true : options.allowUrls.some(function (pattern) { return utils_1.isMatchingPattern(url, pattern); }); + }; + /** JSDoc */ + InboundFilters.prototype._mergeOptions = function (clientOptions) { + if (clientOptions === void 0) { clientOptions = {}; } + return { + allowUrls: tslib_1.__spread((this._options.whitelistUrls || []), (this._options.allowUrls || []), (clientOptions.whitelistUrls || []), (clientOptions.allowUrls || [])), + denyUrls: tslib_1.__spread((this._options.blacklistUrls || []), (this._options.denyUrls || []), (clientOptions.blacklistUrls || []), (clientOptions.denyUrls || [])), + ignoreErrors: tslib_1.__spread((this._options.ignoreErrors || []), (clientOptions.ignoreErrors || []), DEFAULT_IGNORE_ERRORS), + ignoreInternal: typeof this._options.ignoreInternal !== 'undefined' ? this._options.ignoreInternal : true, + }; + }; + /** JSDoc */ + InboundFilters.prototype._getPossibleEventMessages = function (event) { + if (event.message) { + return [event.message]; + } + if (event.exception) { + try { + var _a = (event.exception.values && event.exception.values[0]) || {}, _b = _a.type, type = _b === void 0 ? '' : _b, _c = _a.value, value = _c === void 0 ? '' : _c; + return ["" + value, type + ": " + value]; + } + catch (oO) { + utils_1.logger.error("Cannot extract message for event " + utils_1.getEventDescription(event)); + return []; + } + } + return []; + }; + /** JSDoc */ + InboundFilters.prototype._getEventFilterUrl = function (event) { + try { + if (event.stacktrace) { + var frames_1 = event.stacktrace.frames; + return (frames_1 && frames_1[frames_1.length - 1].filename) || null; + } + if (event.exception) { + var frames_2 = event.exception.values && event.exception.values[0].stacktrace && event.exception.values[0].stacktrace.frames; + return (frames_2 && frames_2[frames_2.length - 1].filename) || null; + } + return null; + } + catch (oO) { + utils_1.logger.error("Cannot extract url for event " + utils_1.getEventDescription(event)); + return null; + } + }; + /** + * @inheritDoc + */ + InboundFilters.id = 'InboundFilters'; + return InboundFilters; +}()); +exports.InboundFilters = InboundFilters; +//# sourceMappingURL=inboundfilters.js.map -var tty = __webpack_require__(867); -var util = __webpack_require__(669); +/***/ }), +/* 36 */, +/* 37 */ +/***/ (function(module, __unusedexports, __webpack_require__) { -/** - * This is the Node.js implementation of `debug()`. - * - * Expose `debug()` as the module. - */ +"use strict"; -exports = module.exports = __webpack_require__(209); -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -/** - * Colors. - */ +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } -exports.colors = [6, 2, 3, 4, 5, 1]; +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } -/** - * Build up the default `inspectOpts` object from the environment variables. - * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js - */ +var BottleneckError, LocalDatastore, parser; +parser = __webpack_require__(850); +BottleneckError = __webpack_require__(212); +LocalDatastore = class LocalDatastore { + constructor(instance, storeOptions, storeInstanceOptions) { + this.instance = instance; + this.storeOptions = storeOptions; + this.clientId = this.instance._randomIndex(); + parser.load(storeInstanceOptions, storeInstanceOptions, this); + this._nextRequest = this._lastReservoirRefresh = this._lastReservoirIncrease = Date.now(); + this._running = 0; + this._done = 0; + this._unblockTime = 0; + this.ready = this.Promise.resolve(); + this.clients = {}; -exports.inspectOpts = Object.keys(process.env).filter(function (key) { - return /^debug_/i.test(key); -}).reduce(function (obj, key) { - // camel-case - var prop = key - .substring(6) - .toLowerCase() - .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); + this._startHeartbeat(); + } - // coerce string value into JS value - var val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) val = true; - else if (/^(no|off|false|disabled)$/i.test(val)) val = false; - else if (val === 'null') val = null; - else val = Number(val); + _startHeartbeat() { + var base; - obj[prop] = val; - return obj; -}, {}); + if (this.heartbeat == null && (this.storeOptions.reservoirRefreshInterval != null && this.storeOptions.reservoirRefreshAmount != null || this.storeOptions.reservoirIncreaseInterval != null && this.storeOptions.reservoirIncreaseAmount != null)) { + return typeof (base = this.heartbeat = setInterval(() => { + var amount, incr, maximum, now, reservoir; + now = Date.now(); -/** - * The file descriptor to write the `debug()` calls to. - * Set the `DEBUG_FD` env variable to override with another value. i.e.: - * - * $ DEBUG_FD=3 node script.js 3>debug.log - */ + if (this.storeOptions.reservoirRefreshInterval != null && now >= this._lastReservoirRefresh + this.storeOptions.reservoirRefreshInterval) { + this._lastReservoirRefresh = now; + this.storeOptions.reservoir = this.storeOptions.reservoirRefreshAmount; -var fd = parseInt(process.env.DEBUG_FD, 10) || 2; + this.instance._drainAll(this.computeCapacity()); + } -if (1 !== fd && 2 !== fd) { - util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')() -} + if (this.storeOptions.reservoirIncreaseInterval != null && now >= this._lastReservoirIncrease + this.storeOptions.reservoirIncreaseInterval) { + var _this$storeOptions = this.storeOptions; + amount = _this$storeOptions.reservoirIncreaseAmount; + maximum = _this$storeOptions.reservoirIncreaseMaximum; + reservoir = _this$storeOptions.reservoir; + this._lastReservoirIncrease = now; + incr = maximum != null ? Math.min(amount, maximum - reservoir) : amount; -var stream = 1 === fd ? process.stdout : - 2 === fd ? process.stderr : - createWritableStdioStream(fd); + if (incr > 0) { + this.storeOptions.reservoir += incr; + return this.instance._drainAll(this.computeCapacity()); + } + } + }, this.heartbeatInterval)).unref === "function" ? base.unref() : void 0; + } else { + return clearInterval(this.heartbeat); + } + } -/** - * Is stdout a TTY? Colored output is enabled when `true`. - */ + __publish__(message) { + var _this = this; -function useColors() { - return 'colors' in exports.inspectOpts - ? Boolean(exports.inspectOpts.colors) - : tty.isatty(fd); -} + return _asyncToGenerator(function* () { + yield _this.yieldLoop(); + return _this.instance.Events.trigger("message", message.toString()); + })(); + } -/** - * Map %o to `util.inspect()`, all on a single line. - */ + __disconnect__(flush) { + var _this2 = this; -exports.formatters.o = function(v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts) - .split('\n').map(function(str) { - return str.trim() - }).join(' '); -}; + return _asyncToGenerator(function* () { + yield _this2.yieldLoop(); + clearInterval(_this2.heartbeat); + return _this2.Promise.resolve(); + })(); + } -/** - * Map %o to `util.inspect()`, allowing multiple lines if needed. - */ + yieldLoop(t = 0) { + return new this.Promise(function (resolve, reject) { + return setTimeout(resolve, t); + }); + } -exports.formatters.O = function(v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); -}; + computePenalty() { + var ref; + return (ref = this.storeOptions.penalty) != null ? ref : 15 * this.storeOptions.minTime || 5000; + } -/** - * Adds ANSI color escape codes if enabled. - * - * @api public - */ + __updateSettings__(options) { + var _this3 = this; -function formatArgs(args) { - var name = this.namespace; - var useColors = this.useColors; + return _asyncToGenerator(function* () { + yield _this3.yieldLoop(); + parser.overwrite(options, options, _this3.storeOptions); - if (useColors) { - var c = this.color; - var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m'; + _this3._startHeartbeat(); - args[0] = prefix + args[0].split('\n').join('\n' + prefix); - args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); - } else { - args[0] = new Date().toUTCString() - + ' ' + name + ' ' + args[0]; + _this3.instance._drainAll(_this3.computeCapacity()); + + return true; + })(); } -} -/** - * Invokes `util.format()` with the specified arguments and writes to `stream`. - */ + __running__() { + var _this4 = this; -function log() { - return stream.write(util.format.apply(util, arguments) + '\n'); -} + return _asyncToGenerator(function* () { + yield _this4.yieldLoop(); + return _this4._running; + })(); + } -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ + __queued__() { + var _this5 = this; -function save(namespaces) { - if (null == namespaces) { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } else { - process.env.DEBUG = namespaces; + return _asyncToGenerator(function* () { + yield _this5.yieldLoop(); + return _this5.instance.queued(); + })(); } -} -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ + __done__() { + var _this6 = this; -function load() { - return process.env.DEBUG; -} + return _asyncToGenerator(function* () { + yield _this6.yieldLoop(); + return _this6._done; + })(); + } -/** - * Copied from `node/src/node.js`. - * - * XXX: It's lame that node doesn't expose this API out-of-the-box. It also - * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame. - */ + __groupCheck__(time) { + var _this7 = this; -function createWritableStdioStream (fd) { - var stream; - var tty_wrap = process.binding('tty_wrap'); + return _asyncToGenerator(function* () { + yield _this7.yieldLoop(); + return _this7._nextRequest + _this7.timeout < time; + })(); + } - // Note stream._type is used for test-module-load-list.js + computeCapacity() { + var maxConcurrent, reservoir; + var _this$storeOptions2 = this.storeOptions; + maxConcurrent = _this$storeOptions2.maxConcurrent; + reservoir = _this$storeOptions2.reservoir; - switch (tty_wrap.guessHandleType(fd)) { - case 'TTY': - stream = new tty.WriteStream(fd); - stream._type = 'tty'; + if (maxConcurrent != null && reservoir != null) { + return Math.min(maxConcurrent - this._running, reservoir); + } else if (maxConcurrent != null) { + return maxConcurrent - this._running; + } else if (reservoir != null) { + return reservoir; + } else { + return null; + } + } - // Hack to have stream not keep the event loop alive. - // See https://github.com/joyent/node/issues/1726 - if (stream._handle && stream._handle.unref) { - stream._handle.unref(); - } - break; + conditionsCheck(weight) { + var capacity; + capacity = this.computeCapacity(); + return capacity == null || weight <= capacity; + } - case 'FILE': - var fs = __webpack_require__(747); - stream = new fs.SyncWriteStream(fd, { autoClose: false }); - stream._type = 'fs'; - break; + __incrementReservoir__(incr) { + var _this8 = this; - case 'PIPE': - case 'TCP': - var net = __webpack_require__(631); - stream = new net.Socket({ - fd: fd, - readable: false, - writable: true - }); + return _asyncToGenerator(function* () { + var reservoir; + yield _this8.yieldLoop(); + reservoir = _this8.storeOptions.reservoir += incr; - // FIXME Should probably have an option in net.Socket to create a - // stream from an existing fd which is writable only. But for now - // we'll just add this hack and set the `readable` member to false. - // Test: ./node test/fixtures/echo.js < /etc/passwd - stream.readable = false; - stream.read = null; - stream._type = 'pipe'; + _this8.instance._drainAll(_this8.computeCapacity()); - // FIXME Hack to have stream not keep the event loop alive. - // See https://github.com/joyent/node/issues/1726 - if (stream._handle && stream._handle.unref) { - stream._handle.unref(); - } - break; + return reservoir; + })(); + } - default: - // Probably an error on in uv_guess_handle() - throw new Error('Implement me. Unknown stream file type!'); - } - - // For supporting legacy API we put the FD here. - stream.fd = fd; - - stream._isStdio = true; - - return stream; -} - -/** - * Init logic for `debug` instances. - * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. - */ - -function init (debug) { - debug.inspectOpts = {}; + __currentReservoir__() { + var _this9 = this; - var keys = Object.keys(exports.inspectOpts); - for (var i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + return _asyncToGenerator(function* () { + yield _this9.yieldLoop(); + return _this9.storeOptions.reservoir; + })(); } -} -/** - * Enable namespaces listed in `process.env.DEBUG` initially. - */ + isBlocked(now) { + return this._unblockTime >= now; + } -exports.enable(load()); + check(weight, now) { + return this.conditionsCheck(weight) && this._nextRequest - now <= 0; + } + __check__(weight) { + var _this10 = this; -/***/ }), -/* 37 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + return _asyncToGenerator(function* () { + var now; + yield _this10.yieldLoop(); + now = Date.now(); + return _this10.check(weight, now); + })(); + } -module.exports = parseOptions; + __register__(index, weight, expiration) { + var _this11 = this; -const { Deprecation } = __webpack_require__(692); -const { getUserAgent } = __webpack_require__(796); -const once = __webpack_require__(969); + return _asyncToGenerator(function* () { + var now, wait; + yield _this11.yieldLoop(); + now = Date.now(); -const pkg = __webpack_require__(876); + if (_this11.conditionsCheck(weight)) { + _this11._running += weight; -const deprecateOptionsTimeout = once((log, deprecation) => - log.warn(deprecation) -); -const deprecateOptionsAgent = once((log, deprecation) => log.warn(deprecation)); -const deprecateOptionsHeaders = once((log, deprecation) => - log.warn(deprecation) -); + if (_this11.storeOptions.reservoir != null) { + _this11.storeOptions.reservoir -= weight; + } -function parseOptions(options, log, hook) { - if (options.headers) { - options.headers = Object.keys(options.headers).reduce((newObj, key) => { - newObj[key.toLowerCase()] = options.headers[key]; - return newObj; - }, {}); + wait = Math.max(_this11._nextRequest - now, 0); + _this11._nextRequest = now + wait + _this11.storeOptions.minTime; + return { + success: true, + wait, + reservoir: _this11.storeOptions.reservoir + }; + } else { + return { + success: false + }; + } + })(); } - const clientDefaults = { - headers: options.headers || {}, - request: options.request || {}, - mediaType: { - previews: [], - format: "" - } - }; - - if (options.baseUrl) { - clientDefaults.baseUrl = options.baseUrl; + strategyIsBlock() { + return this.storeOptions.strategy === 3; } - if (options.userAgent) { - clientDefaults.headers["user-agent"] = options.userAgent; - } + __submit__(queueLength, weight) { + var _this12 = this; - if (options.previews) { - clientDefaults.mediaType.previews = options.previews; - } + return _asyncToGenerator(function* () { + var blocked, now, reachedHWM; + yield _this12.yieldLoop(); - if (options.timeZone) { - clientDefaults.headers["time-zone"] = options.timeZone; - } + if (_this12.storeOptions.maxConcurrent != null && weight > _this12.storeOptions.maxConcurrent) { + throw new BottleneckError(`Impossible to add a job having a weight of ${weight} to a limiter having a maxConcurrent setting of ${_this12.storeOptions.maxConcurrent}`); + } - if (options.timeout) { - deprecateOptionsTimeout( - log, - new Deprecation( - "[@octokit/rest] new Octokit({timeout}) is deprecated. Use {request: {timeout}} instead. See https://github.com/octokit/request.js#request" - ) - ); - clientDefaults.request.timeout = options.timeout; - } + now = Date.now(); + reachedHWM = _this12.storeOptions.highWater != null && queueLength === _this12.storeOptions.highWater && !_this12.check(weight, now); + blocked = _this12.strategyIsBlock() && (reachedHWM || _this12.isBlocked(now)); - if (options.agent) { - deprecateOptionsAgent( - log, - new Deprecation( - "[@octokit/rest] new Octokit({agent}) is deprecated. Use {request: {agent}} instead. See https://github.com/octokit/request.js#request" - ) - ); - clientDefaults.request.agent = options.agent; - } + if (blocked) { + _this12._unblockTime = now + _this12.computePenalty(); + _this12._nextRequest = _this12._unblockTime + _this12.storeOptions.minTime; - if (options.headers) { - deprecateOptionsHeaders( - log, - new Deprecation( - "[@octokit/rest] new Octokit({headers}) is deprecated. Use {userAgent, previews} instead. See https://github.com/octokit/request.js#request" - ) - ); + _this12.instance._dropAllQueued(); + } + + return { + reachedHWM, + blocked, + strategy: _this12.storeOptions.strategy + }; + })(); } - const userAgentOption = clientDefaults.headers["user-agent"]; - const defaultUserAgent = `octokit.js/${pkg.version} ${getUserAgent()}`; + __free__(index, weight) { + var _this13 = this; - clientDefaults.headers["user-agent"] = [userAgentOption, defaultUserAgent] - .filter(Boolean) - .join(" "); + return _asyncToGenerator(function* () { + yield _this13.yieldLoop(); + _this13._running -= weight; + _this13._done += weight; - clientDefaults.request.hook = hook.bind(null, "request"); + _this13.instance._drainAll(_this13.computeCapacity()); - return clientDefaults; -} + return { + running: _this13._running + }; + })(); + } +}; +module.exports = LocalDatastore; /***/ }), /* 38 */, @@ -1769,34 +2355,444 @@ module.exports = opts => { /***/ }), -/* 40 */, +/* 40 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const net_1 = __importDefault(__webpack_require__(631)); +const tls_1 = __importDefault(__webpack_require__(16)); +const url_1 = __importDefault(__webpack_require__(835)); +const assert_1 = __importDefault(__webpack_require__(357)); +const debug_1 = __importDefault(__webpack_require__(784)); +const agent_base_1 = __webpack_require__(443); +const parse_proxy_response_1 = __importDefault(__webpack_require__(428)); +const debug = debug_1.default('https-proxy-agent:agent'); +/** + * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to + * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests. + * + * Outgoing HTTP requests are first tunneled through the proxy server using the + * `CONNECT` HTTP request method to establish a connection to the proxy server, + * and then the proxy server connects to the destination target and issues the + * HTTP request from the proxy server. + * + * `https:` requests have their socket connection upgraded to TLS once + * the connection to the proxy server has been established. + * + * @api public + */ +class HttpsProxyAgent extends agent_base_1.Agent { + constructor(_opts) { + let opts; + if (typeof _opts === 'string') { + opts = url_1.default.parse(_opts); + } + else { + opts = _opts; + } + if (!opts) { + throw new Error('an HTTP(S) proxy server `host` and `port` must be specified!'); + } + debug('creating new HttpsProxyAgent instance: %o', opts); + super(opts); + const proxy = Object.assign({}, opts); + // If `true`, then connect to the proxy server over TLS. + // Defaults to `false`. + this.secureProxy = opts.secureProxy || isHTTPS(proxy.protocol); + // Prefer `hostname` over `host`, and set the `port` if needed. + proxy.host = proxy.hostname || proxy.host; + if (typeof proxy.port === 'string') { + proxy.port = parseInt(proxy.port, 10); + } + if (!proxy.port && proxy.host) { + proxy.port = this.secureProxy ? 443 : 80; + } + // ALPN is supported by Node.js >= v5. + // attempt to negotiate http/1.1 for proxy servers that support http/2 + if (this.secureProxy && !('ALPNProtocols' in proxy)) { + proxy.ALPNProtocols = ['http 1.1']; + } + if (proxy.host && proxy.path) { + // If both a `host` and `path` are specified then it's most likely + // the result of a `url.parse()` call... we need to remove the + // `path` portion so that `net.connect()` doesn't attempt to open + // that as a Unix socket file. + delete proxy.path; + delete proxy.pathname; + } + this.proxy = proxy; + } + /** + * Called when the node-core HTTP client library is creating a + * new HTTP request. + * + * @api protected + */ + callback(req, opts) { + return __awaiter(this, void 0, void 0, function* () { + const { proxy, secureProxy } = this; + // Create a socket connection to the proxy server. + let socket; + if (secureProxy) { + debug('Creating `tls.Socket`: %o', proxy); + socket = tls_1.default.connect(proxy); + } + else { + debug('Creating `net.Socket`: %o', proxy); + socket = net_1.default.connect(proxy); + } + const headers = Object.assign({}, proxy.headers); + const hostname = `${opts.host}:${opts.port}`; + let payload = `CONNECT ${hostname} HTTP/1.1\r\n`; + // Inject the `Proxy-Authorization` header if necessary. + if (proxy.auth) { + headers['Proxy-Authorization'] = `Basic ${Buffer.from(proxy.auth).toString('base64')}`; + } + // The `Host` header should only include the port + // number when it is not the default port. + let { host, port, secureEndpoint } = opts; + if (!isDefaultPort(port, secureEndpoint)) { + host += `:${port}`; + } + headers.Host = host; + headers.Connection = 'close'; + for (const name of Object.keys(headers)) { + payload += `${name}: ${headers[name]}\r\n`; + } + const proxyResponsePromise = parse_proxy_response_1.default(socket); + socket.write(`${payload}\r\n`); + const { statusCode, buffered } = yield proxyResponsePromise; + if (statusCode === 200) { + req.once('socket', resume); + if (opts.secureEndpoint) { + const servername = opts.servername || opts.host; + if (!servername) { + throw new Error('Could not determine "servername"'); + } + // The proxy is connecting to a TLS server, so upgrade + // this socket connection to a TLS connection. + debug('Upgrading socket connection to TLS'); + return tls_1.default.connect(Object.assign(Object.assign({}, omit(opts, 'host', 'hostname', 'path', 'port')), { socket, + servername })); + } + return socket; + } + // Some other status code that's not 200... need to re-play the HTTP + // header "data" events onto the socket once the HTTP machinery is + // attached so that the node core `http` can parse and handle the + // error status code. + // Close the original socket, and a new "fake" socket is returned + // instead, so that the proxy doesn't get the HTTP request + // written to it (which may contain `Authorization` headers or other + // sensitive data). + // + // See: https://hackerone.com/reports/541502 + socket.destroy(); + const fakeSocket = new net_1.default.Socket(); + fakeSocket.readable = true; + // Need to wait for the "socket" event to re-play the "data" events. + req.once('socket', (s) => { + debug('replaying proxy buffer for failed request'); + assert_1.default(s.listenerCount('data') > 0); + // Replay the "buffered" Buffer onto the fake `socket`, since at + // this point the HTTP module machinery has been hooked up for + // the user. + s.push(buffered); + s.push(null); + }); + return fakeSocket; + }); + } +} +exports.default = HttpsProxyAgent; +function resume(socket) { + socket.resume(); +} +function isDefaultPort(port, secure) { + return Boolean((!secure && port === 80) || (secure && port === 443)); +} +function isHTTPS(protocol) { + return typeof protocol === 'string' ? /^https:?$/i.test(protocol) : false; +} +function omit(obj, ...keys) { + const ret = {}; + let key; + for (key in obj) { + if (!keys.includes(key)) { + ret[key] = obj[key]; + } + } + return ret; +} +//# sourceMappingURL=agent.js.map + +/***/ }), /* 41 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +/***/ (function(module, exports, __webpack_require__) { + +/** + * Module dependencies. + */ + +var tty = __webpack_require__(867); +var util = __webpack_require__(669); + +/** + * This is the Node.js implementation of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = __webpack_require__(209); +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; + +/** + * Colors. + */ + +exports.colors = [6, 2, 3, 4, 5, 1]; + +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ + +exports.inspectOpts = Object.keys(process.env).filter(function (key) { + return /^debug_/i.test(key); +}).reduce(function (obj, key) { + // camel-case + var prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); + + // coerce string value into JS value + var val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) val = true; + else if (/^(no|off|false|disabled)$/i.test(val)) val = false; + else if (val === 'null') val = null; + else val = Number(val); + + obj[prop] = val; + return obj; +}, {}); + +/** + * The file descriptor to write the `debug()` calls to. + * Set the `DEBUG_FD` env variable to override with another value. i.e.: + * + * $ DEBUG_FD=3 node script.js 3>debug.log + */ + +var fd = parseInt(process.env.DEBUG_FD, 10) || 2; + +if (1 !== fd && 2 !== fd) { + util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')() +} + +var stream = 1 === fd ? process.stdout : + 2 === fd ? process.stderr : + createWritableStdioStream(fd); -module.exports = withAuthorizationPrefix; +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ + +function useColors() { + return 'colors' in exports.inspectOpts + ? Boolean(exports.inspectOpts.colors) + : tty.isatty(fd); +} + +/** + * Map %o to `util.inspect()`, all on a single line. + */ + +exports.formatters.o = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n').map(function(str) { + return str.trim() + }).join(' '); +}; + +/** + * Map %o to `util.inspect()`, allowing multiple lines if needed. + */ + +exports.formatters.O = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; + +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ -const atob = __webpack_require__(368); +function formatArgs(args) { + var name = this.namespace; + var useColors = this.useColors; -const REGEX_IS_BASIC_AUTH = /^[\w-]+:/; + if (useColors) { + var c = this.color; + var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m'; -function withAuthorizationPrefix(authorization) { - if (/^(basic|bearer|token) /i.test(authorization)) { - return authorization; + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); + } else { + args[0] = new Date().toUTCString() + + ' ' + name + ' ' + args[0]; } +} - try { - if (REGEX_IS_BASIC_AUTH.test(atob(authorization))) { - return `basic ${authorization}`; - } - } catch (error) {} +/** + * Invokes `util.format()` with the specified arguments and writes to `stream`. + */ + +function log() { + return stream.write(util.format.apply(util, arguments) + '\n'); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + +function save(namespaces) { + if (null == namespaces) { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } else { + process.env.DEBUG = namespaces; + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + return process.env.DEBUG; +} + +/** + * Copied from `node/src/node.js`. + * + * XXX: It's lame that node doesn't expose this API out-of-the-box. It also + * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame. + */ + +function createWritableStdioStream (fd) { + var stream; + var tty_wrap = process.binding('tty_wrap'); + + // Note stream._type is used for test-module-load-list.js + + switch (tty_wrap.guessHandleType(fd)) { + case 'TTY': + stream = new tty.WriteStream(fd); + stream._type = 'tty'; + + // Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } + break; + + case 'FILE': + var fs = __webpack_require__(747); + stream = new fs.SyncWriteStream(fd, { autoClose: false }); + stream._type = 'fs'; + break; + + case 'PIPE': + case 'TCP': + var net = __webpack_require__(631); + stream = new net.Socket({ + fd: fd, + readable: false, + writable: true + }); + + // FIXME Should probably have an option in net.Socket to create a + // stream from an existing fd which is writable only. But for now + // we'll just add this hack and set the `readable` member to false. + // Test: ./node test/fixtures/echo.js < /etc/passwd + stream.readable = false; + stream.read = null; + stream._type = 'pipe'; + + // FIXME Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } + break; - if (authorization.split(/\./).length === 3) { - return `bearer ${authorization}`; + default: + // Probably an error on in uv_guess_handle() + throw new Error('Implement me. Unknown stream file type!'); } - return `token ${authorization}`; + // For supporting legacy API we put the FD here. + stream.fd = fd; + + stream._isStdio = true; + + return stream; +} + +/** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ + +function init (debug) { + debug.inspectOpts = {}; + + var keys = Object.keys(exports.inspectOpts); + for (var i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } } +/** + * Enable namespaces listed in `process.env.DEBUG` initially. + */ + +exports.enable(load()); + /***/ }), /* 42 */, @@ -2098,519 +3094,1039 @@ module.exports = new Type('tag:yaml.org,2002:int', { /* 45 */, /* 46 */, /* 47 */, -/* 48 */ +/* 48 */, +/* 49 */ /***/ (function(module, __unusedexports, __webpack_require__) { -module.exports = authenticationBeforeRequest; +var wrappy = __webpack_require__(11) +module.exports = wrappy(once) +module.exports.strict = wrappy(onceStrict) -const btoa = __webpack_require__(675); +once.proto = once(function () { + Object.defineProperty(Function.prototype, 'once', { + value: function () { + return once(this) + }, + configurable: true + }) -const withAuthorizationPrefix = __webpack_require__(41); + Object.defineProperty(Function.prototype, 'onceStrict', { + value: function () { + return onceStrict(this) + }, + configurable: true + }) +}) -function authenticationBeforeRequest(state, options) { - if (typeof state.auth === "string") { - options.headers.authorization = withAuthorizationPrefix(state.auth); - return; +function once (fn) { + var f = function () { + if (f.called) return f.value + f.called = true + return f.value = fn.apply(this, arguments) } + f.called = false + return f +} - if (state.auth.username) { - const hash = btoa(`${state.auth.username}:${state.auth.password}`); - options.headers.authorization = `Basic ${hash}`; - if (state.otp) { - options.headers["x-github-otp"] = state.otp; - } - return; +function onceStrict (fn) { + var f = function () { + if (f.called) + throw new Error(f.onceError) + f.called = true + return f.value = fn.apply(this, arguments) } + var name = fn.name || 'Function wrapped with `once`' + f.onceError = name + " shouldn't be called more than once" + f.called = false + return f +} - if (state.auth.clientId) { - // There is a special case for OAuth applications, when `clientId` and `clientSecret` is passed as - // Basic Authorization instead of query parameters. The only routes where that applies share the same - // URL though: `/applications/:client_id/tokens/:access_token`. - // - // 1. [Check an authorization](https://developer.github.com/v3/oauth_authorizations/#check-an-authorization) - // 2. [Reset an authorization](https://developer.github.com/v3/oauth_authorizations/#reset-an-authorization) - // 3. [Revoke an authorization for an application](https://developer.github.com/v3/oauth_authorizations/#revoke-an-authorization-for-an-application) - // - // We identify by checking the URL. It must merge both "/applications/:client_id/tokens/:access_token" - // as well as "/applications/123/tokens/token456" - if (/\/applications\/:?[\w_]+\/tokens\/:?[\w_]+($|\?)/.test(options.url)) { - const hash = btoa(`${state.auth.clientId}:${state.auth.clientSecret}`); - options.headers.authorization = `Basic ${hash}`; - return; - } - options.url += options.url.indexOf("?") === -1 ? "?" : "&"; - options.url += `client_id=${state.auth.clientId}&client_secret=${state.auth.clientSecret}`; - return; - } +/***/ }), +/* 50 */ +/***/ (function(__unusedmodule, exports) { - return Promise.resolve() +Object.defineProperty(exports, "__esModule", { value: true }); +/** Console logging verbosity for the SDK. */ +var LogLevel; +(function (LogLevel) { + /** No logs will be generated. */ + LogLevel[LogLevel["None"] = 0] = "None"; + /** Only SDK internal errors will be logged. */ + LogLevel[LogLevel["Error"] = 1] = "Error"; + /** Information useful for debugging the SDK will be logged. */ + LogLevel[LogLevel["Debug"] = 2] = "Debug"; + /** All SDK actions will be logged. */ + LogLevel[LogLevel["Verbose"] = 3] = "Verbose"; +})(LogLevel = exports.LogLevel || (exports.LogLevel = {})); +//# sourceMappingURL=loglevel.js.map + +/***/ }), +/* 51 */, +/* 52 */, +/* 53 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - .then(() => { - return state.auth(); - }) +"use strict"; - .then(authorization => { - options.headers.authorization = withAuthorizationPrefix(authorization); - }); -} +const indentString = __webpack_require__(861); +const cleanStack = __webpack_require__(201); +const cleanInternalStack = stack => stack.replace(/\s+at .*aggregate-error\/index.js:\d+:\d+\)?/g, ''); -/***/ }), -/* 49 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +class AggregateError extends Error { + constructor(errors) { + if (!Array.isArray(errors)) { + throw new TypeError(`Expected input to be an Array, got ${typeof errors}`); + } -"use strict"; + errors = [...errors].map(error => { + if (error instanceof Error) { + return error; + } -const os = __webpack_require__(87); -const execa = __webpack_require__(955); + if (error !== null && typeof error === 'object') { + // Handle plain error objects with message property and/or possibly other metadata + return Object.assign(new Error(error.message), error); + } -// Reference: https://www.gaijin.at/en/lstwinver.php -const names = new Map([ - ['10.0', '10'], - ['6.3', '8.1'], - ['6.2', '8'], - ['6.1', '7'], - ['6.0', 'Vista'], - ['5.2', 'Server 2003'], - ['5.1', 'XP'], - ['5.0', '2000'], - ['4.9', 'ME'], - ['4.1', '98'], - ['4.0', '95'] -]); + return new Error(error); + }); -const windowsRelease = release => { - const version = /\d+\.\d/.exec(release || os.release()); + let message = errors + .map(error => { + // The `stack` property is not standardized, so we can't assume it exists + return typeof error.stack === 'string' ? cleanInternalStack(cleanStack(error.stack)) : String(error); + }) + .join('\n'); + message = '\n' + indentString(message, 4); + super(message); - if (release && !version) { - throw new Error('`release` argument doesn\'t match `n.n`'); + this.name = 'AggregateError'; + + Object.defineProperty(this, '_errors', {value: errors}); } - const ver = (version || [])[0]; - - // Server 2008, 2012 and 2016 versions are ambiguous with desktop versions and must be detected at runtime. - // If `release` is omitted or we're on a Windows system, and the version number is an ambiguous version - // then use `wmic` to get the OS caption: https://msdn.microsoft.com/en-us/library/aa394531(v=vs.85).aspx - // If the resulting caption contains the year 2008, 2012 or 2016, it is a server version, so return a server OS name. - if ((!release || release === os.release()) && ['6.1', '6.2', '6.3', '10.0'].includes(ver)) { - const stdout = execa.sync('wmic', ['os', 'get', 'Caption']).stdout || ''; - const year = (stdout.match(/2008|2012|2016/) || [])[0]; - if (year) { - return `Server ${year}`; + * [Symbol.iterator]() { + for (const error of this._errors) { + yield error; } } - - return names.get(ver); -}; - -module.exports = windowsRelease; - - -/***/ }), -/* 50 */, -/* 51 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -var Symbol = __webpack_require__(498), - getRawTag = __webpack_require__(443), - objectToString = __webpack_require__(602); - -/** `Object#toString` result references. */ -var nullTag = '[object Null]', - undefinedTag = '[object Undefined]'; - -/** Built-in value references. */ -var symToStringTag = Symbol ? Symbol.toStringTag : undefined; - -/** - * The base implementation of `getTag` without fallbacks for buggy environments. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ -function baseGetTag(value) { - if (value == null) { - return value === undefined ? undefinedTag : nullTag; - } - return (symToStringTag && symToStringTag in Object(value)) - ? getRawTag(value) - : objectToString(value); } -module.exports = baseGetTag; +module.exports = AggregateError; /***/ }), -/* 52 */ +/* 54 */, +/* 55 */, +/* 56 */ /***/ (function(module, __unusedexports, __webpack_require__) { "use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. +module.exports = PassThrough; -var yaml = __webpack_require__(751); +var Transform = __webpack_require__(339); +__webpack_require__(689)(PassThrough, Transform); -module.exports = yaml; +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + Transform.call(this, options); +} +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; /***/ }), -/* 53 */, -/* 54 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -module.exports = paginatePlugin; - -const { paginateRest } = __webpack_require__(378); +/* 57 */ +/***/ (function(module, exports, __webpack_require__) { -function paginatePlugin(octokit) { - Object.assign(octokit, paginateRest(octokit)); -} +"use strict"; +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ -/***/ }), -/* 55 */, -/* 56 */ -/***/ (function(module, exports, __webpack_require__) { /** * Module dependencies. + * @private */ -var tty = __webpack_require__(867); -var util = __webpack_require__(669); +var finalhandler = __webpack_require__(430); +var Router = __webpack_require__(987); +var methods = __webpack_require__(203); +var middleware = __webpack_require__(917); +var query = __webpack_require__(210); +var debug = __webpack_require__(590)('express:application'); +var View = __webpack_require__(742); +var http = __webpack_require__(605); +var compileETag = __webpack_require__(120).compileETag; +var compileQueryParser = __webpack_require__(120).compileQueryParser; +var compileTrust = __webpack_require__(120).compileTrust; +var deprecate = __webpack_require__(418)('express'); +var flatten = __webpack_require__(211); +var merge = __webpack_require__(707); +var resolve = __webpack_require__(622).resolve; +var setPrototypeOf = __webpack_require__(64) +var slice = Array.prototype.slice; /** - * This is the Node.js implementation of `debug()`. - * - * Expose `debug()` as the module. + * Application prototype. */ -exports = module.exports = __webpack_require__(911); -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; +var app = exports = module.exports = {}; /** - * Colors. + * Variable for trust proxy inheritance back-compat + * @private */ -exports.colors = [6, 2, 3, 4, 5, 1]; +var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default'; /** - * Build up the default `inspectOpts` object from the environment variables. + * Initialize the server. * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + * - setup default configuration + * - setup default middleware + * - setup route reflection methods + * + * @private */ -exports.inspectOpts = Object.keys(process.env).filter(function (key) { - return /^debug_/i.test(key); -}).reduce(function (obj, key) { - // camel-case - var prop = key - .substring(6) - .toLowerCase() - .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); - - // coerce string value into JS value - var val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) val = true; - else if (/^(no|off|false|disabled)$/i.test(val)) val = false; - else if (val === 'null') val = null; - else val = Number(val); +app.init = function init() { + this.cache = {}; + this.engines = {}; + this.settings = {}; - obj[prop] = val; - return obj; -}, {}); + this.defaultConfiguration(); +}; /** - * The file descriptor to write the `debug()` calls to. - * Set the `DEBUG_FD` env variable to override with another value. i.e.: - * - * $ DEBUG_FD=3 node script.js 3>debug.log + * Initialize application configuration. + * @private */ -var fd = parseInt(process.env.DEBUG_FD, 10) || 2; - -if (1 !== fd && 2 !== fd) { - util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')() -} - -var stream = 1 === fd ? process.stdout : - 2 === fd ? process.stderr : - createWritableStdioStream(fd); +app.defaultConfiguration = function defaultConfiguration() { + var env = process.env.NODE_ENV || 'development'; -/** - * Is stdout a TTY? Colored output is enabled when `true`. - */ + // default settings + this.enable('x-powered-by'); + this.set('etag', 'weak'); + this.set('env', env); + this.set('query parser', 'extended'); + this.set('subdomain offset', 2); + this.set('trust proxy', false); -function useColors() { - return 'colors' in exports.inspectOpts - ? Boolean(exports.inspectOpts.colors) - : tty.isatty(fd); -} + // trust proxy inherit back-compat + Object.defineProperty(this.settings, trustProxyDefaultSymbol, { + configurable: true, + value: true + }); -/** - * Map %o to `util.inspect()`, all on a single line. - */ + debug('booting in %s mode', env); -exports.formatters.o = function(v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts) - .split('\n').map(function(str) { - return str.trim() - }).join(' '); -}; + this.on('mount', function onmount(parent) { + // inherit trust proxy + if (this.settings[trustProxyDefaultSymbol] === true + && typeof parent.settings['trust proxy fn'] === 'function') { + delete this.settings['trust proxy']; + delete this.settings['trust proxy fn']; + } -/** - * Map %o to `util.inspect()`, allowing multiple lines if needed. - */ + // inherit protos + setPrototypeOf(this.request, parent.request) + setPrototypeOf(this.response, parent.response) + setPrototypeOf(this.engines, parent.engines) + setPrototypeOf(this.settings, parent.settings) + }); -exports.formatters.O = function(v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); -}; + // setup locals + this.locals = Object.create(null); -/** - * Adds ANSI color escape codes if enabled. - * - * @api public - */ + // top-most app is mounted at / + this.mountpath = '/'; -function formatArgs(args) { - var name = this.namespace; - var useColors = this.useColors; + // default locals + this.locals.settings = this.settings; - if (useColors) { - var c = this.color; - var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m'; + // default configuration + this.set('view', View); + this.set('views', resolve('views')); + this.set('jsonp callback name', 'callback'); - args[0] = prefix + args[0].split('\n').join('\n' + prefix); - args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); - } else { - args[0] = new Date().toUTCString() - + ' ' + name + ' ' + args[0]; + if (env === 'production') { + this.enable('view cache'); } -} - -/** - * Invokes `util.format()` with the specified arguments and writes to `stream`. - */ -function log() { - return stream.write(util.format.apply(util, arguments) + '\n'); -} + Object.defineProperty(this, 'router', { + get: function() { + throw new Error('\'app.router\' is deprecated!\nPlease see the 3.x to 4.x migration guide for details on how to update your app.'); + } + }); +}; /** - * Save `namespaces`. + * lazily adds the base router if it has not yet been added. * - * @param {String} namespaces - * @api private + * We cannot add the base router in the defaultConfiguration because + * it reads app settings which might be set after that has run. + * + * @private */ +app.lazyrouter = function lazyrouter() { + if (!this._router) { + this._router = new Router({ + caseSensitive: this.enabled('case sensitive routing'), + strict: this.enabled('strict routing') + }); -function save(namespaces) { - if (null == namespaces) { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } else { - process.env.DEBUG = namespaces; + this._router.use(query(this.get('query parser fn'))); + this._router.use(middleware.init(this)); } -} +}; /** - * Load `namespaces`. + * Dispatch a req, res pair into the application. Starts pipeline processing. * - * @return {String} returns the previously persisted debug modes - * @api private + * If no callback is provided, then default error handlers will respond + * in the event of an error bubbling through the stack. + * + * @private */ -function load() { - return process.env.DEBUG; -} +app.handle = function handle(req, res, callback) { + var router = this._router; + + // final handler + var done = callback || finalhandler(req, res, { + env: this.get('env'), + onerror: logerror.bind(this) + }); + + // no routes + if (!router) { + debug('no routes defined on app'); + done(); + return; + } + + router.handle(req, res, done); +}; /** - * Copied from `node/src/node.js`. + * Proxy `Router#use()` to add middleware to the app router. + * See Router#use() documentation for details. * - * XXX: It's lame that node doesn't expose this API out-of-the-box. It also - * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame. + * If the _fn_ parameter is an express app, then it will be + * mounted at the _route_ specified. + * + * @public */ -function createWritableStdioStream (fd) { - var stream; - var tty_wrap = process.binding('tty_wrap'); +app.use = function use(fn) { + var offset = 0; + var path = '/'; - // Note stream._type is used for test-module-load-list.js + // default path to '/' + // disambiguate app.use([fn]) + if (typeof fn !== 'function') { + var arg = fn; - switch (tty_wrap.guessHandleType(fd)) { - case 'TTY': - stream = new tty.WriteStream(fd); - stream._type = 'tty'; + while (Array.isArray(arg) && arg.length !== 0) { + arg = arg[0]; + } - // Hack to have stream not keep the event loop alive. - // See https://github.com/joyent/node/issues/1726 - if (stream._handle && stream._handle.unref) { - stream._handle.unref(); - } - break; + // first arg is the path + if (typeof arg !== 'function') { + offset = 1; + path = fn; + } + } - case 'FILE': - var fs = __webpack_require__(747); - stream = new fs.SyncWriteStream(fd, { autoClose: false }); - stream._type = 'fs'; - break; + var fns = flatten(slice.call(arguments, offset)); - case 'PIPE': - case 'TCP': - var net = __webpack_require__(631); - stream = new net.Socket({ - fd: fd, - readable: false, - writable: true - }); + if (fns.length === 0) { + throw new TypeError('app.use() requires a middleware function') + } - // FIXME Should probably have an option in net.Socket to create a - // stream from an existing fd which is writable only. But for now - // we'll just add this hack and set the `readable` member to false. - // Test: ./node test/fixtures/echo.js < /etc/passwd - stream.readable = false; - stream.read = null; - stream._type = 'pipe'; + // setup router + this.lazyrouter(); + var router = this._router; - // FIXME Hack to have stream not keep the event loop alive. - // See https://github.com/joyent/node/issues/1726 - if (stream._handle && stream._handle.unref) { - stream._handle.unref(); - } - break; + fns.forEach(function (fn) { + // non-express app + if (!fn || !fn.handle || !fn.set) { + return router.use(path, fn); + } - default: - // Probably an error on in uv_guess_handle() - throw new Error('Implement me. Unknown stream file type!'); - } + debug('.use app under %s', path); + fn.mountpath = path; + fn.parent = this; - // For supporting legacy API we put the FD here. - stream.fd = fd; + // restore .app property on req and res + router.use(path, function mounted_app(req, res, next) { + var orig = req.app; + fn.handle(req, res, function (err) { + setPrototypeOf(req, orig.request) + setPrototypeOf(res, orig.response) + next(err); + }); + }); - stream._isStdio = true; + // mounted an app + fn.emit('mount', this); + }, this); - return stream; -} + return this; +}; /** - * Init logic for `debug` instances. + * Proxy to the app `Router#route()` + * Returns a new `Route` instance for the _path_. * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. + * Routes are isolated middleware stacks for specific paths. + * See the Route api docs for details. + * + * @public */ -function init (debug) { - debug.inspectOpts = {}; - - var keys = Object.keys(exports.inspectOpts); - for (var i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } -} +app.route = function route(path) { + this.lazyrouter(); + return this._router.route(path); +}; /** - * Enable namespaces listed in `process.env.DEBUG` initially. + * Register the given template engine callback `fn` + * as `ext`. + * + * By default will `require()` the engine based on the + * file extension. For example if you try to render + * a "foo.ejs" file Express will invoke the following internally: + * + * app.engine('ejs', require('ejs').__express); + * + * For engines that do not provide `.__express` out of the box, + * or if you wish to "map" a different extension to the template engine + * you may use this method. For example mapping the EJS template engine to + * ".html" files: + * + * app.engine('html', require('ejs').renderFile); + * + * In this case EJS provides a `.renderFile()` method with + * the same signature that Express expects: `(path, options, callback)`, + * though note that it aliases this method as `ejs.__express` internally + * so if you're using ".ejs" extensions you dont need to do anything. + * + * Some template engines do not follow this convention, the + * [Consolidate.js](https://github.com/tj/consolidate.js) + * library was created to map all of node's popular template + * engines to follow this convention, thus allowing them to + * work seamlessly within Express. + * + * @param {String} ext + * @param {Function} fn + * @return {app} for chaining + * @public */ -exports.enable(load()); - - -/***/ }), -/* 57 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const StandaloneConnector_1 = __webpack_require__(219); -exports.StandaloneConnector = StandaloneConnector_1.default; -const SentinelConnector_1 = __webpack_require__(571); -exports.SentinelConnector = SentinelConnector_1.default; - +app.engine = function engine(ext, fn) { + if (typeof fn !== 'function') { + throw new Error('callback function required'); + } -/***/ }), -/* 58 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + // get file extension + var extension = ext[0] !== '.' + ? '.' + ext + : ext; -var coreJsData = __webpack_require__(871); + // store engine + this.engines[extension] = fn; -/** Used to detect methods masquerading as native. */ -var maskSrcKey = (function() { - var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); - return uid ? ('Symbol(src)_1.' + uid) : ''; -}()); + return this; +}; /** - * Checks if `func` has its source masked. + * Proxy to `Router#param()` with one added api feature. The _name_ parameter + * can be an array of names. * - * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` is masked, else `false`. + * See the Router#param() docs for more details. + * + * @param {String|Array} name + * @param {Function} fn + * @return {app} for chaining + * @public */ -function isMasked(func) { - return !!maskSrcKey && (maskSrcKey in func); -} -module.exports = isMasked; +app.param = function param(name, fn) { + this.lazyrouter(); + if (Array.isArray(name)) { + for (var i = 0; i < name.length; i++) { + this.param(name[i], fn); + } -/***/ }), -/* 59 */, -/* 60 */ -/***/ (function(module) { + return this; + } -var toString = Object.prototype.toString; + this._router.param(name, fn); -module.exports = function isArguments(value) { - var str = toString.call(value); - var isArguments = str === '[object Arguments]'; - if (!isArguments) { - isArguments = str !== '[object Array]' - && value !== null - && typeof value === 'object' - && typeof value.length === 'number' - && value.length >= 0 - && toString.call(value.callee) === '[object Function]'; - } - return isArguments; + return this; }; - - -/***/ }), -/* 61 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -var getMapData = __webpack_require__(549); - /** - * Checks if a map value for `key` exists. + * Assign `setting` to `val`, or return `setting`'s value. * - * @private - * @name has - * @memberOf MapCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function mapCacheHas(key) { - return getMapData(this, key).has(key); -} - -module.exports = mapCacheHas; - - -/***/ }), -/* 62 */, + * app.set('foo', 'bar'); + * app.set('foo'); + * // => "bar" + * + * Mounted servers inherit their parent server's settings. + * + * @param {String} setting + * @param {*} [val] + * @return {Server} for chaining + * @public + */ + +app.set = function set(setting, val) { + if (arguments.length === 1) { + // app.get(setting) + return this.settings[setting]; + } + + debug('set "%s" to %o', setting, val); + + // set value + this.settings[setting] = val; + + // trigger matched settings + switch (setting) { + case 'etag': + this.set('etag fn', compileETag(val)); + break; + case 'query parser': + this.set('query parser fn', compileQueryParser(val)); + break; + case 'trust proxy': + this.set('trust proxy fn', compileTrust(val)); + + // trust proxy inherit back-compat + Object.defineProperty(this.settings, trustProxyDefaultSymbol, { + configurable: true, + value: false + }); + + break; + } + + return this; +}; + +/** + * Return the app's absolute pathname + * based on the parent(s) that have + * mounted it. + * + * For example if the application was + * mounted as "/admin", which itself + * was mounted as "/blog" then the + * return value would be "/blog/admin". + * + * @return {String} + * @private + */ + +app.path = function path() { + return this.parent + ? this.parent.path() + this.mountpath + : ''; +}; + +/** + * Check if `setting` is enabled (truthy). + * + * app.enabled('foo') + * // => false + * + * app.enable('foo') + * app.enabled('foo') + * // => true + * + * @param {String} setting + * @return {Boolean} + * @public + */ + +app.enabled = function enabled(setting) { + return Boolean(this.set(setting)); +}; + +/** + * Check if `setting` is disabled. + * + * app.disabled('foo') + * // => true + * + * app.enable('foo') + * app.disabled('foo') + * // => false + * + * @param {String} setting + * @return {Boolean} + * @public + */ + +app.disabled = function disabled(setting) { + return !this.set(setting); +}; + +/** + * Enable `setting`. + * + * @param {String} setting + * @return {app} for chaining + * @public + */ + +app.enable = function enable(setting) { + return this.set(setting, true); +}; + +/** + * Disable `setting`. + * + * @param {String} setting + * @return {app} for chaining + * @public + */ + +app.disable = function disable(setting) { + return this.set(setting, false); +}; + +/** + * Delegate `.VERB(...)` calls to `router.VERB(...)`. + */ + +methods.forEach(function(method){ + app[method] = function(path){ + if (method === 'get' && arguments.length === 1) { + // app.get(setting) + return this.set(path); + } + + this.lazyrouter(); + + var route = this._router.route(path); + route[method].apply(route, slice.call(arguments, 1)); + return this; + }; +}); + +/** + * Special-cased "all" method, applying the given route `path`, + * middleware, and callback to _every_ HTTP method. + * + * @param {String} path + * @param {Function} ... + * @return {app} for chaining + * @public + */ + +app.all = function all(path) { + this.lazyrouter(); + + var route = this._router.route(path); + var args = slice.call(arguments, 1); + + for (var i = 0; i < methods.length; i++) { + route[methods[i]].apply(route, args); + } + + return this; +}; + +// del -> delete alias + +app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead'); + +/** + * Render the given view `name` name with `options` + * and a callback accepting an error and the + * rendered template string. + * + * Example: + * + * app.render('email', { name: 'Tobi' }, function(err, html){ + * // ... + * }) + * + * @param {String} name + * @param {Object|Function} options or fn + * @param {Function} callback + * @public + */ + +app.render = function render(name, options, callback) { + var cache = this.cache; + var done = callback; + var engines = this.engines; + var opts = options; + var renderOptions = {}; + var view; + + // support callback function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } + + // merge app.locals + merge(renderOptions, this.locals); + + // merge options._locals + if (opts._locals) { + merge(renderOptions, opts._locals); + } + + // merge options + merge(renderOptions, opts); + + // set .cache unless explicitly provided + if (renderOptions.cache == null) { + renderOptions.cache = this.enabled('view cache'); + } + + // primed cache + if (renderOptions.cache) { + view = cache[name]; + } + + // view + if (!view) { + var View = this.get('view'); + + view = new View(name, { + defaultEngine: this.get('view engine'), + root: this.get('views'), + engines: engines + }); + + if (!view.path) { + var dirs = Array.isArray(view.root) && view.root.length > 1 + ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"' + : 'directory "' + view.root + '"' + var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs); + err.view = view; + return done(err); + } + + // prime the cache + if (renderOptions.cache) { + cache[name] = view; + } + } + + // render + tryRender(view, renderOptions, done); +}; + +/** + * Listen for connections. + * + * A node `http.Server` is returned, with this + * application (which is a `Function`) as its + * callback. If you wish to create both an HTTP + * and HTTPS server you may do so with the "http" + * and "https" modules as shown here: + * + * var http = require('http') + * , https = require('https') + * , express = require('express') + * , app = express(); + * + * http.createServer(app).listen(80); + * https.createServer({ ... }, app).listen(443); + * + * @return {http.Server} + * @public + */ + +app.listen = function listen() { + var server = http.createServer(this); + return server.listen.apply(server, arguments); +}; + +/** + * Log error using console.error. + * + * @param {Error} err + * @private + */ + +function logerror(err) { + /* istanbul ignore next */ + if (this.get('env') !== 'test') console.error(err.stack || err.toString()); +} + +/** + * Try rendering a view. + * @private + */ + +function tryRender(view, options, callback) { + try { + view.render(options, callback); + } catch (err) { + callback(err); + } +} + + +/***/ }), +/* 58 */, +/* 59 */, +/* 60 */ +/***/ (function(module, exports, __webpack_require__) { + +/* module decorator */ module = __webpack_require__.nmd(module); +Object.defineProperty(exports, "__esModule", { value: true }); +var is_1 = __webpack_require__(613); +var object_1 = __webpack_require__(90); +/** + * Checks whether we're in the Node.js or Browser environment + * + * @returns Answer to given question + */ +function isNodeEnv() { + return Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]'; +} +exports.isNodeEnv = isNodeEnv; +/** + * Requires a module which is protected against bundler minification. + * + * @param request The module path to resolve + */ +// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types +function dynamicRequire(mod, request) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + return mod.require(request); +} +exports.dynamicRequire = dynamicRequire; +/** Default request keys that'll be used to extract data from the request */ +var DEFAULT_REQUEST_KEYS = ['cookies', 'data', 'headers', 'method', 'query_string', 'url']; +/** + * Normalizes data from the request object, accounting for framework differences. + * + * @param req The request object from which to extract data + * @param keys An optional array of keys to include in the normalized data. Defaults to DEFAULT_REQUEST_KEYS if not + * provided. + * @returns An object containing normalized request data + */ +function extractNodeRequestData(req, keys) { + if (keys === void 0) { keys = DEFAULT_REQUEST_KEYS; } + // make sure we can safely use dynamicRequire below + if (!isNodeEnv()) { + throw new Error("Can't get node request data outside of a node environment"); + } + var requestData = {}; + // headers: + // node, express: req.headers + // koa: req.header + var headers = (req.headers || req.header || {}); + // method: + // node, express, koa: req.method + var method = req.method; + // host: + // express: req.hostname in > 4 and req.host in < 4 + // koa: req.host + // node: req.headers.host + var host = req.hostname || req.host || headers.host || ''; + // protocol: + // node: + // express, koa: req.protocol + var protocol = req.protocol === 'https' || req.secure || (req.socket || {}).encrypted + ? 'https' + : 'http'; + // url (including path and query string): + // node, express: req.originalUrl + // koa: req.url + var originalUrl = (req.originalUrl || req.url); + // absolute url + var absoluteUrl = protocol + "://" + host + originalUrl; + keys.forEach(function (key) { + switch (key) { + case 'headers': + requestData.headers = headers; + break; + case 'method': + requestData.method = method; + break; + case 'url': + requestData.url = absoluteUrl; + break; + case 'cookies': + // cookies: + // node, express, koa: req.headers.cookie + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + requestData.cookies = dynamicRequire(module, 'cookie').parse(headers.cookie || ''); + break; + case 'query_string': + // query string: + // node: req.url (raw) + // express, koa: req.query + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + requestData.query_string = dynamicRequire(module, 'url').parse(originalUrl || '', false).query; + break; + case 'data': + if (method === 'GET' || method === 'HEAD') { + break; + } + // body data: + // node, express, koa: req.body + if (req.body !== undefined) { + requestData.data = is_1.isString(req.body) ? req.body : JSON.stringify(object_1.normalize(req.body)); + } + break; + default: + if ({}.hasOwnProperty.call(req, key)) { + requestData[key] = req[key]; + } + } + }); + return requestData; +} +exports.extractNodeRequestData = extractNodeRequestData; +//# sourceMappingURL=node.js.map + +/***/ }), +/* 61 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + + +var BottleneckError, States; +BottleneckError = __webpack_require__(212); +States = class States { + constructor(status1) { + this.status = status1; + this._jobs = {}; + this.counts = this.status.map(function () { + return 0; + }); + } + + next(id) { + var current, next; + current = this._jobs[id]; + next = current + 1; + + if (current != null && next < this.status.length) { + this.counts[current]--; + this.counts[next]++; + return this._jobs[id]++; + } else if (current != null) { + this.counts[current]--; + return delete this._jobs[id]; + } + } + + start(id) { + var initial; + initial = 0; + this._jobs[id] = initial; + return this.counts[initial]++; + } + + remove(id) { + var current; + current = this._jobs[id]; + + if (current != null) { + this.counts[current]--; + delete this._jobs[id]; + } + + return current != null; + } + + jobStatus(id) { + var ref; + return (ref = this.status[this._jobs[id]]) != null ? ref : null; + } + + statusJobs(status) { + var k, pos, ref, results, v; + + if (status != null) { + pos = this.status.indexOf(status); + + if (pos < 0) { + throw new BottleneckError(`status must be one of ${this.status.join(', ')}`); + } + + ref = this._jobs; + results = []; + + for (k in ref) { + v = ref[k]; + + if (v === pos) { + results.push(k); + } + } + + return results; + } else { + return Object.keys(this._jobs); + } + } + + statusCounts() { + return this.counts.reduce((acc, v, i) => { + acc[this.status[i]] = v; + return acc; + }, {}); + } + +}; +module.exports = States; + +/***/ }), +/* 62 */, /* 63 */ /***/ (function(module, __unusedexports, __webpack_require__) { @@ -2758,154 +4274,301 @@ function mixinProperties (obj, proto) { /* 66 */ /***/ (function(__unusedmodule, exports, __webpack_require__) { -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -var util = __webpack_require__(338); -var has = Object.prototype.hasOwnProperty; -var hasNativeMap = typeof Map !== "undefined"; - -/** - * A data structure which is a combination of an array and a set. Adding a new - * member is O(1), testing for membership is O(1), and finding the index of an - * element is O(1). Removing elements from the set is not supported. Only - * strings are supported for membership. - */ -function ArraySet() { - this._array = []; - this._set = hasNativeMap ? new Map() : Object.create(null); -} - -/** - * Static method for creating ArraySet instances from an existing array. - */ -ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { - var set = new ArraySet(); - for (var i = 0, len = aArray.length; i < len; i++) { - set.add(aArray[i], aAllowDuplicates); - } - return set; -}; - +Object.defineProperty(exports, "__esModule", { value: true }); +var is_1 = __webpack_require__(613); /** - * Return how many unique items are in this ArraySet. If duplicates have been - * added, than those do not count towards the size. + * Truncates given string to the maximum characters count * - * @returns Number + * @param str An object that contains serializable values + * @param max Maximum number of characters in truncated string + * @returns string Encoded */ -ArraySet.prototype.size = function ArraySet_size() { - return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length; -}; - +function truncate(str, max) { + if (max === void 0) { max = 0; } + if (typeof str !== 'string' || max === 0) { + return str; + } + return str.length <= max ? str : str.substr(0, max) + "..."; +} +exports.truncate = truncate; /** - * Add the given string to this set. + * This is basically just `trim_line` from + * https://github.com/getsentry/sentry/blob/master/src/sentry/lang/javascript/processor.py#L67 * - * @param String aStr + * @param str An object that contains serializable values + * @param max Maximum number of characters in truncated string + * @returns string Encoded */ -ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { - var sStr = hasNativeMap ? aStr : util.toSetString(aStr); - var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr); - var idx = this._array.length; - if (!isDuplicate || aAllowDuplicates) { - this._array.push(aStr); - } - if (!isDuplicate) { - if (hasNativeMap) { - this._set.set(aStr, idx); - } else { - this._set[sStr] = idx; +function snipLine(line, colno) { + var newLine = line; + var ll = newLine.length; + if (ll <= 150) { + return newLine; } - } -}; - + if (colno > ll) { + // eslint-disable-next-line no-param-reassign + colno = ll; + } + var start = Math.max(colno - 60, 0); + if (start < 5) { + start = 0; + } + var end = Math.min(start + 140, ll); + if (end > ll - 5) { + end = ll; + } + if (end === ll) { + start = Math.max(end - 140, 0); + } + newLine = newLine.slice(start, end); + if (start > 0) { + newLine = "'{snip} " + newLine; + } + if (end < ll) { + newLine += ' {snip}'; + } + return newLine; +} +exports.snipLine = snipLine; /** - * Is the given string a member of this set? - * - * @param String aStr + * Join values in array + * @param input array of values to be joined together + * @param delimiter string to be placed in-between values + * @returns Joined values */ -ArraySet.prototype.has = function ArraySet_has(aStr) { - if (hasNativeMap) { - return this._set.has(aStr); - } else { - var sStr = util.toSetString(aStr); - return has.call(this._set, sStr); - } -}; - +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function safeJoin(input, delimiter) { + if (!Array.isArray(input)) { + return ''; + } + var output = []; + // eslint-disable-next-line @typescript-eslint/prefer-for-of + for (var i = 0; i < input.length; i++) { + var value = input[i]; + try { + output.push(String(value)); + } + catch (e) { + output.push('[value cannot be serialized]'); + } + } + return output.join(delimiter); +} +exports.safeJoin = safeJoin; /** - * What is the index of the given string in the array? - * - * @param String aStr + * Checks if the value matches a regex or includes the string + * @param value The string value to be checked against + * @param pattern Either a regex or a string that must be contained in value */ -ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { - if (hasNativeMap) { - var idx = this._set.get(aStr); - if (idx >= 0) { - return idx; +function isMatchingPattern(value, pattern) { + if (!is_1.isString(value)) { + return false; } - } else { - var sStr = util.toSetString(aStr); - if (has.call(this._set, sStr)) { - return this._set[sStr]; + if (is_1.isRegExp(pattern)) { + return pattern.test(value); } - } + if (typeof pattern === 'string') { + return value.indexOf(pattern) !== -1; + } + return false; +} +exports.isMatchingPattern = isMatchingPattern; +//# sourceMappingURL=string.js.map - throw new Error('"' + aStr + '" is not in the set.'); -}; +/***/ }), +/* 67 */ +/***/ (function(module, exports, __webpack_require__) { -/** - * What is the element at the given index? - * - * @param Number aIdx +"use strict"; +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed */ -ArraySet.prototype.at = function ArraySet_at(aIdx) { - if (aIdx >= 0 && aIdx < this._array.length) { - return this._array[aIdx]; - } - throw new Error('No element indexed by ' + aIdx); -}; + + /** - * Returns the array representation of this set (which has the proper indices - * indicated by indexOf). Note that this is a copy of the internal array used - * for storing the members so that no one can mess with internal state. + * Module dependencies. */ -ArraySet.prototype.toArray = function ArraySet_toArray() { - return this._array.slice(); -}; - -exports.ArraySet = ArraySet; +var bodyParser = __webpack_require__(420) +var EventEmitter = __webpack_require__(614).EventEmitter; +var mixin = __webpack_require__(979); +var proto = __webpack_require__(57); +var Route = __webpack_require__(251); +var Router = __webpack_require__(987); +var req = __webpack_require__(108); +var res = __webpack_require__(801); -/***/ }), -/* 67 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { +/** + * Expose `createApplication()`. + */ + +exports = module.exports = createApplication; + +/** + * Create an express application. + * + * @return {Function} + * @api public + */ + +function createApplication() { + var app = function(req, res, next) { + app.handle(req, res, next); + }; + + mixin(app, EventEmitter.prototype, false); + mixin(app, proto, false); + + // expose the prototype that will get set on requests + app.request = Object.create(req, { + app: { configurable: true, enumerable: true, writable: true, value: app } + }) + + // expose the prototype that will get set on responses + app.response = Object.create(res, { + app: { configurable: true, enumerable: true, writable: true, value: app } + }) + + app.init(); + return app; +} + +/** + * Expose the prototypes. + */ + +exports.application = proto; +exports.request = req; +exports.response = res; + +/** + * Expose constructors. + */ + +exports.Route = Route; +exports.Router = Router; + +/** + * Expose middleware + */ + +exports.json = bodyParser.json +exports.query = __webpack_require__(210); +exports.raw = bodyParser.raw +exports.static = __webpack_require__(961); +exports.text = bodyParser.text +exports.urlencoded = bodyParser.urlencoded + +/** + * Replace removed middleware with an appropriate error message. + */ + +var removedMiddlewares = [ + 'bodyParser', + 'compress', + 'cookieSession', + 'session', + 'logger', + 'cookieParser', + 'favicon', + 'responseTime', + 'errorHandler', + 'timeout', + 'methodOverride', + 'vhost', + 'csrf', + 'directory', + 'limit', + 'multipart', + 'staticCache' +] + +removedMiddlewares.forEach(function (name) { + Object.defineProperty(exports, name, { + get: function () { + throw new Error('Most middleware (like ' + name + ') is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.'); + }, + configurable: true + }); +}); + + +/***/ }), +/* 68 */ +/***/ (function(__unusedmodule, exports) { "use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const redis_errors_1 = __webpack_require__(706); -class ClusterAllFailedError extends redis_errors_1.RedisError { - constructor(message, lastNodeError) { - super(message); - this.lastNodeError = lastNodeError; - Error.captureStackTrace(this, this.constructor); - } - get name() { - return this.constructor.name; - } + +Object.defineProperty(exports, '__esModule', { value: true }); + +async function auth(token) { + const tokenType = token.split(/\./).length === 3 ? "app" : /^v\d+\./.test(token) ? "installation" : "oauth"; + return { + type: "token", + token: token, + tokenType + }; } -exports.default = ClusterAllFailedError; + +/** + * Prefix token for usage in the Authorization header + * + * @param token OAuth token or JSON Web Token + */ +function withAuthorizationPrefix(token) { + if (token.split(/\./).length === 3) { + return `bearer ${token}`; + } + + return `token ${token}`; +} + +async function hook(token, request, route, parameters) { + const endpoint = request.endpoint.merge(route, parameters); + endpoint.headers.authorization = withAuthorizationPrefix(token); + return request(endpoint); +} + +const createTokenAuth = function createTokenAuth(token) { + if (!token) { + throw new Error("[@octokit/auth-token] No token passed to createTokenAuth"); + } + + if (typeof token !== "string") { + throw new Error("[@octokit/auth-token] Token passed to createTokenAuth is not a string"); + } + + token = token.replace(/^(token|bearer) +/i, ""); + return Object.assign(auth.bind(null, token), { + hook: hook.bind(null, token) + }); +}; + +exports.createTokenAuth = createTokenAuth; +//# sourceMappingURL=index.js.map /***/ }), -/* 68 */, /* 69 */, -/* 70 */, +/* 70 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +const StandaloneConnector_1 = __webpack_require__(219); +exports.StandaloneConnector = StandaloneConnector_1.default; +const SentinelConnector_1 = __webpack_require__(143); +exports.SentinelConnector = SentinelConnector_1.default; + + +/***/ }), /* 71 */ /***/ (function(__unusedmodule, exports) { @@ -2956,309 +4619,295 @@ exports.DEFAULT_REDIS_OPTIONS = { /***/ }), /* 72 */ -/***/ (function(module) { +/***/ (function(module, exports, __webpack_require__) { "use strict"; -const pTry = (fn, ...arguments_) => new Promise(resolve => { - resolve(fn(...arguments_)); +Object.defineProperty(exports, "__esModule", { + value: true }); +exports.default = void 0; -module.exports = pTry; -// TODO: remove this in the next major version -module.exports.default = pTry; - - -/***/ }), -/* 73 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -var getMapData = __webpack_require__(549); +var _v = _interopRequireDefault(__webpack_require__(806)); -/** - * Sets the map `key` to `value`. - * - * @private - * @name set - * @memberOf MapCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the map cache instance. - */ -function mapCacheSet(key, value) { - var data = getMapData(this, key), - size = data.size; - - data.set(key, value); - this.size += data.size == size ? 0 : 1; - return this; -} +var _md = _interopRequireDefault(__webpack_require__(708)); -module.exports = mapCacheSet; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +const v3 = (0, _v.default)('v3', 0x30, _md.default); +var _default = v3; +exports.default = _default; +module.exports = exports.default; /***/ }), +/* 73 */, /* 74 */, -/* 75 */ +/* 75 */, +/* 76 */ /***/ (function(module, __unusedexports, __webpack_require__) { "use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ +module.exports = __webpack_require__(324); + +/***/ }), +/* 77 */ +/***/ (function(module, exports, __webpack_require__) { /** * Module dependencies. - * @private */ -var debug = __webpack_require__(590)('express:view'); -var path = __webpack_require__(622); -var fs = __webpack_require__(747); +var tty = __webpack_require__(867); +var util = __webpack_require__(669); /** - * Module variables. - * @private + * This is the Node.js implementation of `debug()`. + * + * Expose `debug()` as the module. */ -var dirname = path.dirname; -var basename = path.basename; -var extname = path.extname; -var join = path.join; -var resolve = path.resolve; +exports = module.exports = __webpack_require__(909); +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; /** - * Module exports. - * @public + * Colors. */ -module.exports = View; +exports.colors = [6, 2, 3, 4, 5, 1]; /** - * Initialize a new `View` with the given `name`. - * - * Options: - * - * - `defaultEngine` the default template engine name - * - `engines` template engine require() cache - * - `root` root path for view lookup + * Build up the default `inspectOpts` object from the environment variables. * - * @param {string} name - * @param {object} options - * @public + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js */ -function View(name, options) { - var opts = options || {}; - - this.defaultEngine = opts.defaultEngine; - this.ext = extname(name); - this.name = name; - this.root = opts.root; - - if (!this.ext && !this.defaultEngine) { - throw new Error('No default engine was specified and no extension was provided.'); - } - - var fileName = name; +exports.inspectOpts = Object.keys(process.env).filter(function (key) { + return /^debug_/i.test(key); +}).reduce(function (obj, key) { + // camel-case + var prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); - if (!this.ext) { - // get extension from default engine name - this.ext = this.defaultEngine[0] !== '.' - ? '.' + this.defaultEngine - : this.defaultEngine; + // coerce string value into JS value + var val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) val = true; + else if (/^(no|off|false|disabled)$/i.test(val)) val = false; + else if (val === 'null') val = null; + else val = Number(val); - fileName += this.ext; - } + obj[prop] = val; + return obj; +}, {}); - if (!opts.engines[this.ext]) { - // load engine - var mod = this.ext.substr(1) - debug('require "%s"', mod) +/** + * The file descriptor to write the `debug()` calls to. + * Set the `DEBUG_FD` env variable to override with another value. i.e.: + * + * $ DEBUG_FD=3 node script.js 3>debug.log + */ - // default engine export - var fn = require(mod).__express +var fd = parseInt(process.env.DEBUG_FD, 10) || 2; - if (typeof fn !== 'function') { - throw new Error('Module "' + mod + '" does not provide a view engine.') - } +if (1 !== fd && 2 !== fd) { + util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')() +} - opts.engines[this.ext] = fn - } +var stream = 1 === fd ? process.stdout : + 2 === fd ? process.stderr : + createWritableStdioStream(fd); - // store loaded engine - this.engine = opts.engines[this.ext]; +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ - // lookup path - this.path = this.lookup(fileName); +function useColors() { + return 'colors' in exports.inspectOpts + ? Boolean(exports.inspectOpts.colors) + : tty.isatty(fd); } /** - * Lookup view by the given `name` - * - * @param {string} name - * @private + * Map %o to `util.inspect()`, all on a single line. */ -View.prototype.lookup = function lookup(name) { - var path; - var roots = [].concat(this.root); - - debug('lookup "%s"', name); - - for (var i = 0; i < roots.length && !path; i++) { - var root = roots[i]; - - // resolve the path - var loc = resolve(root, name); - var dir = dirname(loc); - var file = basename(loc); - - // resolve the file - path = this.resolve(dir, file); - } - - return path; +exports.formatters.o = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n').map(function(str) { + return str.trim() + }).join(' '); }; /** - * Render with the given options. - * - * @param {object} options - * @param {function} callback - * @private + * Map %o to `util.inspect()`, allowing multiple lines if needed. */ -View.prototype.render = function render(options, callback) { - debug('render "%s"', this.path); - this.engine(this.path, options, callback); +exports.formatters.O = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); }; /** - * Resolve the file within the given directory. + * Adds ANSI color escape codes if enabled. * - * @param {string} dir - * @param {string} file - * @private + * @api public */ -View.prototype.resolve = function resolve(dir, file) { - var ext = this.ext; +function formatArgs(args) { + var name = this.namespace; + var useColors = this.useColors; - // . - var path = join(dir, file); - var stat = tryStat(path); + if (useColors) { + var c = this.color; + var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m'; - if (stat && stat.isFile()) { - return path; + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); + } else { + args[0] = new Date().toUTCString() + + ' ' + name + ' ' + args[0]; } +} - // /index. - path = join(dir, basename(file, ext), 'index' + ext); - stat = tryStat(path); +/** + * Invokes `util.format()` with the specified arguments and writes to `stream`. + */ - if (stat && stat.isFile()) { - return path; - } -}; +function log() { + return stream.write(util.format.apply(util, arguments) + '\n'); +} /** - * Return a stat, maybe. + * Save `namespaces`. * - * @param {string} path - * @return {fs.Stats} - * @private + * @param {String} namespaces + * @api private */ -function tryStat(path) { - debug('stat "%s"', path); - - try { - return fs.statSync(path); - } catch (e) { - return undefined; +function save(namespaces) { + if (null == namespaces) { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } else { + process.env.DEBUG = namespaces; } } +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ -/***/ }), -/* 76 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +function load() { + return process.env.DEBUG; +} -"use strict"; +/** + * Copied from `node/src/node.js`. + * + * XXX: It's lame that node doesn't expose this API out-of-the-box. It also + * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame. + */ +function createWritableStdioStream (fd) { + var stream; + var tty_wrap = process.binding('tty_wrap'); -module.exports = __webpack_require__(324); + // Note stream._type is used for test-module-load-list.js -/***/ }), -/* 77 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + switch (tty_wrap.guessHandleType(fd)) { + case 'TTY': + stream = new tty.WriteStream(fd); + stream._type = 'tty'; -module.exports = authenticationPlugin; + // Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } + break; -const { Deprecation } = __webpack_require__(692); -const once = __webpack_require__(969); + case 'FILE': + var fs = __webpack_require__(747); + stream = new fs.SyncWriteStream(fd, { autoClose: false }); + stream._type = 'fs'; + break; -const deprecateAuthenticate = once((log, deprecation) => log.warn(deprecation)); + case 'PIPE': + case 'TCP': + var net = __webpack_require__(631); + stream = new net.Socket({ + fd: fd, + readable: false, + writable: true + }); -const authenticate = __webpack_require__(253); -const beforeRequest = __webpack_require__(365); -const requestError = __webpack_require__(491); + // FIXME Should probably have an option in net.Socket to create a + // stream from an existing fd which is writable only. But for now + // we'll just add this hack and set the `readable` member to false. + // Test: ./node test/fixtures/echo.js < /etc/passwd + stream.readable = false; + stream.read = null; + stream._type = 'pipe'; -function authenticationPlugin(octokit, options) { - if (options.auth) { - octokit.authenticate = () => { - deprecateAuthenticate( - octokit.log, - new Deprecation( - '[@octokit/rest] octokit.authenticate() is deprecated and has no effect when "auth" option is set on Octokit constructor' - ) - ); - }; - return; + // FIXME Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } + break; + + default: + // Probably an error on in uv_guess_handle() + throw new Error('Implement me. Unknown stream file type!'); } - const state = { - octokit, - auth: false - }; - octokit.authenticate = authenticate.bind(null, state); - octokit.hook.before("request", beforeRequest.bind(null, state)); - octokit.hook.error("request", requestError.bind(null, state)); -} + // For supporting legacy API we put the FD here. + stream.fd = fd; -/***/ }), -/* 78 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + stream._isStdio = true; -var getMapData = __webpack_require__(549); + return stream; +} /** - * Removes `key` and its value from the map. + * Init logic for `debug` instances. * - * @private - * @name delete - * @memberOf MapCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ -function mapCacheDelete(key) { - var result = getMapData(this, key)['delete'](key); - this.size -= result ? 1 : 0; - return result; -} + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ -module.exports = mapCacheDelete; +function init (debug) { + debug.inspectOpts = {}; + var keys = Object.keys(exports.inspectOpts); + for (var i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} -/***/ }), +/** + * Enable namespaces listed in `process.env.DEBUG` initially. + */ + +exports.enable(load()); + + +/***/ }), +/* 78 */, /* 79 */ /***/ (function(module, __unusedexports, __webpack_require__) { @@ -3308,48 +4957,165 @@ bufferEq.restore = function() { /***/ }), /* 80 */ -/***/ (function(module) { - -"use strict"; - +/***/ (function(__unusedmodule, exports, __webpack_require__) { -module.exports = parseJson -function parseJson (txt, reviver, context) { - context = context || 20 - try { - return JSON.parse(txt, reviver) - } catch (e) { - if (typeof txt !== 'string') { - const isEmptyArray = Array.isArray(txt) && txt.length === 0 - const errorMessage = 'Cannot parse ' + - (isEmptyArray ? 'an empty array' : String(txt)) - throw new TypeError(errorMessage) +Object.defineProperty(exports, "__esModule", { value: true }); +var tslib_1 = __webpack_require__(422); +var utils_1 = __webpack_require__(657); +var utils_2 = __webpack_require__(3); +exports.DEFAULT_TRACING_ORIGINS = ['localhost', /^\//]; +exports.defaultRequestInstrumentionOptions = { + traceFetch: true, + traceXHR: true, + tracingOrigins: exports.DEFAULT_TRACING_ORIGINS, +}; +/** Registers span creators for xhr and fetch requests */ +function registerRequestInstrumentation(_options) { + // eslint-disable-next-line @typescript-eslint/unbound-method + var _a = tslib_1.__assign(tslib_1.__assign({}, exports.defaultRequestInstrumentionOptions), _options), traceFetch = _a.traceFetch, traceXHR = _a.traceXHR, tracingOrigins = _a.tracingOrigins, shouldCreateSpanForRequest = _a.shouldCreateSpanForRequest; + // We should cache url -> decision so that we don't have to compute + // regexp everytime we create a request. + var urlMap = {}; + var defaultShouldCreateSpan = function (url) { + if (urlMap[url]) { + return urlMap[url]; + } + var origins = tracingOrigins; + urlMap[url] = + origins.some(function (origin) { return utils_1.isMatchingPattern(url, origin); }) && + !utils_1.isMatchingPattern(url, 'sentry_key'); + return urlMap[url]; + }; + // We want that our users don't have to re-implement shouldCreateSpanForRequest themselves + // That's why we filter out already unwanted Spans from tracingOrigins + var shouldCreateSpan = defaultShouldCreateSpan; + if (typeof shouldCreateSpanForRequest === 'function') { + shouldCreateSpan = function (url) { + return defaultShouldCreateSpan(url) && shouldCreateSpanForRequest(url); + }; } - const syntaxErr = e.message.match(/^Unexpected token.*position\s+(\d+)/i) - const errIdx = syntaxErr - ? +syntaxErr[1] - : e.message.match(/^Unexpected end of JSON.*/i) - ? txt.length - 1 - : null - if (errIdx != null) { - const start = errIdx <= context - ? 0 - : errIdx - context - const end = errIdx + context >= txt.length - ? txt.length - : errIdx + context - e.message += ` while parsing near '${ - start === 0 ? '' : '...' - }${txt.slice(start, end)}${ - end === txt.length ? '' : '...' - }'` - } else { - e.message += ` while parsing '${txt.slice(0, context * 2)}'` + var spans = {}; + if (traceFetch) { + utils_1.addInstrumentationHandler({ + callback: function (handlerData) { + _fetchCallback(handlerData, shouldCreateSpan, spans); + }, + type: 'fetch', + }); + } + if (traceXHR) { + utils_1.addInstrumentationHandler({ + callback: function (handlerData) { + xhrCallback(handlerData, shouldCreateSpan, spans); + }, + type: 'xhr', + }); } - throw e - } } - +exports.registerRequestInstrumentation = registerRequestInstrumentation; +/** + * Create and track fetch request spans + */ +function _fetchCallback(handlerData, shouldCreateSpan, spans) { + if (!handlerData.fetchData || !shouldCreateSpan(handlerData.fetchData.url)) { + return; + } + if (handlerData.endTimestamp && handlerData.fetchData.__span) { + var span = spans[handlerData.fetchData.__span]; + if (span) { + var response = handlerData.response; + if (response) { + span.setHttpStatus(response.status); + } + span.finish(); + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete spans[handlerData.fetchData.__span]; + } + return; + } + var activeTransaction = utils_2.getActiveTransaction(); + if (activeTransaction) { + var span = activeTransaction.startChild({ + data: tslib_1.__assign(tslib_1.__assign({}, handlerData.fetchData), { type: 'fetch' }), + description: handlerData.fetchData.method + " " + handlerData.fetchData.url, + op: 'http', + }); + handlerData.fetchData.__span = span.spanId; + spans[span.spanId] = span; + var request = (handlerData.args[0] = handlerData.args[0]); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + var options = (handlerData.args[1] = handlerData.args[1] || {}); + var headers = options.headers; + if (utils_1.isInstanceOf(request, Request)) { + headers = request.headers; + } + if (headers) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + if (typeof headers.append === 'function') { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + headers.append('sentry-trace', span.toTraceparent()); + } + else if (Array.isArray(headers)) { + headers = tslib_1.__spread(headers, [['sentry-trace', span.toTraceparent()]]); + } + else { + headers = tslib_1.__assign(tslib_1.__assign({}, headers), { 'sentry-trace': span.toTraceparent() }); + } + } + else { + headers = { 'sentry-trace': span.toTraceparent() }; + } + options.headers = headers; + } +} +exports._fetchCallback = _fetchCallback; +/** + * Create and track xhr request spans + */ +function xhrCallback(handlerData, shouldCreateSpan, spans) { + if (!handlerData || !handlerData.xhr || !handlerData.xhr.__sentry_xhr__) { + return; + } + var xhr = handlerData.xhr.__sentry_xhr__; + if (!shouldCreateSpan(xhr.url)) { + return; + } + // We only capture complete, non-sentry requests + if (handlerData.xhr.__sentry_own_request__) { + return; + } + if (handlerData.endTimestamp && handlerData.xhr.__sentry_xhr_span_id__) { + var span = spans[handlerData.xhr.__sentry_xhr_span_id__]; + if (span) { + span.setData('url', xhr.url); + span.setData('method', xhr.method); + span.setHttpStatus(xhr.status_code); + span.finish(); + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete spans[handlerData.xhr.__sentry_xhr_span_id__]; + } + return; + } + var activeTransaction = utils_2.getActiveTransaction(); + if (activeTransaction) { + var span = activeTransaction.startChild({ + data: tslib_1.__assign(tslib_1.__assign({}, xhr.data), { type: 'xhr' }), + description: xhr.method + " " + xhr.url, + op: 'http', + }); + handlerData.xhr.__sentry_xhr_span_id__ = span.spanId; + spans[handlerData.xhr.__sentry_xhr_span_id__] = span; + if (handlerData.xhr.setRequestHeader) { + try { + handlerData.xhr.setRequestHeader('sentry-trace', span.toTraceparent()); + } + catch (_) { + // Error: InvalidStateError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED. + } + } + } +} +//# sourceMappingURL=request.js.map /***/ }), /* 81 */ @@ -3616,136 +5382,13 @@ formatters.O = function (v) { /***/ }), /* 82 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; - - -var Type = __webpack_require__(945); - -var YAML_DATE_REGEXP = new RegExp( - '^([0-9][0-9][0-9][0-9])' + // [1] year - '-([0-9][0-9])' + // [2] month - '-([0-9][0-9])$'); // [3] day - -var YAML_TIMESTAMP_REGEXP = new RegExp( - '^([0-9][0-9][0-9][0-9])' + // [1] year - '-([0-9][0-9]?)' + // [2] month - '-([0-9][0-9]?)' + // [3] day - '(?:[Tt]|[ \\t]+)' + // ... - '([0-9][0-9]?)' + // [4] hour - ':([0-9][0-9])' + // [5] minute - ':([0-9][0-9])' + // [6] second - '(?:\\.([0-9]*))?' + // [7] fraction - '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour - '(?::([0-9][0-9]))?))?$'); // [11] tz_minute - -function resolveYamlTimestamp(data) { - if (data === null) return false; - if (YAML_DATE_REGEXP.exec(data) !== null) return true; - if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; - return false; -} - -function constructYamlTimestamp(data) { - var match, year, month, day, hour, minute, second, fraction = 0, - delta = null, tz_hour, tz_minute, date; - - match = YAML_DATE_REGEXP.exec(data); - if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); - - if (match === null) throw new Error('Date resolve error'); - - // match: [1] year [2] month [3] day - - year = +(match[1]); - month = +(match[2]) - 1; // JS month starts with 0 - day = +(match[3]); - - if (!match[4]) { // no hour - return new Date(Date.UTC(year, month, day)); - } - - // match: [4] hour [5] minute [6] second [7] fraction - - hour = +(match[4]); - minute = +(match[5]); - second = +(match[6]); - - if (match[7]) { - fraction = match[7].slice(0, 3); - while (fraction.length < 3) { // milli-seconds - fraction += '0'; - } - fraction = +fraction; - } - - // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute - - if (match[9]) { - tz_hour = +(match[10]); - tz_minute = +(match[11] || 0); - delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds - if (match[9] === '-') delta = -delta; - } - - date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); - - if (delta) date.setTime(date.getTime() - delta); - - return date; -} - -function representYamlTimestamp(object /*, style*/) { - return object.toISOString(); -} - -module.exports = new Type('tag:yaml.org,2002:timestamp', { - kind: 'scalar', - resolve: resolveYamlTimestamp, - construct: constructYamlTimestamp, - instanceOf: Date, - represent: representYamlTimestamp -}); +/***/ (function(module) { +module.exports = require("console"); /***/ }), /* 83 */, -/* 84 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -var rng = __webpack_require__(594); -var bytesToUuid = __webpack_require__(643); - -function v4(options, buf, offset) { - var i = buf && offset || 0; - - if (typeof(options) == 'string') { - buf = options === 'binary' ? new Array(16) : null; - options = null; - } - options = options || {}; - - var rnds = options.random || (options.rng || rng)(); - - // 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) { - for (var ii = 0; ii < 16; ++ii) { - buf[i + ii] = rnds[ii]; - } - } - - return buf || bytesToUuid(rnds); -} - -module.exports = v4; - - -/***/ }), +/* 84 */, /* 85 */ /***/ (function(__unusedmodule, exports, __webpack_require__) { @@ -3950,322 +5593,334 @@ module.exports = require("os"); /***/ }), /* 88 */, -/* 89 */ -/***/ (function(module) { - -"use strict"; +/* 89 */, +/* 90 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -}; -module.exports = function (app) { return __awaiter(void 0, void 0, void 0, function () { - function refresh() { - return __awaiter(this, void 0, void 0, function () { - var installations, _a; - return __generator(this, function (_b) { - switch (_b.label) { - case 0: return [4 /*yield*/, getInstallations()]; - case 1: - installations = _b.sent(); - stats.installations = installations.length; - _a = stats; - return [4 /*yield*/, popularInstallations(installations)]; - case 2: - _a.popular = _b.sent(); - return [2 /*return*/]; - } - }); - }); - } - function getInstallations() { - return __awaiter(this, void 0, void 0, function () { - var github; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, app.auth()]; - case 1: - github = _a.sent(); - return [2 /*return*/, github.paginate(github.apps.listInstallations.endpoint.merge({ per_page: 100 }), function (response) { - return response.data; - })]; - } - }); - }); +Object.defineProperty(exports, "__esModule", { value: true }); +var tslib_1 = __webpack_require__(422); +var browser_1 = __webpack_require__(681); +var is_1 = __webpack_require__(613); +var memo_1 = __webpack_require__(666); +var stacktrace_1 = __webpack_require__(277); +var string_1 = __webpack_require__(66); +/** + * Wrap a given object method with a higher-order function + * + * @param source An object that contains a method to be wrapped. + * @param name A name of method to be wrapped. + * @param replacement A function that should be used to wrap a given method. + * @returns void + */ +function fill(source, name, replacement) { + if (!(name in source)) { + return; } - function popularInstallations(installations) { - return __awaiter(this, void 0, void 0, function () { - var popular; - var _this = this; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, Promise.all(installations.map(function (installation) { return __awaiter(_this, void 0, void 0, function () { - var account, github, repositories; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - account = installation.account; - if (ignoredAccounts.includes(account.login.toLowerCase())) { - account.stars = 0; - app.log.debug({ installation: installation }, 'Installation is ignored'); - return [2 /*return*/, account]; - } - return [4 /*yield*/, app.auth(installation.id)]; - case 1: - github = _a.sent(); - return [4 /*yield*/, github.paginate(github.apps.listRepos.endpoint.merge({ per_page: 100 }), function (response) { - return response.data.filter(function (repository) { return !repository.private; }); - })]; - case 2: - repositories = _a.sent(); - account.stars = repositories.reduce(function (stars, repository) { - return stars + repository.stargazers_count; - }, 0); - return [2 /*return*/, account]; - } - }); - }); }))]; - case 1: - popular = _a.sent(); - popular = popular.filter(function (installation) { return installation.stars > 0; }); - return [2 /*return*/, popular.sort(function (a, b) { return b.stars - a.stars; }).slice(0, 10)]; - } + var original = source[name]; + var wrapped = replacement(original); + // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work + // otherwise it'll throw "TypeError: Object.defineProperties called on non-object" + if (typeof wrapped === 'function') { + try { + wrapped.prototype = wrapped.prototype || {}; + Object.defineProperties(wrapped, { + __sentry_original__: { + enumerable: false, + value: original, + }, }); - }); + } + catch (_Oo) { + // This can throw if multiple fill happens on a global object like XMLHttpRequest + // Fixes https://github.com/getsentry/sentry-javascript/issues/2043 + } } - var REFRESH_INTERVAL, stats, initializing, ignoredAccounts; - return __generator(this, function (_a) { - if (process.env.DISABLE_STATS) { - return [2 /*return*/]; - } - REFRESH_INTERVAL = 60 * 60 * 1000; - stats = { installations: 0, popular: [{}] }; - initializing = refresh(); - // Refresh the stats on an interval - setInterval(refresh, REFRESH_INTERVAL); - ignoredAccounts = (process.env.IGNORED_ACCOUNTS || '').toLowerCase().split(','); - // Setup /probot/stats endpoint to return cached stats - app.router.get('/probot/stats', function (req, res) { return __awaiter(void 0, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - // ensure stats are loaded - return [4 /*yield*/, initializing]; - case 1: - // ensure stats are loaded - _a.sent(); - res.json(stats); - return [2 /*return*/]; - } - }); - }); }); - return [2 /*return*/]; - }); -}); }; -//# sourceMappingURL=stats.js.map - -/***/ }), -/* 90 */, -/* 91 */ -/***/ (function(module) { - + source[name] = wrapped; +} +exports.fill = fill; /** - * Helpers. + * Encodes given object into url-friendly format + * + * @param object An object that contains serializable values + * @returns string Encoded */ - -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var w = d * 7; -var y = d * 365.25; - +function urlEncode(object) { + return Object.keys(object) + .map(function (key) { return encodeURIComponent(key) + "=" + encodeURIComponent(object[key]); }) + .join('&'); +} +exports.urlEncode = urlEncode; /** - * Parse or format the given `val`. - * - * Options: + * Transforms any object into an object literal with all it's attributes + * attached to it. * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public + * @param value Initial source that we have to transform in order to be usable by the serializer */ - -module.exports = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isNaN(val) === false) { - return options.long ? fmtLong(val) : fmtShort(val); - } - throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) - ); -}; - +function getWalkSource(value) { + if (is_1.isError(value)) { + var error = value; + var err = { + message: error.message, + name: error.name, + stack: error.stack, + }; + for (var i in error) { + if (Object.prototype.hasOwnProperty.call(error, i)) { + err[i] = error[i]; + } + } + return err; + } + if (is_1.isEvent(value)) { + var event_1 = value; + var source = {}; + source.type = event_1.type; + // Accessing event.target can throw (see getsentry/raven-js#838, #768) + try { + source.target = is_1.isElement(event_1.target) + ? browser_1.htmlTreeAsString(event_1.target) + : Object.prototype.toString.call(event_1.target); + } + catch (_oO) { + source.target = ''; + } + try { + source.currentTarget = is_1.isElement(event_1.currentTarget) + ? browser_1.htmlTreeAsString(event_1.currentTarget) + : Object.prototype.toString.call(event_1.currentTarget); + } + catch (_oO) { + source.currentTarget = ''; + } + if (typeof CustomEvent !== 'undefined' && is_1.isInstanceOf(value, CustomEvent)) { + source.detail = event_1.detail; + } + for (var i in event_1) { + if (Object.prototype.hasOwnProperty.call(event_1, i)) { + source[i] = event_1; + } + } + return source; + } + return value; +} +/** Calculates bytes size of input string */ +function utf8Length(value) { + // eslint-disable-next-line no-bitwise + return ~-encodeURI(value).split(/%..|./).length; +} +/** Calculates bytes size of input object */ +function jsonSize(value) { + return utf8Length(JSON.stringify(value)); +} +/** JSDoc */ +function normalizeToSize(object, +// Default Node.js REPL depth +depth, +// 100kB, as 200kB is max payload size, so half sounds reasonable +maxSize) { + if (depth === void 0) { depth = 3; } + if (maxSize === void 0) { maxSize = 100 * 1024; } + var serialized = normalize(object, depth); + if (jsonSize(serialized) > maxSize) { + return normalizeToSize(object, depth - 1, maxSize); + } + return serialized; +} +exports.normalizeToSize = normalizeToSize; +/** Transforms any input value into a string form, either primitive value or a type of the input */ +function serializeValue(value) { + var type = Object.prototype.toString.call(value); + // Node.js REPL notation + if (typeof value === 'string') { + return value; + } + if (type === '[object Object]') { + return '[Object]'; + } + if (type === '[object Array]') { + return '[Array]'; + } + var normalized = normalizeValue(value); + return is_1.isPrimitive(normalized) ? normalized : type; +} /** - * Parse the given `str` and return milliseconds. + * normalizeValue() * - * @param {String} str - * @return {Number} - * @api private + * Takes unserializable input and make it serializable friendly + * + * - translates undefined/NaN values to "[undefined]"/"[NaN]" respectively, + * - serializes Error objects + * - filter global objects */ - -function parse(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = /^((?:\d+)?\-?\d?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'weeks': - case 'week': - case 'w': - return n * w; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; - } +function normalizeValue(value, key) { + if (key === 'domain' && value && typeof value === 'object' && value._events) { + return '[Domain]'; + } + if (key === 'domainEmitter') { + return '[DomainEmitter]'; + } + if (typeof global !== 'undefined' && value === global) { + return '[Global]'; + } + if (typeof window !== 'undefined' && value === window) { + return '[Window]'; + } + if (typeof document !== 'undefined' && value === document) { + return '[Document]'; + } + // React's SyntheticEvent thingy + if (is_1.isSyntheticEvent(value)) { + return '[SyntheticEvent]'; + } + if (typeof value === 'number' && value !== value) { + return '[NaN]'; + } + if (value === void 0) { + return '[undefined]'; + } + if (typeof value === 'function') { + return "[Function: " + stacktrace_1.getFunctionName(value) + "]"; + } + return value; } - /** - * Short format for `ms`. + * Walks an object to perform a normalization on it + * + * @param key of object that's walked in current iteration + * @param value object to be walked + * @param depth Optional number indicating how deep should walking be performed + * @param memo Optional Memo class handling decycling + */ +// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types +function walk(key, value, depth, memo) { + if (depth === void 0) { depth = +Infinity; } + if (memo === void 0) { memo = new memo_1.Memo(); } + // If we reach the maximum depth, serialize whatever has left + if (depth === 0) { + return serializeValue(value); + } + /* eslint-disable @typescript-eslint/no-unsafe-member-access */ + // If value implements `toJSON` method, call it and return early + if (value !== null && value !== undefined && typeof value.toJSON === 'function') { + return value.toJSON(); + } + /* eslint-enable @typescript-eslint/no-unsafe-member-access */ + // If normalized value is a primitive, there are no branches left to walk, so we can just bail out, as theres no point in going down that branch any further + var normalized = normalizeValue(value, key); + if (is_1.isPrimitive(normalized)) { + return normalized; + } + // Create source that we will use for next itterations, either objectified error object (Error type with extracted keys:value pairs) or the input itself + var source = getWalkSource(value); + // Create an accumulator that will act as a parent for all future itterations of that branch + var acc = Array.isArray(value) ? [] : {}; + // If we already walked that branch, bail out, as it's circular reference + if (memo.memoize(value)) { + return '[Circular ~]'; + } + // Walk all keys of the source + for (var innerKey in source) { + // Avoid iterating over fields in the prototype if they've somehow been exposed to enumeration. + if (!Object.prototype.hasOwnProperty.call(source, innerKey)) { + continue; + } + // Recursively walk through all the child nodes + acc[innerKey] = walk(innerKey, source[innerKey], depth - 1, memo); + } + // Once walked through all the branches, remove the parent from memo storage + memo.unmemoize(value); + // Return accumulated values + return acc; +} +exports.walk = walk; +/** + * normalize() * - * @param {Number} ms - * @return {String} - * @api private + * - Creates a copy to prevent original input mutation + * - Skip non-enumerablers + * - Calls `toJSON` if implemented + * - Removes circular references + * - Translates non-serializeable values (undefined/NaN/Functions) to serializable format + * - Translates known global objects/Classes to a string representations + * - Takes care of Error objects serialization + * - Optionally limit depth of final output */ - -function fmtShort(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return Math.round(ms / d) + 'd'; - } - if (msAbs >= h) { - return Math.round(ms / h) + 'h'; - } - if (msAbs >= m) { - return Math.round(ms / m) + 'm'; - } - if (msAbs >= s) { - return Math.round(ms / s) + 's'; - } - return ms + 'ms'; +// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types +function normalize(input, depth) { + try { + return JSON.parse(JSON.stringify(input, function (key, value) { return walk(key, value, depth); })); + } + catch (_oO) { + return '**non-serializable**'; + } } - +exports.normalize = normalize; /** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private + * Given any captured exception, extract its keys and create a sorted + * and truncated list that will be used inside the event message. + * eg. `Non-error exception captured with keys: foo, bar, baz` */ - -function fmtLong(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return plural(ms, msAbs, d, 'day'); - } - if (msAbs >= h) { - return plural(ms, msAbs, h, 'hour'); - } - if (msAbs >= m) { - return plural(ms, msAbs, m, 'minute'); - } - if (msAbs >= s) { - return plural(ms, msAbs, s, 'second'); - } - return ms + ' ms'; +// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types +function extractExceptionKeysForMessage(exception, maxLength) { + if (maxLength === void 0) { maxLength = 40; } + var keys = Object.keys(getWalkSource(exception)); + keys.sort(); + if (!keys.length) { + return '[object has no keys]'; + } + if (keys[0].length >= maxLength) { + return string_1.truncate(keys[0], maxLength); + } + for (var includedKeys = keys.length; includedKeys > 0; includedKeys--) { + var serialized = keys.slice(0, includedKeys).join(', '); + if (serialized.length > maxLength) { + continue; + } + if (includedKeys === keys.length) { + return serialized; + } + return string_1.truncate(serialized, maxLength); + } + return ''; } - +exports.extractExceptionKeysForMessage = extractExceptionKeysForMessage; /** - * Pluralization helper. + * Given any object, return the new object with removed keys that value was `undefined`. + * Works recursively on objects and arrays. */ - -function plural(ms, msAbs, n, name) { - var isPlural = msAbs >= n * 1.5; - return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); -} - +function dropUndefinedKeys(val) { + var e_1, _a; + if (is_1.isPlainObject(val)) { + var obj = val; + var rv = {}; + try { + for (var _b = tslib_1.__values(Object.keys(obj)), _c = _b.next(); !_c.done; _c = _b.next()) { + var key = _c.value; + if (typeof obj[key] !== 'undefined') { + rv[key] = dropUndefinedKeys(obj[key]); + } + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_c && !_c.done && (_a = _b.return)) _a.call(_b); + } + finally { if (e_1) throw e_1.error; } + } + return rv; + } + if (Array.isArray(val)) { + return val.map(dropUndefinedKeys); + } + return val; +} +exports.dropUndefinedKeys = dropUndefinedKeys; +//# sourceMappingURL=object.js.map /***/ }), +/* 91 */, /* 92 */ /***/ (function(module, __unusedexports, __webpack_require__) { @@ -4312,7 +5967,7 @@ module.exports = { 'shiftjis': { type: '_dbcs', - table: function() { return __webpack_require__(232) }, + table: function() { return __webpack_require__(546) }, encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, encodeSkipVals: [{from: 0xED40, to: 0xF940}], }, @@ -4329,7 +5984,7 @@ module.exports = { 'eucjp': { type: '_dbcs', - table: function() { return __webpack_require__(701) }, + table: function() { return __webpack_require__(658) }, encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, }, @@ -4438,7 +6093,7 @@ module.exports = { 'big5': 'big5hkscs', 'big5hkscs': { type: '_dbcs', - table: function() { return __webpack_require__(393).concat(__webpack_require__(628)) }, + table: function() { return __webpack_require__(393).concat(__webpack_require__(958)) }, encodeSkipVals: [0xa2cc], }, @@ -4452,1404 +6107,378 @@ module.exports = { /* 93 */ /***/ (function(module, __unusedexports, __webpack_require__) { -module.exports = minimatch -minimatch.Minimatch = Minimatch - -var path = { sep: '/' } -try { - path = __webpack_require__(622) -} catch (er) {} - -var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} -var expand = __webpack_require__(306) - -var plTypes = { - '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, - '?': { open: '(?:', close: ')?' }, - '+': { open: '(?:', close: ')+' }, - '*': { open: '(?:', close: ')*' }, - '@': { open: '(?:', close: ')' } -} - -// any single thing other than / -// don't need to escape / when using new RegExp() -var qmark = '[^/]' - -// * => any number of characters -var star = qmark + '*?' - -// ** when dots are allowed. Anything goes, except .. and . -// not (^ or / followed by one or two dots followed by $ or /), -// followed by anything, any number of times. -var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?' - -// not a ^ or / followed by a dot, -// followed by anything, any number of times. -var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' - -// characters that need to be escaped in RegExp. -var reSpecials = charSet('().*{}+?[]^$\\!') - -// "abc" -> { a:true, b:true, c:true } -function charSet (s) { - return s.split('').reduce(function (set, c) { - set[c] = true - return set - }, {}) -} - -// normalizes slashes. -var slashSplit = /\/+/ - -minimatch.filter = filter -function filter (pattern, options) { - options = options || {} - return function (p, i, list) { - return minimatch(p, pattern, options) - } -} - -function ext (a, b) { - a = a || {} - b = b || {} - var t = {} - Object.keys(b).forEach(function (k) { - t[k] = b[k] - }) - Object.keys(a).forEach(function (k) { - t[k] = a[k] - }) - return t -} - -minimatch.defaults = function (def) { - if (!def || !Object.keys(def).length) return minimatch - - var orig = minimatch - - var m = function minimatch (p, pattern, options) { - return orig.minimatch(p, pattern, ext(def, options)) - } - - m.Minimatch = function Minimatch (pattern, options) { - return new orig.Minimatch(pattern, ext(def, options)) - } - - return m -} - -Minimatch.defaults = function (def) { - if (!def || !Object.keys(def).length) return Minimatch - return minimatch.defaults(def).Minimatch -} - -function minimatch (p, pattern, options) { - if (typeof pattern !== 'string') { - throw new TypeError('glob pattern string required') - } - - if (!options) options = {} - - // shortcut: comments match nothing. - if (!options.nocomment && pattern.charAt(0) === '#') { - return false - } - - // "" only matches "" - if (pattern.trim() === '') return p === '' - - return new Minimatch(pattern, options).match(p) -} - -function Minimatch (pattern, options) { - if (!(this instanceof Minimatch)) { - return new Minimatch(pattern, options) - } - - if (typeof pattern !== 'string') { - throw new TypeError('glob pattern string required') - } - - if (!options) options = {} - pattern = pattern.trim() - - // windows support: need to use /, not \ - if (path.sep !== '/') { - pattern = pattern.split(path.sep).join('/') - } - - this.options = options - this.set = [] - this.pattern = pattern - this.regexp = null - this.negate = false - this.comment = false - this.empty = false - - // make the set of regexps etc. - this.make() -} - -Minimatch.prototype.debug = function () {} - -Minimatch.prototype.make = make -function make () { - // don't do it more than once. - if (this._made) return - - var pattern = this.pattern - var options = this.options - - // empty patterns and comments match nothing. - if (!options.nocomment && pattern.charAt(0) === '#') { - this.comment = true - return - } - if (!pattern) { - this.empty = true - return - } - - // step 1: figure out negation, etc. - this.parseNegate() - - // step 2: expand braces - var set = this.globSet = this.braceExpand() - - if (options.debug) this.debug = console.error - - this.debug(this.pattern, set) - - // step 3: now we have a set, so turn each one into a series of path-portion - // matching patterns. - // These will be regexps, except in the case of "**", which is - // set to the GLOBSTAR object for globstar behavior, - // and will not contain any / characters - set = this.globParts = set.map(function (s) { - return s.split(slashSplit) - }) - - this.debug(this.pattern, set) +"use strict"; - // glob --> regexps - set = set.map(function (s, si, set) { - return s.map(this.parse, this) - }, this) - this.debug(this.pattern, set) - // filter out everything that didn't compile properly. - set = set.filter(function (s) { - return s.indexOf(false) === -1 - }) +var common = __webpack_require__(740); - this.debug(this.pattern, set) - this.set = set +function Mark(name, buffer, position, line, column) { + this.name = name; + this.buffer = buffer; + this.position = position; + this.line = line; + this.column = column; } -Minimatch.prototype.parseNegate = parseNegate -function parseNegate () { - var pattern = this.pattern - var negate = false - var options = this.options - var negateOffset = 0 - - if (options.nonegate) return - for (var i = 0, l = pattern.length - ; i < l && pattern.charAt(i) === '!' - ; i++) { - negate = !negate - negateOffset++ - } +Mark.prototype.getSnippet = function getSnippet(indent, maxLength) { + var head, start, tail, end, snippet; - if (negateOffset) this.pattern = pattern.substr(negateOffset) - this.negate = negate -} + if (!this.buffer) return null; -// Brace expansion: -// a{b,c}d -> abd acd -// a{b,}c -> abc ac -// a{0..3}d -> a0d a1d a2d a3d -// a{b,c{d,e}f}g -> abg acdfg acefg -// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg -// -// Invalid sets are not expanded. -// a{2..}b -> a{2..}b -// a{b}c -> a{b}c -minimatch.braceExpand = function (pattern, options) { - return braceExpand(pattern, options) -} + indent = indent || 4; + maxLength = maxLength || 75; -Minimatch.prototype.braceExpand = braceExpand + head = ''; + start = this.position; -function braceExpand (pattern, options) { - if (!options) { - if (this instanceof Minimatch) { - options = this.options - } else { - options = {} + while (start > 0 && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(start - 1)) === -1) { + start -= 1; + if (this.position - start > (maxLength / 2 - 1)) { + head = ' ... '; + start += 5; + break; } } - pattern = typeof pattern === 'undefined' - ? this.pattern : pattern - - if (typeof pattern === 'undefined') { - throw new TypeError('undefined pattern') - } - - if (options.nobrace || - !pattern.match(/\{.*\}/)) { - // shortcut. no need to expand. - return [pattern] - } - - return expand(pattern) -} - -// parse a component of the expanded set. -// At this point, no pattern may contain "/" in it -// so we're going to return a 2d array, where each entry is the full -// pattern, split on '/', and then turned into a regular expression. -// A regexp is made at the end which joins each array with an -// escaped /, and another full one which joins each regexp with |. -// -// Following the lead of Bash 4.1, note that "**" only has special meaning -// when it is the *only* thing in a path portion. Otherwise, any series -// of * is equivalent to a single *. Globstar behavior is enabled by -// default, and can be disabled by setting options.noglobstar. -Minimatch.prototype.parse = parse -var SUBPARSE = {} -function parse (pattern, isSub) { - if (pattern.length > 1024 * 64) { - throw new TypeError('pattern is too long') - } - - var options = this.options - - // shortcuts - if (!options.noglobstar && pattern === '**') return GLOBSTAR - if (pattern === '') return '' - - var re = '' - var hasMagic = !!options.nocase - var escaping = false - // ? => one single character - var patternListStack = [] - var negativeLists = [] - var stateChar - var inClass = false - var reClassStart = -1 - var classStart = -1 - // . and .. never match anything that doesn't start with ., - // even when options.dot is set. - var patternStart = pattern.charAt(0) === '.' ? '' // anything - // not (start or / followed by . or .. followed by / or end) - : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' - : '(?!\\.)' - var self = this + tail = ''; + end = this.position; - function clearStateChar () { - if (stateChar) { - // we had some state-tracking character - // that wasn't consumed by this pass. - switch (stateChar) { - case '*': - re += star - hasMagic = true - break - case '?': - re += qmark - hasMagic = true - break - default: - re += '\\' + stateChar - break - } - self.debug('clearStateChar %j %j', stateChar, re) - stateChar = false + while (end < this.buffer.length && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(end)) === -1) { + end += 1; + if (end - this.position > (maxLength / 2 - 1)) { + tail = ' ... '; + end -= 5; + break; } } - for (var i = 0, len = pattern.length, c - ; (i < len) && (c = pattern.charAt(i)) - ; i++) { - this.debug('%s\t%s %s %j', pattern, i, re, c) - - // skip over any that are escaped. - if (escaping && reSpecials[c]) { - re += '\\' + c - escaping = false - continue - } - - switch (c) { - case '/': - // completely not allowed, even escaped. - // Should already be path-split by now. - return false - - case '\\': - clearStateChar() - escaping = true - continue - - // the various stateChar values - // for the "extglob" stuff. - case '?': - case '*': - case '+': - case '@': - case '!': - this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) - - // all of those are literals inside a class, except that - // the glob [!a] means [^a] in regexp - if (inClass) { - this.debug(' in class') - if (c === '!' && i === classStart + 1) c = '^' - re += c - continue - } - - // if we already have a stateChar, then it means - // that there was something like ** or +? in there. - // Handle the stateChar, then proceed with this one. - self.debug('call clearStateChar %j', stateChar) - clearStateChar() - stateChar = c - // if extglob is disabled, then +(asdf|foo) isn't a thing. - // just clear the statechar *now*, rather than even diving into - // the patternList stuff. - if (options.noext) clearStateChar() - continue - - case '(': - if (inClass) { - re += '(' - continue - } - - if (!stateChar) { - re += '\\(' - continue - } - - patternListStack.push({ - type: stateChar, - start: i - 1, - reStart: re.length, - open: plTypes[stateChar].open, - close: plTypes[stateChar].close - }) - // negation is (?:(?!js)[^/]*) - re += stateChar === '!' ? '(?:(?!(?:' : '(?:' - this.debug('plType %j %j', stateChar, re) - stateChar = false - continue - - case ')': - if (inClass || !patternListStack.length) { - re += '\\)' - continue - } - - clearStateChar() - hasMagic = true - var pl = patternListStack.pop() - // negation is (?:(?!js)[^/]*) - // The others are (?:) - re += pl.close - if (pl.type === '!') { - negativeLists.push(pl) - } - pl.reEnd = re.length - continue - - case '|': - if (inClass || !patternListStack.length || escaping) { - re += '\\|' - escaping = false - continue - } - - clearStateChar() - re += '|' - continue - - // these are mostly the same in regexp and glob - case '[': - // swallow any state-tracking char before the [ - clearStateChar() - - if (inClass) { - re += '\\' + c - continue - } - - inClass = true - classStart = i - reClassStart = re.length - re += c - continue - - case ']': - // a right bracket shall lose its special - // meaning and represent itself in - // a bracket expression if it occurs - // first in the list. -- POSIX.2 2.8.3.2 - if (i === classStart + 1 || !inClass) { - re += '\\' + c - escaping = false - continue - } - - // handle the case where we left a class open. - // "[z-a]" is valid, equivalent to "\[z-a\]" - if (inClass) { - // split where the last [ was, make sure we don't have - // an invalid re. if so, re-walk the contents of the - // would-be class to re-translate any characters that - // were passed through as-is - // TODO: It would probably be faster to determine this - // without a try/catch and a new RegExp, but it's tricky - // to do safely. For now, this is safe and works. - var cs = pattern.substring(classStart + 1, i) - try { - RegExp('[' + cs + ']') - } catch (er) { - // not a valid class! - var sp = this.parse(cs, SUBPARSE) - re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]' - hasMagic = hasMagic || sp[1] - inClass = false - continue - } - } - - // finish up the class. - hasMagic = true - inClass = false - re += c - continue - - default: - // swallow any state char that wasn't consumed - clearStateChar() - - if (escaping) { - // no need - escaping = false - } else if (reSpecials[c] - && !(c === '^' && inClass)) { - re += '\\' - } - - re += c - - } // switch - } // for - - // handle the case where we left a class open. - // "[abc" is valid, equivalent to "\[abc" - if (inClass) { - // split where the last [ was, and escape it - // this is a huge pita. We now have to re-walk - // the contents of the would-be class to re-translate - // any characters that were passed through as-is - cs = pattern.substr(classStart + 1) - sp = this.parse(cs, SUBPARSE) - re = re.substr(0, reClassStart) + '\\[' + sp[0] - hasMagic = hasMagic || sp[1] - } - - // handle the case where we had a +( thing at the *end* - // of the pattern. - // each pattern list stack adds 3 chars, and we need to go through - // and escape any | chars that were passed through as-is for the regexp. - // Go through and escape them, taking care not to double-escape any - // | chars that were already escaped. - for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { - var tail = re.slice(pl.reStart + pl.open.length) - this.debug('setting tail', re, pl) - // maybe some even number of \, then maybe 1 \, followed by a | - tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) { - if (!$2) { - // the | isn't already escaped, so escape it. - $2 = '\\' - } - - // need to escape all those slashes *again*, without escaping the - // one that we need for escaping the | character. As it works out, - // escaping an even number of slashes can be done by simply repeating - // it exactly after itself. That's why this trick works. - // - // I am sorry that you have to see this. - return $1 + $1 + $2 + '|' - }) + snippet = this.buffer.slice(start, end); - this.debug('tail=%j\n %s', tail, tail, pl, re) - var t = pl.type === '*' ? star - : pl.type === '?' ? qmark - : '\\' + pl.type + return common.repeat(' ', indent) + head + snippet + tail + '\n' + + common.repeat(' ', indent + this.position - start + head.length) + '^'; +}; - hasMagic = true - re = re.slice(0, pl.reStart) + t + '\\(' + tail - } - // handle trailing things that only matter at the very end. - clearStateChar() - if (escaping) { - // trailing \\ - re += '\\\\' - } +Mark.prototype.toString = function toString(compact) { + var snippet, where = ''; - // only need to apply the nodot start if the re starts with - // something that could conceivably capture a dot - var addPatternStart = false - switch (re.charAt(0)) { - case '.': - case '[': - case '(': addPatternStart = true + if (this.name) { + where += 'in "' + this.name + '" '; } - // Hack to work around lack of negative lookbehind in JS - // A pattern like: *.!(x).!(y|z) needs to ensure that a name - // like 'a.xyz.yz' doesn't match. So, the first negative - // lookahead, has to look ALL the way ahead, to the end of - // the pattern. - for (var n = negativeLists.length - 1; n > -1; n--) { - var nl = negativeLists[n] - - var nlBefore = re.slice(0, nl.reStart) - var nlFirst = re.slice(nl.reStart, nl.reEnd - 8) - var nlLast = re.slice(nl.reEnd - 8, nl.reEnd) - var nlAfter = re.slice(nl.reEnd) - - nlLast += nlAfter + where += 'at line ' + (this.line + 1) + ', column ' + (this.column + 1); - // Handle nested stuff like *(*.js|!(*.json)), where open parens - // mean that we should *not* include the ) in the bit that is considered - // "after" the negated section. - var openParensBefore = nlBefore.split('(').length - 1 - var cleanAfter = nlAfter - for (i = 0; i < openParensBefore; i++) { - cleanAfter = cleanAfter.replace(/\)[+*?]?/, '') - } - nlAfter = cleanAfter + if (!compact) { + snippet = this.getSnippet(); - var dollar = '' - if (nlAfter === '' && isSub !== SUBPARSE) { - dollar = '$' + if (snippet) { + where += ':\n' + snippet; } - var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast - re = newRe - } - - // if the re is not "" at this point, then we need to make sure - // it doesn't match against an empty path part. - // Otherwise a/* will match a/, which it should not. - if (re !== '' && hasMagic) { - re = '(?=.)' + re - } - - if (addPatternStart) { - re = patternStart + re - } - - // parsing just a piece of a larger pattern. - if (isSub === SUBPARSE) { - return [re, hasMagic] - } - - // skip the regexp for non-magical patterns - // unescape anything in it, though, so that it'll be - // an exact match against a file etc. - if (!hasMagic) { - return globUnescape(pattern) - } - - var flags = options.nocase ? 'i' : '' - try { - var regExp = new RegExp('^' + re + '$', flags) - } catch (er) { - // If it was an invalid regular expression, then it can't match - // anything. This trick looks for a character after the end of - // the string, which is of course impossible, except in multi-line - // mode, but it's not a /m regex. - return new RegExp('$.') - } - - regExp._glob = pattern - regExp._src = re - - return regExp -} - -minimatch.makeRe = function (pattern, options) { - return new Minimatch(pattern, options || {}).makeRe() -} - -Minimatch.prototype.makeRe = makeRe -function makeRe () { - if (this.regexp || this.regexp === false) return this.regexp - - // at this point, this.set is a 2d array of partial - // pattern strings, or "**". - // - // It's better to use .match(). This function shouldn't - // be used, really, but it's pretty convenient sometimes, - // when you just want to work with a regex. - var set = this.set - - if (!set.length) { - this.regexp = false - return this.regexp - } - var options = this.options - - var twoStar = options.noglobstar ? star - : options.dot ? twoStarDot - : twoStarNoDot - var flags = options.nocase ? 'i' : '' - - var re = set.map(function (pattern) { - return pattern.map(function (p) { - return (p === GLOBSTAR) ? twoStar - : (typeof p === 'string') ? regExpEscape(p) - : p._src - }).join('\\\/') - }).join('|') - - // must match entire pattern - // ending in a * or ** will make it less strict. - re = '^(?:' + re + ')$' - - // can match anything, as long as it's not this. - if (this.negate) re = '^(?!' + re + ').*$' - - try { - this.regexp = new RegExp(re, flags) - } catch (ex) { - this.regexp = false - } - return this.regexp -} - -minimatch.match = function (list, pattern, options) { - options = options || {} - var mm = new Minimatch(pattern, options) - list = list.filter(function (f) { - return mm.match(f) - }) - if (mm.options.nonull && !list.length) { - list.push(pattern) } - return list -} -Minimatch.prototype.match = match -function match (f, partial) { - this.debug('match', f, this.pattern) - // short-circuit in the case of busted things. - // comments, etc. - if (this.comment) return false - if (this.empty) return f === '' - - if (f === '/' && partial) return true - - var options = this.options + return where; +}; - // windows: need to use /, not \ - if (path.sep !== '/') { - f = f.split(path.sep).join('/') - } - // treat the test path as a set of pathparts. - f = f.split(slashSplit) - this.debug(this.pattern, 'split', f) +module.exports = Mark; - // just ONE of the pattern sets in this.set needs to match - // in order for it to be valid. If negating, then just one - // match means that we have failed. - // Either way, return on the first hit. - var set = this.set - this.debug(this.pattern, 'set', set) +/***/ }), +/* 94 */ +/***/ (function(__unusedmodule, exports) { - // Find the basename of the path by looking for the last non-empty segment - var filename - var i - for (i = f.length - 1; i >= 0; i--) { - filename = f[i] - if (filename) break - } +"use strict"; - for (i = 0; i < set.length; i++) { - var pattern = set[i] - var file = f - if (options.matchBase && pattern.length === 1) { - file = [filename] +Object.defineProperty(exports, "__esModule", { value: true }); +class AbstractConnector { + constructor() { + this.connecting = false; } - var hit = this.matchOne(file, pattern, partial) - if (hit) { - if (options.flipNegate) return true - return !this.negate + check(info) { + return true; } - } - - // didn't get any hits. this is success if it's a negative - // pattern, failure otherwise. - if (options.flipNegate) return false - return this.negate -} - -// set partial to true to test if, for example, -// "/a/b" matches the start of "/*/b/*/d" -// Partial means, if you run out of file before you run -// out of pattern, then that's fine, as long as all -// the parts match. -Minimatch.prototype.matchOne = function (file, pattern, partial) { - var options = this.options - - this.debug('matchOne', - { 'this': this, file: file, pattern: pattern }) - - this.debug('matchOne', file.length, pattern.length) - - for (var fi = 0, - pi = 0, - fl = file.length, - pl = pattern.length - ; (fi < fl) && (pi < pl) - ; fi++, pi++) { - this.debug('matchOne loop') - var p = pattern[pi] - var f = file[fi] - - this.debug(pattern, p, f) - - // should be impossible. - // some invalid regexp stuff in the set. - if (p === false) return false - - if (p === GLOBSTAR) { - this.debug('GLOBSTAR', [pattern, p, f]) - - // "**" - // a/**/b/**/c would match the following: - // a/b/x/y/z/c - // a/x/y/z/b/c - // a/b/x/b/x/c - // a/b/c - // To do this, take the rest of the pattern after - // the **, and see if it would match the file remainder. - // If so, return success. - // If not, the ** "swallows" a segment, and try again. - // This is recursively awful. - // - // a/**/b/**/c matching a/b/x/y/z/c - // - a matches a - // - doublestar - // - matchOne(b/x/y/z/c, b/**/c) - // - b matches b - // - doublestar - // - matchOne(x/y/z/c, c) -> no - // - matchOne(y/z/c, c) -> no - // - matchOne(z/c, c) -> no - // - matchOne(c, c) yes, hit - var fr = fi - var pr = pi + 1 - if (pr === pl) { - this.debug('** at the end') - // a ** at the end will just swallow the rest. - // We have found a match. - // however, it will not swallow /.x, unless - // options.dot is set. - // . and .. are *never* matched by **, for explosively - // exponential reasons. - for (; fi < fl; fi++) { - if (file[fi] === '.' || file[fi] === '..' || - (!options.dot && file[fi].charAt(0) === '.')) return false - } - return true - } - - // ok, let's see if we can swallow whatever we can. - while (fr < fl) { - var swallowee = file[fr] - - this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) - - // XXX remove this slice. Just pass the start index. - if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { - this.debug('globstar found match!', fr, fl, swallowee) - // found a match. - return true - } else { - // can't swallow "." or ".." ever. - // can only swallow ".foo" when explicitly asked. - if (swallowee === '.' || swallowee === '..' || - (!options.dot && swallowee.charAt(0) === '.')) { - this.debug('dot detected!', file, fr, pattern, pr) - break - } - - // ** swallows a segment, and continue. - this.debug('globstar swallow a segment, and continue') - fr++ + disconnect() { + this.connecting = false; + if (this.stream) { + this.stream.end(); } - } - - // no match was found. - // However, in partial mode, we can't say this is necessarily over. - // If there's more *pattern* left, then - if (partial) { - // ran out of file - this.debug('\n>>> no match, partial?', file, fr, pattern, pr) - if (fr === fl) return true - } - return false } - - // something other than ** - // non-magic patterns just have to match exactly - // patterns with magic have been turned into regexps. - var hit - if (typeof p === 'string') { - if (options.nocase) { - hit = f.toLowerCase() === p.toLowerCase() - } else { - hit = f === p - } - this.debug('string match', p, f, hit) - } else { - hit = f.match(p) - this.debug('pattern match', p, f, hit) - } - - if (!hit) return false - } - - // Note: ending in / means that we'll get a final "" - // at the end of the pattern. This can only match a - // corresponding "" at the end of the file. - // If the file ends in /, then it can only match a - // a pattern that ends in /, unless the pattern just - // doesn't have any more for it. But, a/b/ should *not* - // match "a/b/*", even though "" matches against the - // [^/]*? pattern, except in partial mode, where it might - // simply not be reached yet. - // However, a/b/ should still satisfy a/* - - // now either we fell off the end of the pattern, or we're done. - if (fi === fl && pi === pl) { - // ran out of pattern and filename at the same time. - // an exact hit! - return true - } else if (fi === fl) { - // ran out of file, but still had pattern left. - // this is ok if we're doing the match as part of - // a glob fs traversal. - return partial - } else if (pi === pl) { - // ran out of pattern, still have file left. - // this is only acceptable if we're on the very last - // empty segment of a file with a trailing slash. - // a/* should match a/b/ - var emptyFileEnd = (fi === fl - 1) && (file[fi] === '') - return emptyFileEnd - } - - // should be unreachable. - throw new Error('wtf?') -} - -// replace stuff like \* with * -function globUnescape (s) { - return s.replace(/\\(.)/g, '$1') -} - -function regExpEscape (s) { - return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') } +exports.default = AbstractConnector; /***/ }), -/* 94 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { +/* 95 */, +/* 96 */ +/***/ (function(module) { -/* - * Copyright 2009-2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE.txt or: - * http://opensource.org/licenses/BSD-3-Clause +/** + * lodash 4.0.1 (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright 2012-2016 The Dojo Foundation + * Based on Underscore.js 1.8.3 + * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + * Available under MIT license */ -exports.SourceMapGenerator = __webpack_require__(821).SourceMapGenerator; -exports.SourceMapConsumer = __webpack_require__(276).SourceMapConsumer; -exports.SourceNode = __webpack_require__(841).SourceNode; +/** `Object#toString` result references. */ +var stringTag = '[object String]'; + +/** Used for built-in method references. */ +var objectProto = Object.prototype; -/***/ }), -/* 95 */, -/* 96 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +/** + * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; -var baseIsMap = __webpack_require__(229), - baseUnary = __webpack_require__(157), - nodeUtil = __webpack_require__(344); +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @type Function + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; -/* Node.js helper references. */ -var nodeIsMap = nodeUtil && nodeUtil.isMap; +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} /** - * Checks if `value` is classified as a `Map` object. + * Checks if `value` is classified as a `String` primitive or object. * * @static * @memberOf _ - * @since 4.3.0 * @category Lang * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a map, else `false`. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * - * _.isMap(new Map); + * _.isString('abc'); * // => true * - * _.isMap(new WeakMap); + * _.isString(1); * // => false */ -var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; +function isString(value) { + return typeof value == 'string' || + (!isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag); +} -module.exports = isMap; +module.exports = isString; /***/ }), /* 97 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; - - -var util = __webpack_require__(669); -var format = util.format; -var http = __webpack_require__(605); -var xtend = __webpack_require__(141); -var ansicolors = __webpack_require__(535); -var ansistyles = __webpack_require__(494); - -var styles = xtend(ansistyles, ansicolors); - -// Most of this code is lifted directly from the bunyan ./bin file and should be cleaned up once there is more time -var OM_LONG = 1; -var OM_JSON = 2; -var OM_INSPECT = 3; -var OM_SIMPLE = 4; -var OM_SHORT = 5; -var OM_BUNYAN = 6; -var OM_FROM_NAME = { - 'long': OM_LONG, - 'json': OM_JSON, - 'inspect': OM_INSPECT, - 'simple': OM_SIMPLE, - 'short': OM_SHORT, - 'bunyan': OM_BUNYAN -}; +/***/ (function(module) { -// Levels -var TRACE = 10; -var DEBUG = 20; -var INFO = 30; -var WARN = 40; -var ERROR = 50; -var FATAL = 60; - -var levelFromName = { - 'trace': TRACE, - 'debug': DEBUG, - 'info': INFO, - 'warn': WARN, - 'error': ERROR, - 'fatal': FATAL -}; -var nameFromLevel = {}; -var upperNameFromLevel = {}; -var upperPaddedNameFromLevel = {}; -Object.keys(levelFromName).forEach(function (name) { - var lvl = levelFromName[name]; - nameFromLevel[lvl] = name; - upperNameFromLevel[lvl] = name.toUpperCase(); - upperPaddedNameFromLevel[lvl] = ( - name.length === 4 ? ' ' : '') + name.toUpperCase(); -}); +module.exports = stringify +stringify.default = stringify +stringify.stable = deterministicStringify +stringify.stableStringify = deterministicStringify +var arr = [] +var replacerStack = [] -/** - * Is this a valid Bunyan log record. - */ -function isValidRecord(rec) { - if (rec.v === null || - rec.level === null || - rec.name === null || - rec.hostname === null || - rec.pid === null || - rec.time === null || - rec.msg === null) { - // Not valid Bunyan log. - return false; +// Regular stringify +function stringify (obj, replacer, spacer) { + decirc(obj, '', [], undefined) + var res + if (replacerStack.length === 0) { + res = JSON.stringify(obj, replacer, spacer) } else { - return true; + res = JSON.stringify(obj, replaceGetterValues(replacer), spacer) } + while (arr.length !== 0) { + var part = arr.pop() + if (part.length === 4) { + Object.defineProperty(part[0], part[1], part[3]) + } else { + part[0][part[1]] = part[2] + } + } + return res } - -function indent(s) { - return ' ' + s.split(/\r?\n/).join('\n '); -} - -function stylizeWithColor(s, color) { - if (!s) return ''; - var fn = styles[color]; - return fn ? fn(s) : s; +function decirc (val, k, stack, parent) { + var i + if (typeof val === 'object' && val !== null) { + for (i = 0; i < stack.length; i++) { + if (stack[i] === val) { + var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k) + if (propertyDescriptor.get !== undefined) { + if (propertyDescriptor.configurable) { + Object.defineProperty(parent, k, { value: '[Circular]' }) + arr.push([parent, k, val, propertyDescriptor]) + } else { + replacerStack.push([val, k]) + } + } else { + parent[k] = '[Circular]' + arr.push([parent, k, val]) + } + return + } + } + stack.push(val) + // Optimize for Arrays. Big arrays could kill the performance otherwise! + if (Array.isArray(val)) { + for (i = 0; i < val.length; i++) { + decirc(val[i], i, stack, val) + } + } else { + var keys = Object.keys(val) + for (i = 0; i < keys.length; i++) { + var key = keys[i] + decirc(val[key], key, stack, val) + } + } + stack.pop() + } } -function stylizeWithoutColor(str, color) { - return str; +// Stable-stringify +function compareFunction (a, b) { + if (a < b) { + return -1 + } + if (a > b) { + return 1 + } + return 0 } -/** - * @param {int} level is the level of the record. - * @return The level value to its String representation. - * This is only used on json-related formats output and first suggested at - * https://github.com/trentm/node-bunyan/issues/194#issuecomment-64858117 - */ -function mapLevelToName(level) { - switch (level) { - case TRACE: - return 'TRACE'; - case DEBUG: - return 'DEBUG'; - case INFO: - return 'INFO'; - case WARN: - return 'WARN'; - case ERROR: - return 'ERROR'; - case FATAL: - return 'FATAL'; - } -} - -/** - * Print out a single result, considering input options. - */ -module.exports = function formatRecord(rec, opts) { - - function _res(res) { - var s = ''; - if (res.header) { - s += res.header.trimRight(); - } else if (res.headers) { - if (res.statusCode) { - s += format('HTTP/1.1 %s %s\n', res.statusCode, - http.STATUS_CODES[res.statusCode]); - } - var headers = res.headers; - s += Object.keys(headers).map( - function (h) { return h + ': ' + headers[h]; }).join('\n'); - } - delete res.header; - delete res.headers; - delete res.statusCode; - if (res.body) { - s += '\n\n' + (typeof (res.body) === 'object' - ? JSON.stringify(res.body, null, 2) : res.body); - delete res.body; - } - if (res.trailer) { - s += '\n' + res.trailer; - } - delete res.trailer; - if (s) { - details.push(indent(s)); - } - // E.g. for extra 'foo' field on 'res', add 'res.foo' at - // top-level. This *does* have the potential to stomp on a - // literal 'res.foo' key. - Object.keys(res).forEach(function (k) { - rec['res.' + k] = res[k]; - }); +function deterministicStringify (obj, replacer, spacer) { + var tmp = deterministicDecirc(obj, '', [], undefined) || obj + var res + if (replacerStack.length === 0) { + res = JSON.stringify(tmp, replacer, spacer) + } else { + res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer) } - - var short = false; - var time; - var line = rec.line; - var stylize = opts.color ? stylizeWithColor : stylizeWithoutColor; - var outputMode = isNaN(opts.outputMode) ? OM_FROM_NAME[opts.outputMode] : opts.outputMode; - - switch (outputMode) { - case OM_SHORT: - short = true; - /* falls through */ - case OM_LONG: - // [time] LEVEL: name[/comp]/pid on hostname (src): msg* (extras...) - // msg* - // -- - // long and multi-line extras - // ... - // If 'msg' is single-line, then it goes in the top line. - // If 'req', show the request. - // If 'res', show the response. - // If 'err' and 'err.stack' then show that. - if (!isValidRecord(rec)) { - return line + '\n'; - } - - delete rec.v; - - /* - * We assume the Date is formatted according to ISO8601, in which - * case we can safely chop off the date information. - */ - if (short && rec.time[10] == 'T') { - time = rec.time.substr(11); - time = stylize(time, 'brightBlack'); + while (arr.length !== 0) { + var part = arr.pop() + if (part.length === 4) { + Object.defineProperty(part[0], part[1], part[3]) } else { - time = stylize('[' + rec.time + ']', 'brightBlack'); - } - - delete rec.time; - - var nameStr = rec.name; - delete rec.name; - - if (rec.component) { - nameStr += '/' + rec.component; + part[0][part[1]] = part[2] } - delete rec.component; - - if (!short) - nameStr += '/' + rec.pid; - delete rec.pid; + } + return res +} - var level = (upperPaddedNameFromLevel[rec.level] || 'LVL' + rec.level); - if (opts.color) { - var colorFromLevel = opts.colorFromLevel || { - 10: 'brightBlack', // TRACE - 20: 'brightBlack', // DEBUG - 30: 'cyan', // INFO - 40: 'magenta', // WARN - 50: 'red', // ERROR - 60: 'inverse', // FATAL - }; - level = stylize(level, colorFromLevel[rec.level]); - } - delete rec.level; - - var src = ''; - var s; - var headers; - var hostHeaderLine = ''; - if (rec.src && rec.src.file) { - s = rec.src; - if (s.func) { - src = format(' (%s:%d in %s)', s.file, s.line, s.func); - } else { - src = format(' (%s:%d)', s.file, s.line); +function deterministicDecirc (val, k, stack, parent) { + var i + if (typeof val === 'object' && val !== null) { + for (i = 0; i < stack.length; i++) { + if (stack[i] === val) { + var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k) + if (propertyDescriptor.get !== undefined) { + if (propertyDescriptor.configurable) { + Object.defineProperty(parent, k, { value: '[Circular]' }) + arr.push([parent, k, val, propertyDescriptor]) + } else { + replacerStack.push([val, k]) + } + } else { + parent[k] = '[Circular]' + arr.push([parent, k, val]) + } + return } - src = stylize(src, 'green'); } - delete rec.src; - - var hostname = rec.hostname; - delete rec.hostname; - - var extras = []; - var details = []; - - if (rec.req_id) { - extras.push('req_id=' + rec.req_id); + if (typeof val.toJSON === 'function') { + return } - delete rec.req_id; - - var onelineMsg; - if (rec.msg.indexOf('\n') !== -1) { - onelineMsg = ''; - details.push(indent(stylize(rec.msg, 'cyan'))); + stack.push(val) + // Optimize for Arrays. Big arrays could kill the performance otherwise! + if (Array.isArray(val)) { + for (i = 0; i < val.length; i++) { + deterministicDecirc(val[i], i, stack, val) + } } else { - onelineMsg = ' ' + stylize(rec.msg, 'cyan'); - } - delete rec.msg; - - if (rec.req && typeof (rec.req) === 'object') { - var req = rec.req; - delete rec.req; - headers = req.headers; - s = format('%s %s HTTP/%s%s', req.method, - req.url, - req.httpVersion || '1.1', - (headers ? - '\n' + Object.keys(headers).map(function (h) { - return h + ': ' + headers[h]; - }).join('\n') : - '') - ); - delete req.url; - delete req.method; - delete req.httpVersion; - delete req.headers; - if (req.body) { - s += '\n\n' + (typeof (req.body) === 'object' - ? JSON.stringify(req.body, null, 2) : req.body); - delete req.body; - } - if (req.trailers && Object.keys(req.trailers) > 0) { - s += '\n' + Object.keys(req.trailers).map(function (t) { - return t + ': ' + req.trailers[t]; - }).join('\n'); - } - delete req.trailers; - details.push(indent(s)); - // E.g. for extra 'foo' field on 'req', add 'req.foo' at - // top-level. This *does* have the potential to stomp on a - // literal 'req.foo' key. - Object.keys(req).forEach(function (k) { - rec['req.' + k] = req[k]; - }) - } - - if (rec.client_req && typeof (rec.client_req) === 'object') { - var client_req = rec.client_req; - delete rec.client_req; - headers = client_req.headers; - s = ''; - if (client_req.address) { - hostHeaderLine = 'Host: ' + client_req.address; - if (client_req.port) - hostHeaderLine += ':' + client_req.port; - hostHeaderLine += '\n'; - } - delete client_req.headers; - delete client_req.address; - delete client_req.port; - s += format('%s %s HTTP/%s\n%s%s', client_req.method, - client_req.url, - client_req.httpVersion || '1.1', - hostHeaderLine, - (headers ? - Object.keys(headers).map( - function (h) { - return h + ': ' + headers[h]; - }).join('\n') : - '')); - delete client_req.method; - delete client_req.url; - delete client_req.httpVersion; - if (client_req.body) { - s += '\n\n' + (typeof (client_req.body) === 'object' ? - JSON.stringify(client_req.body, null, 2) : - client_req.body); - delete client_req.body; - } - // E.g. for extra 'foo' field on 'client_req', add - // 'client_req.foo' at top-level. This *does* have the potential - // to stomp on a literal 'client_req.foo' key. - Object.keys(client_req).forEach(function (k) { - rec['client_req.' + k] = client_req[k]; - }) - details.push(indent(s)); - } - - - if (rec.res && typeof (rec.res) === 'object') { - _res(rec.res); - delete rec.res; - } - if (rec.client_res && typeof (rec.client_res) === 'object') { - _res(rec.client_res); - delete rec.res; - } - - if (rec.err && rec.err.stack) { - details.push(indent(rec.err.stack)); - delete rec.err; - } - - var leftover = Object.keys(rec); - for (var i = 0; i < leftover.length; i++) { - var key = leftover[i]; - var value = rec[key]; - var stringified = false; - if (typeof (value) !== 'string') { - value = JSON.stringify(value, null, 2); - stringified = true; + // Create a temporary object in the required way + var tmp = {} + var keys = Object.keys(val).sort(compareFunction) + for (i = 0; i < keys.length; i++) { + var key = keys[i] + deterministicDecirc(val[key], key, stack, val) + tmp[key] = val[key] } - if (value.indexOf('\n') !== -1 || value.length > 50) { - details.push(indent(key + ': ' + value)); - } else if (!stringified && (value.indexOf(' ') != -1 || - value.length === 0)) - { - extras.push(key + '=' + JSON.stringify(value)); + if (parent !== undefined) { + arr.push([parent, k, val]) + parent[k] = tmp } else { - extras.push(key + '=' + value); - } - } - - extras = stylize( - (extras.length ? ' (' + extras.join(', ') + ')' : ''), 'brightBlack'); - details = stylize( - (details.length ? details.join('\n --\n') + '\n' : ''), 'brightBlack'); - if (!short) - return format('%s %s: %s on %s%s:%s%s\n%s', - time, - level, - nameStr, - hostname || '', - src, - onelineMsg, - extras, - details); - else - return format('%s %s %s:%s%s\n%s', - time, - level, - nameStr, - onelineMsg, - extras, - details); - break; - - case OM_INSPECT: - return util.inspect(rec, false, Infinity, true) + '\n'; - - case OM_BUNYAN: - if (opts.levelInString) { - rec.level = mapLevelToName(rec.level); - } - return JSON.stringify(rec, null, 0) + '\n'; - - case OM_JSON: - if (opts.levelInString) { - rec.level = mapLevelToName(rec.level); + return tmp + } } - return JSON.stringify(rec, null, opts.jsonIndent) + '\n'; + stack.pop() + } +} - case OM_SIMPLE: - /* JSSTYLED */ - // - if (!isValidRecord(rec)) { - return line + '\n'; +// wraps replacer function to handle values we couldn't replace +// and mark them as [Circular] +function replaceGetterValues (replacer) { + replacer = replacer !== undefined ? replacer : function (k, v) { return v } + return function (key, val) { + if (replacerStack.length > 0) { + for (var i = 0; i < replacerStack.length; i++) { + var part = replacerStack[i] + if (part[1] === key && part[0] === val) { + val = '[Circular]' + replacerStack.splice(i, 1) + break + } + } } - return format('%s - %s\n', - upperNameFromLevel[rec.level] || 'LVL' + rec.level, - rec.msg); - default: - throw new Error('unknown output mode: '+opts.outputMode); + return replacer.call(this, key, val) } } - /***/ }), /* 98 */ /***/ (function(__unusedmodule, exports, __webpack_require__) { @@ -5859,7 +6488,7 @@ module.exports = function formatRecord(rec, opts) { Object.defineProperty(exports, "__esModule", { value: true }); const events_1 = __webpack_require__(614); const utils_1 = __webpack_require__(200); -const util_1 = __webpack_require__(104); +const util_1 = __webpack_require__(372); const redis_1 = __webpack_require__(837); const debug = utils_1.Debug("cluster:connectionPool"); class ConnectionPool extends events_1.EventEmitter { @@ -6033,748 +6662,962 @@ module.exports = new Type('tag:yaml.org,2002:set', { /***/ }), -/* 101 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.GitHubAPI = exports.ProbotOctokit = void 0; -var plugin_enterprise_compatibility_1 = __webpack_require__(725); -var plugin_retry_1 = __webpack_require__(133); -var plugin_throttling_1 = __webpack_require__(617); -var rest_1 = __webpack_require__(400); -var graphql_1 = __webpack_require__(582); -var logging_1 = __webpack_require__(113); -var pagination_1 = __webpack_require__(327); -exports.ProbotOctokit = rest_1.Octokit - .plugin([plugin_throttling_1.throttling, plugin_retry_1.retry, plugin_enterprise_compatibility_1.enterpriseCompatibility]); -/** - * the [@octokit/rest Node.js module](https://github.com/octokit/rest.js), - * which wraps the [GitHub API](https://developer.github.com/v3/) and allows - * you to do almost anything programmatically that you can do through a web - * browser. - * @see {@link https://github.com/octokit/rest.js} - */ -function GitHubAPI(options) { - if (options === void 0) { options = {}; } - var OctokitFromOptions = options.Octokit || exports.ProbotOctokit; - var octokit = new OctokitFromOptions(Object.assign(options, { - throttle: Object.assign({ - onAbuseLimit: function (retryAfter) { - options.logger.warn("Abuse limit hit, retrying in " + retryAfter + " seconds"); - return true; - }, - onRateLimit: function (retryAfter) { - options.logger.warn("Rate limit hit, retrying in " + retryAfter + " seconds"); - return true; - } - }, options.throttle) - })); - pagination_1.addPagination(octokit); - logging_1.addLogging(octokit, options.logger); - graphql_1.addGraphQL(octokit); - return octokit; -} -exports.GitHubAPI = GitHubAPI; -//# sourceMappingURL=index.js.map - -/***/ }), +/* 101 */, /* 102 */, /* 103 */ /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ +Object.defineProperty(exports, '__esModule', { value: true }); + +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } + +var deprecation = __webpack_require__(692); +var once = _interopDefault(__webpack_require__(49)); +const logOnce = once(deprecation => console.warn(deprecation)); /** - * Module dependencies. - * @api private + * Error with extra properties to help with debugging */ -var Buffer = __webpack_require__(824).Buffer -var contentDisposition = __webpack_require__(492); -var contentType = __webpack_require__(478); -var deprecate = __webpack_require__(418)('express'); -var flatten = __webpack_require__(31); -var mime = __webpack_require__(381).mime; -var etag = __webpack_require__(521); -var proxyaddr = __webpack_require__(410); -var qs = __webpack_require__(386); -var querystring = __webpack_require__(191); +class RequestError extends Error { + constructor(message, statusCode, options) { + super(message); // Maintains proper stack trace (only available on V8) -/** - * Return strong ETag for `body`. - * - * @param {String|Buffer} body - * @param {String} [encoding] - * @return {String} - * @api private - */ + /* istanbul ignore next */ -exports.etag = createETagGenerator({ weak: false }) + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + + this.name = "HttpError"; + this.status = statusCode; + Object.defineProperty(this, "code", { + get() { + logOnce(new deprecation.Deprecation("[@octokit/request-error] `error.code` is deprecated, use `error.status`.")); + return statusCode; + } + + }); + this.headers = options.headers || {}; // redact request credentials without mutating original request options + + const requestCopy = Object.assign({}, options.request); + + if (options.request.headers.authorization) { + requestCopy.headers = Object.assign({}, options.request.headers, { + authorization: options.request.headers.authorization.replace(/ .*$/, " [REDACTED]") + }); + } + + requestCopy.url = requestCopy.url // client_id & client_secret can be passed as URL query parameters to increase rate limit + // see https://developer.github.com/v3/#increasing-the-unauthenticated-rate-limit-for-oauth-applications + .replace(/\bclient_secret=\w+/g, "client_secret=[REDACTED]") // OAuth tokens can be passed as URL query parameters, although it is not recommended + // see https://developer.github.com/v3/#oauth2-token-sent-in-a-header + .replace(/\baccess_token=\w+/g, "access_token=[REDACTED]"); + this.request = requestCopy; + } + +} + +exports.RequestError = RequestError; +//# sourceMappingURL=index.js.map + + +/***/ }), +/* 104 */ +/***/ (function(module, exports, __webpack_require__) { /** - * Return weak ETag for `body`. - * - * @param {String|Buffer} body - * @param {String} [encoding] - * @return {String} - * @api private + * Module dependencies. */ -exports.wetag = createETagGenerator({ weak: true }) +var tty = __webpack_require__(867); +var util = __webpack_require__(669); /** - * Check if `path` looks absolute. + * This is the Node.js implementation of `debug()`. * - * @param {String} path - * @return {Boolean} - * @api private + * Expose `debug()` as the module. */ -exports.isAbsolute = function(path){ - if ('/' === path[0]) return true; - if (':' === path[1] && ('\\' === path[2] || '/' === path[2])) return true; // Windows device path - if ('\\\\' === path.substring(0, 2)) return true; // Microsoft Azure absolute path -}; +exports = module.exports = __webpack_require__(911); +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; /** - * Flatten the given `arr`. - * - * @param {Array} arr - * @return {Array} - * @api private + * Colors. */ -exports.flatten = deprecate.function(flatten, - 'utils.flatten: use array-flatten npm module instead'); +exports.colors = [6, 2, 3, 4, 5, 1]; /** - * Normalize the given `type`, for example "html" becomes "text/html". + * Build up the default `inspectOpts` object from the environment variables. * - * @param {String} type - * @return {Object} - * @api private + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js */ -exports.normalizeType = function(type){ - return ~type.indexOf('/') - ? acceptParams(type) - : { value: mime.lookup(type), params: {} }; -}; +exports.inspectOpts = Object.keys(process.env).filter(function (key) { + return /^debug_/i.test(key); +}).reduce(function (obj, key) { + // camel-case + var prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); + + // coerce string value into JS value + var val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) val = true; + else if (/^(no|off|false|disabled)$/i.test(val)) val = false; + else if (val === 'null') val = null; + else val = Number(val); + + obj[prop] = val; + return obj; +}, {}); /** - * Normalize `types`, for example "html" becomes "text/html". + * The file descriptor to write the `debug()` calls to. + * Set the `DEBUG_FD` env variable to override with another value. i.e.: * - * @param {Array} types - * @return {Array} - * @api private + * $ DEBUG_FD=3 node script.js 3>debug.log */ -exports.normalizeTypes = function(types){ - var ret = []; +var fd = parseInt(process.env.DEBUG_FD, 10) || 2; - for (var i = 0; i < types.length; ++i) { - ret.push(exports.normalizeType(types[i])); - } +if (1 !== fd && 2 !== fd) { + util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')() +} - return ret; -}; +var stream = 1 === fd ? process.stdout : + 2 === fd ? process.stderr : + createWritableStdioStream(fd); /** - * Generate Content-Disposition header appropriate for the filename. - * non-ascii filenames are urlencoded and a filename* parameter is added - * - * @param {String} filename - * @return {String} - * @api private + * Is stdout a TTY? Colored output is enabled when `true`. */ -exports.contentDisposition = deprecate.function(contentDisposition, - 'utils.contentDisposition: use content-disposition npm module instead'); +function useColors() { + return 'colors' in exports.inspectOpts + ? Boolean(exports.inspectOpts.colors) + : tty.isatty(fd); +} /** - * Parse accept params `str` returning an - * object with `.value`, `.quality` and `.params`. - * also includes `.originalIndex` for stable sorting - * - * @param {String} str - * @return {Object} - * @api private + * Map %o to `util.inspect()`, all on a single line. */ -function acceptParams(str, index) { - var parts = str.split(/ *; */); - var ret = { value: parts[0], quality: 1, params: {}, originalIndex: index }; +exports.formatters.o = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n').map(function(str) { + return str.trim() + }).join(' '); +}; - for (var i = 1; i < parts.length; ++i) { - var pms = parts[i].split(/ *= */); - if ('q' === pms[0]) { - ret.quality = parseFloat(pms[1]); - } else { - ret.params[pms[0]] = pms[1]; - } - } +/** + * Map %o to `util.inspect()`, allowing multiple lines if needed. + */ - return ret; -} +exports.formatters.O = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; /** - * Compile "etag" value to function. + * Adds ANSI color escape codes if enabled. * - * @param {Boolean|String|Function} val - * @return {Function} - * @api private + * @api public */ -exports.compileETag = function(val) { - var fn; +function formatArgs(args) { + var name = this.namespace; + var useColors = this.useColors; - if (typeof val === 'function') { - return val; - } + if (useColors) { + var c = this.color; + var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m'; - switch (val) { - case true: - fn = exports.wetag; - break; - case false: - break; - case 'strong': - fn = exports.etag; - break; - case 'weak': - fn = exports.wetag; - break; - default: - throw new TypeError('unknown value for etag function: ' + val); + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); + } else { + args[0] = new Date().toUTCString() + + ' ' + name + ' ' + args[0]; } +} - return fn; +/** + * Invokes `util.format()` with the specified arguments and writes to `stream`. + */ + +function log() { + return stream.write(util.format.apply(util, arguments) + '\n'); } /** - * Compile "query parser" value to function. + * Save `namespaces`. * - * @param {String|Function} val - * @return {Function} + * @param {String} namespaces * @api private */ -exports.compileQueryParser = function compileQueryParser(val) { - var fn; - - if (typeof val === 'function') { - return val; - } - - switch (val) { - case true: - fn = querystring.parse; - break; - case false: - fn = newObject; - break; - case 'extended': - fn = parseExtendedQueryString; - break; - case 'simple': - fn = querystring.parse; - break; - default: - throw new TypeError('unknown value for query parser function: ' + val); +function save(namespaces) { + if (null == namespaces) { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } else { + process.env.DEBUG = namespaces; } - - return fn; } /** - * Compile "proxy trust" value to function. + * Load `namespaces`. * - * @param {Boolean|String|Number|Array|Function} val - * @return {Function} + * @return {String} returns the previously persisted debug modes * @api private */ -exports.compileTrust = function(val) { - if (typeof val === 'function') return val; - - if (val === true) { - // Support plain true/false - return function(){ return true }; - } - - if (typeof val === 'number') { - // Support trusting hop count - return function(a, i){ return i < val }; - } - - if (typeof val === 'string') { - // Support comma-separated values - val = val.split(/ *, */); - } - - return proxyaddr.compile(val || []); +function load() { + return process.env.DEBUG; } /** - * Set the charset in a given Content-Type string. + * Copied from `node/src/node.js`. * - * @param {String} type - * @param {String} charset - * @return {String} - * @api private + * XXX: It's lame that node doesn't expose this API out-of-the-box. It also + * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame. */ -exports.setCharset = function setCharset(type, charset) { - if (!type || !charset) { - return type; - } +function createWritableStdioStream (fd) { + var stream; + var tty_wrap = process.binding('tty_wrap'); - // parse type - var parsed = contentType.parse(type); + // Note stream._type is used for test-module-load-list.js - // set charset - parsed.parameters.charset = charset; + switch (tty_wrap.guessHandleType(fd)) { + case 'TTY': + stream = new tty.WriteStream(fd); + stream._type = 'tty'; - // format type - return contentType.format(parsed); -}; + // Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } + break; -/** - * Create an ETag generator function, generating ETags with - * the given options. - * - * @param {object} options - * @return {function} - * @private - */ + case 'FILE': + var fs = __webpack_require__(747); + stream = new fs.SyncWriteStream(fd, { autoClose: false }); + stream._type = 'fs'; + break; -function createETagGenerator (options) { - return function generateETag (body, encoding) { - var buf = !Buffer.isBuffer(body) - ? Buffer.from(body, encoding) - : body + case 'PIPE': + case 'TCP': + var net = __webpack_require__(631); + stream = new net.Socket({ + fd: fd, + readable: false, + writable: true + }); - return etag(buf, options) + // FIXME Should probably have an option in net.Socket to create a + // stream from an existing fd which is writable only. But for now + // we'll just add this hack and set the `readable` member to false. + // Test: ./node test/fixtures/echo.js < /etc/passwd + stream.readable = false; + stream.read = null; + stream._type = 'pipe'; + + // FIXME Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } + break; + + default: + // Probably an error on in uv_guess_handle() + throw new Error('Implement me. Unknown stream file type!'); } + + // For supporting legacy API we put the FD here. + stream.fd = fd; + + stream._isStdio = true; + + return stream; } /** - * Parse an extended query string with qs. + * Init logic for `debug` instances. * - * @return {Object} - * @private + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. */ -function parseExtendedQueryString(str) { - return qs.parse(str, { - allowPrototypes: true - }); +function init (debug) { + debug.inspectOpts = {}; + + var keys = Object.keys(exports.inspectOpts); + for (var i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } } /** - * Return new empty object. - * - * @return {Object} - * @api private + * Enable namespaces listed in `process.env.DEBUG` initially. */ -function newObject() { - return {}; -} +exports.enable(load()); /***/ }), -/* 104 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { +/* 105 */ +/***/ (function(__unusedmodule, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -const utils_1 = __webpack_require__(200); -const net_1 = __webpack_require__(631); -function getNodeKey(node) { - node.port = node.port || 6379; - node.host = node.host || "127.0.0.1"; - return node.host + ":" + node.port; -} -exports.getNodeKey = getNodeKey; -function nodeKeyToRedisOptions(nodeKey) { - const portIndex = nodeKey.lastIndexOf(":"); - if (portIndex === -1) { - throw new Error(`Invalid node key ${nodeKey}`); - } - return { - host: nodeKey.slice(0, portIndex), - port: Number(nodeKey.slice(portIndex + 1)), - }; -} -exports.nodeKeyToRedisOptions = nodeKeyToRedisOptions; -function normalizeNodeOptions(nodes) { - return nodes.map((node) => { - const options = {}; - if (typeof node === "object") { - Object.assign(options, node); - } - else if (typeof node === "string") { - Object.assign(options, utils_1.parseURL(node)); - } - else if (typeof node === "number") { - options.port = node; - } - else { - throw new Error("Invalid argument " + node); - } - if (typeof options.port === "string") { - options.port = parseInt(options.port, 10); - } - // Cluster mode only support db 0 - delete options.db; - if (!options.port) { - options.port = 6379; - } - if (!options.host) { - options.host = "127.0.0.1"; +exports.getAuthenticatedOctokit = void 0; +async function getAuthenticatedOctokit(state, installationId) { + const { githubToken, log, Octokit, octokit, throttleOptions } = state; + if (!installationId) + return octokit; + const constructorAuthOptions = githubToken + ? {} + : { auth: { installationId: installationId } }; + const constructorThrottleOptions = throttleOptions + ? { + throttle: { + id: installationId, + ...throttleOptions, + }, } - return options; - }); -} -exports.normalizeNodeOptions = normalizeNodeOptions; -function getUniqueHostnamesFromOptions(nodes) { - const uniqueHostsMap = {}; - nodes.forEach((node) => { - uniqueHostsMap[node.host] = true; - }); - return Object.keys(uniqueHostsMap).filter((host) => !net_1.isIP(host)); + : {}; + const pinoLog = log.child({ name: "github" }); + const options = { + log: { + fatal: pinoLog.fatal.bind(pinoLog), + error: pinoLog.error.bind(pinoLog), + warn: pinoLog.warn.bind(pinoLog), + info: pinoLog.info.bind(pinoLog), + debug: pinoLog.debug.bind(pinoLog), + trace: pinoLog.trace.bind(pinoLog), + }, + ...constructorAuthOptions, + ...constructorThrottleOptions, + }; + return new Octokit(options); } -exports.getUniqueHostnamesFromOptions = getUniqueHostnamesFromOptions; - +exports.getAuthenticatedOctokit = getAuthenticatedOctokit; +//# sourceMappingURL=get-authenticated-octokit.js.map /***/ }), -/* 105 */ +/* 106 */ /***/ (function(__unusedmodule, exports, __webpack_require__) { -"use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.createDefaultCache = void 0; -var cache_manager_1 = __importDefault(__webpack_require__(971)); -function createDefaultCache() { - return cache_manager_1.default.caching({ - store: 'memory', - ttl: 60 * 60 // 1 hour - }); -} -exports.createDefaultCache = createDefaultCache; -//# sourceMappingURL=cache.js.map - -/***/ }), -/* 106 */, -/* 107 */ -/***/ (function(__unusedmodule, exports) { - -"use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); -exports.logRequestErrors = void 0; -exports.logRequestErrors = function (err, req, res, next) { - if (req.log) { - req.log.error(err); +var tslib_1 = __webpack_require__(422); +var core_1 = __webpack_require__(196); +var backend_1 = __webpack_require__(876); +var version_1 = __webpack_require__(706); +/** + * The Sentry Node SDK Client. + * + * @see NodeOptions for documentation on configuration options. + * @see SentryClient for usage documentation. + */ +var NodeClient = /** @class */ (function (_super) { + tslib_1.__extends(NodeClient, _super); + /** + * Creates a new Node SDK instance. + * @param options Configuration options for this SDK. + */ + function NodeClient(options) { + return _super.call(this, backend_1.NodeBackend, options) || this; } - next(); -}; -//# sourceMappingURL=log-request-errors.js.map + /** + * @inheritDoc + */ + NodeClient.prototype._prepareEvent = function (event, scope, hint) { + event.platform = event.platform || 'node'; + event.sdk = tslib_1.__assign(tslib_1.__assign({}, event.sdk), { name: version_1.SDK_NAME, packages: tslib_1.__spread(((event.sdk && event.sdk.packages) || []), [ + { + name: 'npm:@sentry/node', + version: version_1.SDK_VERSION, + }, + ]), version: version_1.SDK_VERSION }); + if (this.getOptions().serverName) { + event.server_name = this.getOptions().serverName; + } + return _super.prototype._prepareEvent.call(this, event, scope, hint); + }; + return NodeClient; +}(core_1.BaseClient)); +exports.NodeClient = NodeClient; +//# sourceMappingURL=client.js.map /***/ }), +/* 107 */, /* 108 */ /***/ (function(module, __unusedexports, __webpack_require__) { -var bufferEqual = __webpack_require__(79); -var Buffer = __webpack_require__(149).Buffer; -var crypto = __webpack_require__(417); -var formatEcdsa = __webpack_require__(815); -var util = __webpack_require__(669); +"use strict"; +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ -var MSG_INVALID_ALGORITHM = '"%s" is not a valid algorithm.\n Supported algorithms are:\n "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".' -var MSG_INVALID_SECRET = 'secret must be a string or buffer'; -var MSG_INVALID_VERIFIER_KEY = 'key must be a string or a buffer'; -var MSG_INVALID_SIGNER_KEY = 'key must be a string, a buffer or an object'; -var supportsKeyObjects = typeof crypto.createPublicKey === 'function'; -if (supportsKeyObjects) { - MSG_INVALID_VERIFIER_KEY += ' or a KeyObject'; - MSG_INVALID_SECRET += 'or a KeyObject'; -} -function checkIsPublicKey(key) { - if (Buffer.isBuffer(key)) { - return; - } +/** + * Module dependencies. + * @private + */ - if (typeof key === 'string') { - return; - } +var accepts = __webpack_require__(227); +var deprecate = __webpack_require__(418)('express'); +var isIP = __webpack_require__(631).isIP; +var typeis = __webpack_require__(153); +var http = __webpack_require__(605); +var fresh = __webpack_require__(115); +var parseRange = __webpack_require__(770); +var parse = __webpack_require__(768); +var proxyaddr = __webpack_require__(410); - if (!supportsKeyObjects) { - throw typeError(MSG_INVALID_VERIFIER_KEY); - } +/** + * Request prototype. + * @public + */ - if (typeof key !== 'object') { - throw typeError(MSG_INVALID_VERIFIER_KEY); - } +var req = Object.create(http.IncomingMessage.prototype) - if (typeof key.type !== 'string') { - throw typeError(MSG_INVALID_VERIFIER_KEY); - } +/** + * Module exports. + * @public + */ - if (typeof key.asymmetricKeyType !== 'string') { - throw typeError(MSG_INVALID_VERIFIER_KEY); - } +module.exports = req - if (typeof key.export !== 'function') { - throw typeError(MSG_INVALID_VERIFIER_KEY); - } -}; +/** + * Return request header. + * + * The `Referrer` header field is special-cased, + * both `Referrer` and `Referer` are interchangeable. + * + * Examples: + * + * req.get('Content-Type'); + * // => "text/plain" + * + * req.get('content-type'); + * // => "text/plain" + * + * req.get('Something'); + * // => undefined + * + * Aliased as `req.header()`. + * + * @param {String} name + * @return {String} + * @public + */ -function checkIsPrivateKey(key) { - if (Buffer.isBuffer(key)) { - return; +req.get = +req.header = function header(name) { + if (!name) { + throw new TypeError('name argument is required to req.get'); } - if (typeof key === 'string') { - return; + if (typeof name !== 'string') { + throw new TypeError('name must be a string to req.get'); } - if (typeof key === 'object') { - return; + var lc = name.toLowerCase(); + + switch (lc) { + case 'referer': + case 'referrer': + return this.headers.referrer + || this.headers.referer; + default: + return this.headers[lc]; } +}; - throw typeError(MSG_INVALID_SIGNER_KEY); +/** + * To do: update docs. + * + * Check if the given `type(s)` is acceptable, returning + * the best match when true, otherwise `undefined`, in which + * case you should respond with 406 "Not Acceptable". + * + * The `type` value may be a single MIME type string + * such as "application/json", an extension name + * such as "json", a comma-delimited list such as "json, html, text/plain", + * an argument list such as `"json", "html", "text/plain"`, + * or an array `["json", "html", "text/plain"]`. When a list + * or array is given, the _best_ match, if any is returned. + * + * Examples: + * + * // Accept: text/html + * req.accepts('html'); + * // => "html" + * + * // Accept: text/*, application/json + * req.accepts('html'); + * // => "html" + * req.accepts('text/html'); + * // => "text/html" + * req.accepts('json, text'); + * // => "json" + * req.accepts('application/json'); + * // => "application/json" + * + * // Accept: text/*, application/json + * req.accepts('image/png'); + * req.accepts('png'); + * // => undefined + * + * // Accept: text/*;q=.5, application/json + * req.accepts(['html', 'json']); + * req.accepts('html', 'json'); + * req.accepts('html, json'); + * // => "json" + * + * @param {String|Array} type(s) + * @return {String|Array|Boolean} + * @public + */ + +req.accepts = function(){ + var accept = accepts(this); + return accept.types.apply(accept, arguments); }; -function checkIsSecretKey(key) { - if (Buffer.isBuffer(key)) { - return; - } +/** + * Check if the given `encoding`s are accepted. + * + * @param {String} ...encoding + * @return {String|Array} + * @public + */ - if (typeof key === 'string') { - return key; - } +req.acceptsEncodings = function(){ + var accept = accepts(this); + return accept.encodings.apply(accept, arguments); +}; - if (!supportsKeyObjects) { - throw typeError(MSG_INVALID_SECRET); - } +req.acceptsEncoding = deprecate.function(req.acceptsEncodings, + 'req.acceptsEncoding: Use acceptsEncodings instead'); - if (typeof key !== 'object') { - throw typeError(MSG_INVALID_SECRET); - } +/** + * Check if the given `charset`s are acceptable, + * otherwise you should respond with 406 "Not Acceptable". + * + * @param {String} ...charset + * @return {String|Array} + * @public + */ - if (key.type !== 'secret') { - throw typeError(MSG_INVALID_SECRET); - } +req.acceptsCharsets = function(){ + var accept = accepts(this); + return accept.charsets.apply(accept, arguments); +}; - if (typeof key.export !== 'function') { - throw typeError(MSG_INVALID_SECRET); - } -} +req.acceptsCharset = deprecate.function(req.acceptsCharsets, + 'req.acceptsCharset: Use acceptsCharsets instead'); -function fromBase64(base64) { - return base64 - .replace(/=/g, '') - .replace(/\+/g, '-') - .replace(/\//g, '_'); -} +/** + * Check if the given `lang`s are acceptable, + * otherwise you should respond with 406 "Not Acceptable". + * + * @param {String} ...lang + * @return {String|Array} + * @public + */ -function toBase64(base64url) { - base64url = base64url.toString(); +req.acceptsLanguages = function(){ + var accept = accepts(this); + return accept.languages.apply(accept, arguments); +}; - var padding = 4 - base64url.length % 4; - if (padding !== 4) { - for (var i = 0; i < padding; ++i) { - base64url += '='; - } - } +req.acceptsLanguage = deprecate.function(req.acceptsLanguages, + 'req.acceptsLanguage: Use acceptsLanguages instead'); - return base64url - .replace(/\-/g, '+') - .replace(/_/g, '/'); -} +/** + * Parse Range header field, capping to the given `size`. + * + * Unspecified ranges such as "0-" require knowledge of your resource length. In + * the case of a byte range this is of course the total number of bytes. If the + * Range header field is not given `undefined` is returned, `-1` when unsatisfiable, + * and `-2` when syntactically invalid. + * + * When ranges are returned, the array has a "type" property which is the type of + * range that is required (most commonly, "bytes"). Each array element is an object + * with a "start" and "end" property for the portion of the range. + * + * The "combine" option can be set to `true` and overlapping & adjacent ranges + * will be combined into a single range. + * + * NOTE: remember that ranges are inclusive, so for example "Range: users=0-3" + * should respond with 4 users when available, not 3. + * + * @param {number} size + * @param {object} [options] + * @param {boolean} [options.combine=false] + * @return {number|array} + * @public + */ -function typeError(template) { - var args = [].slice.call(arguments, 1); - var errMsg = util.format.bind(util, template).apply(null, args); - return new TypeError(errMsg); -} +req.range = function range(size, options) { + var range = this.get('Range'); + if (!range) return; + return parseRange(size, range, options); +}; -function bufferOrString(obj) { - return Buffer.isBuffer(obj) || typeof obj === 'string'; -} +/** + * Return the value of param `name` when present or `defaultValue`. + * + * - Checks route placeholders, ex: _/user/:id_ + * - Checks body params, ex: id=12, {"id":12} + * - Checks query string params, ex: ?id=12 + * + * To utilize request bodies, `req.body` + * should be an object. This can be done by using + * the `bodyParser()` middleware. + * + * @param {String} name + * @param {Mixed} [defaultValue] + * @return {String} + * @public + */ -function normalizeInput(thing) { - if (!bufferOrString(thing)) - thing = JSON.stringify(thing); - return thing; -} +req.param = function param(name, defaultValue) { + var params = this.params || {}; + var body = this.body || {}; + var query = this.query || {}; -function createHmacSigner(bits) { - return function sign(thing, secret) { - checkIsSecretKey(secret); - thing = normalizeInput(thing); - var hmac = crypto.createHmac('sha' + bits, secret); - var sig = (hmac.update(thing), hmac.digest('base64')) - return fromBase64(sig); - } -} + var args = arguments.length === 1 + ? 'name' + : 'name, default'; + deprecate('req.param(' + args + '): Use req.params, req.body, or req.query instead'); -function createHmacVerifier(bits) { - return function verify(thing, signature, secret) { - var computedSig = createHmacSigner(bits)(thing, secret); - return bufferEqual(Buffer.from(signature), Buffer.from(computedSig)); - } -} + if (null != params[name] && params.hasOwnProperty(name)) return params[name]; + if (null != body[name]) return body[name]; + if (null != query[name]) return query[name]; -function createKeySigner(bits) { - return function sign(thing, privateKey) { - checkIsPrivateKey(privateKey); - thing = normalizeInput(thing); - // Even though we are specifying "RSA" here, this works with ECDSA - // keys as well. - var signer = crypto.createSign('RSA-SHA' + bits); - var sig = (signer.update(thing), signer.sign(privateKey, 'base64')); - return fromBase64(sig); - } -} + return defaultValue; +}; -function createKeyVerifier(bits) { - return function verify(thing, signature, publicKey) { - checkIsPublicKey(publicKey); - thing = normalizeInput(thing); - signature = toBase64(signature); - var verifier = crypto.createVerify('RSA-SHA' + bits); - verifier.update(thing); - return verifier.verify(publicKey, signature, 'base64'); - } -} +/** + * Check if the incoming request contains the "Content-Type" + * header field, and it contains the give mime `type`. + * + * Examples: + * + * // With Content-Type: text/html; charset=utf-8 + * req.is('html'); + * req.is('text/html'); + * req.is('text/*'); + * // => true + * + * // When Content-Type is application/json + * req.is('json'); + * req.is('application/json'); + * req.is('application/*'); + * // => true + * + * req.is('html'); + * // => false + * + * @param {String|Array} types... + * @return {String|false|null} + * @public + */ -function createPSSKeySigner(bits) { - return function sign(thing, privateKey) { - checkIsPrivateKey(privateKey); - thing = normalizeInput(thing); - var signer = crypto.createSign('RSA-SHA' + bits); - var sig = (signer.update(thing), signer.sign({ - key: privateKey, - padding: crypto.constants.RSA_PKCS1_PSS_PADDING, - saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST - }, 'base64')); - return fromBase64(sig); - } -} +req.is = function is(types) { + var arr = types; -function createPSSKeyVerifier(bits) { - return function verify(thing, signature, publicKey) { - checkIsPublicKey(publicKey); - thing = normalizeInput(thing); - signature = toBase64(signature); - var verifier = crypto.createVerify('RSA-SHA' + bits); - verifier.update(thing); - return verifier.verify({ - key: publicKey, - padding: crypto.constants.RSA_PKCS1_PSS_PADDING, - saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST - }, signature, 'base64'); + // support flattened arguments + if (!Array.isArray(types)) { + arr = new Array(arguments.length); + for (var i = 0; i < arr.length; i++) { + arr[i] = arguments[i]; + } } -} -function createECDSASigner(bits) { - var inner = createKeySigner(bits); - return function sign() { - var signature = inner.apply(null, arguments); - signature = formatEcdsa.derToJose(signature, 'ES' + bits); - return signature; - }; -} + return typeis(this, arr); +}; -function createECDSAVerifer(bits) { - var inner = createKeyVerifier(bits); - return function verify(thing, signature, publicKey) { - signature = formatEcdsa.joseToDer(signature, 'ES' + bits).toString('base64'); - var result = inner(thing, signature, publicKey); - return result; - }; -} +/** + * Return the protocol string "http" or "https" + * when requested with TLS. When the "trust proxy" + * setting trusts the socket address, the + * "X-Forwarded-Proto" header field will be trusted + * and used if present. + * + * If you're running behind a reverse proxy that + * supplies https for you this may be enabled. + * + * @return {String} + * @public + */ -function createNoneSigner() { - return function sign() { - return ''; - } -} +defineGetter(req, 'protocol', function protocol(){ + var proto = this.connection.encrypted + ? 'https' + : 'http'; + var trust = this.app.get('trust proxy fn'); -function createNoneVerifier() { - return function verify(thing, signature) { - return signature === ''; + if (!trust(this.connection.remoteAddress, 0)) { + return proto; } -} -module.exports = function jwa(algorithm) { - var signerFactories = { - hs: createHmacSigner, - rs: createKeySigner, - ps: createPSSKeySigner, - es: createECDSASigner, - none: createNoneSigner, - } - var verifierFactories = { - hs: createHmacVerifier, - rs: createKeyVerifier, - ps: createPSSKeyVerifier, - es: createECDSAVerifer, - none: createNoneVerifier, - } - var match = algorithm.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/i); - if (!match) - throw typeError(MSG_INVALID_ALGORITHM, algorithm); - var algo = (match[1] || match[3]).toLowerCase(); - var bits = match[2]; + // Note: X-Forwarded-Proto is normally only ever a + // single value, but this is to be safe. + var header = this.get('X-Forwarded-Proto') || proto + var index = header.indexOf(',') - return { - sign: signerFactories[algo](bits), - verify: verifierFactories[algo](bits), - } -}; + return index !== -1 + ? header.substring(0, index).trim() + : header.trim() +}); +/** + * Short-hand for: + * + * req.protocol === 'https' + * + * @return {Boolean} + * @public + */ -/***/ }), -/* 109 */ -/***/ (function(__unusedmodule, exports) { +defineGetter(req, 'secure', function secure(){ + return this.protocol === 'https'; +}); -"use strict"; +/** + * Return the remote address from the trusted proxy. + * + * The is the remote address on the socket unless + * "trust proxy" is set. + * + * @return {String} + * @public + */ -Object.defineProperty(exports, "__esModule", { value: true }); -//Try catch is not supported in optimizing -//compiler, so it is isolated -exports.errorObj = { e: {} }; -let tryCatchTarget; -function tryCatcher(err, val) { - try { - const target = tryCatchTarget; - tryCatchTarget = null; - return target.apply(this, arguments); - } - catch (e) { - exports.errorObj.e = e; - return exports.errorObj; +defineGetter(req, 'ip', function ip(){ + var trust = this.app.get('trust proxy fn'); + return proxyaddr(this, trust); +}); + +/** + * When "trust proxy" is set, trusted proxy addresses + client. + * + * For example if the value were "client, proxy1, proxy2" + * you would receive the array `["client", "proxy1", "proxy2"]` + * where "proxy2" is the furthest down-stream and "proxy1" and + * "proxy2" were trusted. + * + * @return {Array} + * @public + */ + +defineGetter(req, 'ips', function ips() { + var trust = this.app.get('trust proxy fn'); + var addrs = proxyaddr.all(this, trust); + + // reverse the order (to farthest -> closest) + // and remove socket address + addrs.reverse().pop() + + return addrs +}); + +/** + * Return subdomains as an array. + * + * Subdomains are the dot-separated parts of the host before the main domain of + * the app. By default, the domain of the app is assumed to be the last two + * parts of the host. This can be changed by setting "subdomain offset". + * + * For example, if the domain is "tobi.ferrets.example.com": + * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`. + * If "subdomain offset" is 3, req.subdomains is `["tobi"]`. + * + * @return {Array} + * @public + */ + +defineGetter(req, 'subdomains', function subdomains() { + var hostname = this.hostname; + + if (!hostname) return []; + + var offset = this.app.get('subdomain offset'); + var subdomains = !isIP(hostname) + ? hostname.split('.').reverse() + : [hostname]; + + return subdomains.slice(offset); +}); + +/** + * Short-hand for `url.parse(req.url).pathname`. + * + * @return {String} + * @public + */ + +defineGetter(req, 'path', function path() { + return parse(this).pathname; +}); + +/** + * Parse the "Host" header field to a hostname. + * + * When the "trust proxy" setting trusts the socket + * address, the "X-Forwarded-Host" header field will + * be trusted. + * + * @return {String} + * @public + */ + +defineGetter(req, 'hostname', function hostname(){ + var trust = this.app.get('trust proxy fn'); + var host = this.get('X-Forwarded-Host'); + + if (!host || !trust(this.connection.remoteAddress, 0)) { + host = this.get('Host'); + } else if (host.indexOf(',') !== -1) { + // Note: X-Forwarded-Host is normally only ever a + // single value, but this is to be safe. + host = host.substring(0, host.indexOf(',')).trimRight() + } + + if (!host) return; + + // IPv6 literal support + var offset = host[0] === '[' + ? host.indexOf(']') + 1 + : 0; + var index = host.indexOf(':', offset); + + return index !== -1 + ? host.substring(0, index) + : host; +}); + +// TODO: change req.host to return host in next major + +defineGetter(req, 'host', deprecate.function(function host(){ + return this.hostname; +}, 'req.host: Use req.hostname instead')); + +/** + * Check if the request is fresh, aka + * Last-Modified and/or the ETag + * still match. + * + * @return {Boolean} + * @public + */ + +defineGetter(req, 'fresh', function(){ + var method = this.method; + var res = this.res + var status = res.statusCode + + // GET or HEAD for weak freshness validation only + if ('GET' !== method && 'HEAD' !== method) return false; + + // 2xx or 304 as per rfc2616 14.26 + if ((status >= 200 && status < 300) || 304 === status) { + return fresh(this.headers, { + 'etag': res.get('ETag'), + 'last-modified': res.get('Last-Modified') + }) + } + + return false; +}); + +/** + * Check if the request is stale, aka + * "Last-Modified" and / or the "ETag" for the + * resource has changed. + * + * @return {Boolean} + * @public + */ + +defineGetter(req, 'stale', function stale(){ + return !this.fresh; +}); + +/** + * Check if the request was an _XMLHttpRequest_. + * + * @return {Boolean} + * @public + */ + +defineGetter(req, 'xhr', function xhr(){ + var val = this.get('X-Requested-With') || ''; + return val.toLowerCase() === 'xmlhttprequest'; +}); + +/** + * Helper function for creating a getter on an object. + * + * @param {Object} obj + * @param {String} name + * @param {Function} getter + * @private + */ +function defineGetter(obj, name, getter) { + Object.defineProperty(obj, name, { + configurable: true, + enumerable: true, + get: getter + }); +} + + +/***/ }), +/* 109 */ +/***/ (function(__unusedmodule, exports) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +//Try catch is not supported in optimizing +//compiler, so it is isolated +exports.errorObj = { e: {} }; +let tryCatchTarget; +function tryCatcher(err, val) { + try { + const target = tryCatchTarget; + tryCatchTarget = null; + return target.apply(this, arguments); + } + catch (e) { + exports.errorObj.e = e; + return exports.errorObj; } } function tryCatch(fn) { @@ -6787,50 +7630,30 @@ exports.tryCatch = tryCatch; /***/ }), /* 110 */, /* 111 */, -/* 112 */, -/* 113 */ +/* 112 */ /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; -var __rest = (this && this.__rest) || function (s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; Object.defineProperty(exports, "__esModule", { value: true }); -exports.Logger = exports.addLogging = void 0; -var bunyan_1 = __importDefault(__webpack_require__(891)); -exports.Logger = bunyan_1.default; -function addLogging(client, logger) { - if (!logger) { - return; - } - client.hook.error('request', function (error, options) { - var method = options.method, url = options.url, headers = options.headers, params = __rest(options, ["method", "url", "headers"]); - var msg = "GitHub request: " + method + " " + url + " - " + error.status; - logger.debug({ params: params }, msg); - throw error; - }); - client.hook.after('request', function (result, options) { - var method = options.method, url = options.url, headers = options.headers, params = __rest(options, ["method", "url", "headers"]); - var msg = "GitHub request: " + method + " " + url + " - " + result.headers.status; - logger.debug({ params: params }, msg); +exports.getWebhooks = void 0; +const webhooks_1 = __webpack_require__(693); +const get_error_handler_1 = __webpack_require__(863); +const octokit_webhooks_transform_1 = __webpack_require__(179); +function getWebhooks(state) { + const webhooks = new webhooks_1.Webhooks({ + path: state.webhooks.path, + secret: state.webhooks.secret, + transform: octokit_webhooks_transform_1.webhookTransform.bind(null, state), }); + webhooks.on("error", get_error_handler_1.getErrorHandler(state.log)); + return webhooks; } -exports.addLogging = addLogging; -//# sourceMappingURL=logging.js.map +exports.getWebhooks = getWebhooks; +//# sourceMappingURL=get-webhooks.js.map /***/ }), +/* 113 */, /* 114 */, /* 115 */ /***/ (function(module) { @@ -6976,480 +7799,7 @@ function parseTokenList (str) { /***/ }), -/* 116 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -module.exports = LRUCache - -// This will be a proper iterable 'Map' in engines that support it, -// or a fakey-fake PseudoMap in older versions. -var Map = __webpack_require__(718) -var util = __webpack_require__(669) - -// A linked list to keep track of recently-used-ness -var Yallist = __webpack_require__(266) - -// use symbols if possible, otherwise just _props -var symbols = {} -var hasSymbol = typeof Symbol === 'function' -var makeSymbol -if (hasSymbol) { - makeSymbol = function (key) { - return Symbol.for(key) - } -} else { - makeSymbol = function (key) { - return '_' + key - } -} - -function priv (obj, key, val) { - var sym - if (symbols[key]) { - sym = symbols[key] - } else { - sym = makeSymbol(key) - symbols[key] = sym - } - if (arguments.length === 2) { - return obj[sym] - } else { - obj[sym] = val - return val - } -} - -function naiveLength () { return 1 } - -// lruList is a yallist where the head is the youngest -// item, and the tail is the oldest. the list contains the Hit -// objects as the entries. -// Each Hit object has a reference to its Yallist.Node. This -// never changes. -// -// cache is a Map (or PseudoMap) that matches the keys to -// the Yallist.Node object. -function LRUCache (options) { - if (!(this instanceof LRUCache)) { - return new LRUCache(options) - } - - if (typeof options === 'number') { - options = { max: options } - } - - if (!options) { - options = {} - } - - var max = priv(this, 'max', options.max) - // Kind of weird to have a default max of Infinity, but oh well. - if (!max || - !(typeof max === 'number') || - max <= 0) { - priv(this, 'max', Infinity) - } - - var lc = options.length || naiveLength - if (typeof lc !== 'function') { - lc = naiveLength - } - priv(this, 'lengthCalculator', lc) - - priv(this, 'allowStale', options.stale || false) - priv(this, 'maxAge', options.maxAge || 0) - priv(this, 'dispose', options.dispose) - this.reset() -} - -// resize the cache when the max changes. -Object.defineProperty(LRUCache.prototype, 'max', { - set: function (mL) { - if (!mL || !(typeof mL === 'number') || mL <= 0) { - mL = Infinity - } - priv(this, 'max', mL) - trim(this) - }, - get: function () { - return priv(this, 'max') - }, - enumerable: true -}) - -Object.defineProperty(LRUCache.prototype, 'allowStale', { - set: function (allowStale) { - priv(this, 'allowStale', !!allowStale) - }, - get: function () { - return priv(this, 'allowStale') - }, - enumerable: true -}) - -Object.defineProperty(LRUCache.prototype, 'maxAge', { - set: function (mA) { - if (!mA || !(typeof mA === 'number') || mA < 0) { - mA = 0 - } - priv(this, 'maxAge', mA) - trim(this) - }, - get: function () { - return priv(this, 'maxAge') - }, - enumerable: true -}) - -// resize the cache when the lengthCalculator changes. -Object.defineProperty(LRUCache.prototype, 'lengthCalculator', { - set: function (lC) { - if (typeof lC !== 'function') { - lC = naiveLength - } - if (lC !== priv(this, 'lengthCalculator')) { - priv(this, 'lengthCalculator', lC) - priv(this, 'length', 0) - priv(this, 'lruList').forEach(function (hit) { - hit.length = priv(this, 'lengthCalculator').call(this, hit.value, hit.key) - priv(this, 'length', priv(this, 'length') + hit.length) - }, this) - } - trim(this) - }, - get: function () { return priv(this, 'lengthCalculator') }, - enumerable: true -}) - -Object.defineProperty(LRUCache.prototype, 'length', { - get: function () { return priv(this, 'length') }, - enumerable: true -}) - -Object.defineProperty(LRUCache.prototype, 'itemCount', { - get: function () { return priv(this, 'lruList').length }, - enumerable: true -}) - -LRUCache.prototype.rforEach = function (fn, thisp) { - thisp = thisp || this - for (var walker = priv(this, 'lruList').tail; walker !== null;) { - var prev = walker.prev - forEachStep(this, fn, walker, thisp) - walker = prev - } -} - -function forEachStep (self, fn, node, thisp) { - var hit = node.value - if (isStale(self, hit)) { - del(self, node) - if (!priv(self, 'allowStale')) { - hit = undefined - } - } - if (hit) { - fn.call(thisp, hit.value, hit.key, self) - } -} - -LRUCache.prototype.forEach = function (fn, thisp) { - thisp = thisp || this - for (var walker = priv(this, 'lruList').head; walker !== null;) { - var next = walker.next - forEachStep(this, fn, walker, thisp) - walker = next - } -} - -LRUCache.prototype.keys = function () { - return priv(this, 'lruList').toArray().map(function (k) { - return k.key - }, this) -} - -LRUCache.prototype.values = function () { - return priv(this, 'lruList').toArray().map(function (k) { - return k.value - }, this) -} - -LRUCache.prototype.reset = function () { - if (priv(this, 'dispose') && - priv(this, 'lruList') && - priv(this, 'lruList').length) { - priv(this, 'lruList').forEach(function (hit) { - priv(this, 'dispose').call(this, hit.key, hit.value) - }, this) - } - - priv(this, 'cache', new Map()) // hash of items by key - priv(this, 'lruList', new Yallist()) // list of items in order of use recency - priv(this, 'length', 0) // length of items in the list -} - -LRUCache.prototype.dump = function () { - return priv(this, 'lruList').map(function (hit) { - if (!isStale(this, hit)) { - return { - k: hit.key, - v: hit.value, - e: hit.now + (hit.maxAge || 0) - } - } - }, this).toArray().filter(function (h) { - return h - }) -} - -LRUCache.prototype.dumpLru = function () { - return priv(this, 'lruList') -} - -LRUCache.prototype.inspect = function (n, opts) { - var str = 'LRUCache {' - var extras = false - - var as = priv(this, 'allowStale') - if (as) { - str += '\n allowStale: true' - extras = true - } - - var max = priv(this, 'max') - if (max && max !== Infinity) { - if (extras) { - str += ',' - } - str += '\n max: ' + util.inspect(max, opts) - extras = true - } - - var maxAge = priv(this, 'maxAge') - if (maxAge) { - if (extras) { - str += ',' - } - str += '\n maxAge: ' + util.inspect(maxAge, opts) - extras = true - } - - var lc = priv(this, 'lengthCalculator') - if (lc && lc !== naiveLength) { - if (extras) { - str += ',' - } - str += '\n length: ' + util.inspect(priv(this, 'length'), opts) - extras = true - } - - var didFirst = false - priv(this, 'lruList').forEach(function (item) { - if (didFirst) { - str += ',\n ' - } else { - if (extras) { - str += ',\n' - } - didFirst = true - str += '\n ' - } - var key = util.inspect(item.key).split('\n').join('\n ') - var val = { value: item.value } - if (item.maxAge !== maxAge) { - val.maxAge = item.maxAge - } - if (lc !== naiveLength) { - val.length = item.length - } - if (isStale(this, item)) { - val.stale = true - } - - val = util.inspect(val, opts).split('\n').join('\n ') - str += key + ' => ' + val - }) - - if (didFirst || extras) { - str += '\n' - } - str += '}' - - return str -} - -LRUCache.prototype.set = function (key, value, maxAge) { - maxAge = maxAge || priv(this, 'maxAge') - - var now = maxAge ? Date.now() : 0 - var len = priv(this, 'lengthCalculator').call(this, value, key) - - if (priv(this, 'cache').has(key)) { - if (len > priv(this, 'max')) { - del(this, priv(this, 'cache').get(key)) - return false - } - - var node = priv(this, 'cache').get(key) - var item = node.value - - // dispose of the old one before overwriting - if (priv(this, 'dispose')) { - priv(this, 'dispose').call(this, key, item.value) - } - - item.now = now - item.maxAge = maxAge - item.value = value - priv(this, 'length', priv(this, 'length') + (len - item.length)) - item.length = len - this.get(key) - trim(this) - return true - } - - var hit = new Entry(key, value, len, now, maxAge) - - // oversized objects fall out of cache automatically. - if (hit.length > priv(this, 'max')) { - if (priv(this, 'dispose')) { - priv(this, 'dispose').call(this, key, value) - } - return false - } - - priv(this, 'length', priv(this, 'length') + hit.length) - priv(this, 'lruList').unshift(hit) - priv(this, 'cache').set(key, priv(this, 'lruList').head) - trim(this) - return true -} - -LRUCache.prototype.has = function (key) { - if (!priv(this, 'cache').has(key)) return false - var hit = priv(this, 'cache').get(key).value - if (isStale(this, hit)) { - return false - } - return true -} - -LRUCache.prototype.get = function (key) { - return get(this, key, true) -} - -LRUCache.prototype.peek = function (key) { - return get(this, key, false) -} - -LRUCache.prototype.pop = function () { - var node = priv(this, 'lruList').tail - if (!node) return null - del(this, node) - return node.value -} - -LRUCache.prototype.del = function (key) { - del(this, priv(this, 'cache').get(key)) -} - -LRUCache.prototype.load = function (arr) { - // reset the cache - this.reset() - - var now = Date.now() - // A previous serialized cache has the most recent items first - for (var l = arr.length - 1; l >= 0; l--) { - var hit = arr[l] - var expiresAt = hit.e || 0 - if (expiresAt === 0) { - // the item was created without expiration in a non aged cache - this.set(hit.k, hit.v) - } else { - var maxAge = expiresAt - now - // dont add already expired items - if (maxAge > 0) { - this.set(hit.k, hit.v, maxAge) - } - } - } -} - -LRUCache.prototype.prune = function () { - var self = this - priv(this, 'cache').forEach(function (value, key) { - get(self, key, false) - }) -} - -function get (self, key, doUse) { - var node = priv(self, 'cache').get(key) - if (node) { - var hit = node.value - if (isStale(self, hit)) { - del(self, node) - if (!priv(self, 'allowStale')) hit = undefined - } else { - if (doUse) { - priv(self, 'lruList').unshiftNode(node) - } - } - if (hit) hit = hit.value - } - return hit -} - -function isStale (self, hit) { - if (!hit || (!hit.maxAge && !priv(self, 'maxAge'))) { - return false - } - var stale = false - var diff = Date.now() - hit.now - if (hit.maxAge) { - stale = diff > hit.maxAge - } else { - stale = priv(self, 'maxAge') && (diff > priv(self, 'maxAge')) - } - return stale -} - -function trim (self) { - if (priv(self, 'length') > priv(self, 'max')) { - for (var walker = priv(self, 'lruList').tail; - priv(self, 'length') > priv(self, 'max') && walker !== null;) { - // We know that we're about to delete this one, and also - // what the next least recently used key will be, so just - // go ahead and set it now. - var prev = walker.prev - del(self, walker) - walker = prev - } - } -} - -function del (self, node) { - if (node) { - var hit = node.value - if (priv(self, 'dispose')) { - priv(self, 'dispose').call(this, hit.key, hit.value) - } - priv(self, 'length', priv(self, 'length') - hit.length) - priv(self, 'cache').delete(hit.key) - priv(self, 'lruList').removeNode(node) - } -} - -// classy, since V8 prefers predictable objects. -function Entry (key, value, length, now, maxAge) { - this.key = key - this.value = value - this.length = length - this.now = now - this.maxAge = maxAge || 0 -} - - -/***/ }), +/* 116 */, /* 117 */, /* 118 */ /***/ (function(module, __unusedexports, __webpack_require__) { @@ -7490,130 +7840,321 @@ module.exports.default = macosRelease; /***/ }), -/* 119 */ -/***/ (function(module) { +/* 119 */, +/* 120 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { -/** - * Checks if a stack value for `key` exists. - * - * @private - * @name has - * @memberOf Stack - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. +"use strict"; +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed */ -function stackHas(key) { - return this.__data__.has(key); -} -module.exports = stackHas; -/***/ }), -/* 120 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +/** + * Module dependencies. + * @api private + */ -"use strict"; +var Buffer = __webpack_require__(9).Buffer +var contentDisposition = __webpack_require__(492); +var contentType = __webpack_require__(478); +var deprecate = __webpack_require__(418)('express'); +var flatten = __webpack_require__(211); +var mime = __webpack_require__(381).mime; +var etag = __webpack_require__(521); +var proxyaddr = __webpack_require__(410); +var qs = __webpack_require__(386); +var querystring = __webpack_require__(191); +/** + * Return strong ETag for `body`. + * + * @param {String|Buffer} body + * @param {String} [encoding] + * @return {String} + * @api private + */ -const assert = __webpack_require__(357) +exports.etag = createETagGenerator({ weak: false }) -class RedisError extends Error { - get name () { - return this.constructor.name - } -} +/** + * Return weak ETag for `body`. + * + * @param {String|Buffer} body + * @param {String} [encoding] + * @return {String} + * @api private + */ -class ParserError extends RedisError { - constructor (message, buffer, offset) { - assert(buffer) - assert.strictEqual(typeof offset, 'number') +exports.wetag = createETagGenerator({ weak: true }) - const tmp = Error.stackTraceLimit - Error.stackTraceLimit = 2 - super(message) - Error.stackTraceLimit = tmp - this.offset = offset - this.buffer = buffer - } +/** + * Check if `path` looks absolute. + * + * @param {String} path + * @return {Boolean} + * @api private + */ - get name () { - return this.constructor.name - } -} +exports.isAbsolute = function(path){ + if ('/' === path[0]) return true; + if (':' === path[1] && ('\\' === path[2] || '/' === path[2])) return true; // Windows device path + if ('\\\\' === path.substring(0, 2)) return true; // Microsoft Azure absolute path +}; -class ReplyError extends RedisError { - constructor (message) { - const tmp = Error.stackTraceLimit - Error.stackTraceLimit = 2 - super(message) - Error.stackTraceLimit = tmp - } - get name () { - return this.constructor.name +/** + * Flatten the given `arr`. + * + * @param {Array} arr + * @return {Array} + * @api private + */ + +exports.flatten = deprecate.function(flatten, + 'utils.flatten: use array-flatten npm module instead'); + +/** + * Normalize the given `type`, for example "html" becomes "text/html". + * + * @param {String} type + * @return {Object} + * @api private + */ + +exports.normalizeType = function(type){ + return ~type.indexOf('/') + ? acceptParams(type) + : { value: mime.lookup(type), params: {} }; +}; + +/** + * Normalize `types`, for example "html" becomes "text/html". + * + * @param {Array} types + * @return {Array} + * @api private + */ + +exports.normalizeTypes = function(types){ + var ret = []; + + for (var i = 0; i < types.length; ++i) { + ret.push(exports.normalizeType(types[i])); + } + + return ret; +}; + +/** + * Generate Content-Disposition header appropriate for the filename. + * non-ascii filenames are urlencoded and a filename* parameter is added + * + * @param {String} filename + * @return {String} + * @api private + */ + +exports.contentDisposition = deprecate.function(contentDisposition, + 'utils.contentDisposition: use content-disposition npm module instead'); + +/** + * Parse accept params `str` returning an + * object with `.value`, `.quality` and `.params`. + * also includes `.originalIndex` for stable sorting + * + * @param {String} str + * @return {Object} + * @api private + */ + +function acceptParams(str, index) { + var parts = str.split(/ *; */); + var ret = { value: parts[0], quality: 1, params: {}, originalIndex: index }; + + for (var i = 1; i < parts.length; ++i) { + var pms = parts[i].split(/ *= */); + if ('q' === pms[0]) { + ret.quality = parseFloat(pms[1]); + } else { + ret.params[pms[0]] = pms[1]; + } } + + return ret; } -class AbortError extends RedisError { - get name () { - return this.constructor.name +/** + * Compile "etag" value to function. + * + * @param {Boolean|String|Function} val + * @return {Function} + * @api private + */ + +exports.compileETag = function(val) { + var fn; + + if (typeof val === 'function') { + return val; } + + switch (val) { + case true: + fn = exports.wetag; + break; + case false: + break; + case 'strong': + fn = exports.etag; + break; + case 'weak': + fn = exports.wetag; + break; + default: + throw new TypeError('unknown value for etag function: ' + val); + } + + return fn; } -class InterruptError extends AbortError { - get name () { - return this.constructor.name +/** + * Compile "query parser" value to function. + * + * @param {String|Function} val + * @return {Function} + * @api private + */ + +exports.compileQueryParser = function compileQueryParser(val) { + var fn; + + if (typeof val === 'function') { + return val; + } + + switch (val) { + case true: + fn = querystring.parse; + break; + case false: + fn = newObject; + break; + case 'extended': + fn = parseExtendedQueryString; + break; + case 'simple': + fn = querystring.parse; + break; + default: + throw new TypeError('unknown value for query parser function: ' + val); } + + return fn; } -module.exports = { - RedisError, - ParserError, - ReplyError, - AbortError, - InterruptError +/** + * Compile "proxy trust" value to function. + * + * @param {Boolean|String|Number|Array|Function} val + * @return {Function} + * @api private + */ + +exports.compileTrust = function(val) { + if (typeof val === 'function') return val; + + if (val === true) { + // Support plain true/false + return function(){ return true }; + } + + if (typeof val === 'number') { + // Support trusting hop count + return function(a, i){ return i < val }; + } + + if (typeof val === 'string') { + // Support comma-separated values + val = val.split(/ *, */); + } + + return proxyaddr.compile(val || []); } +/** + * Set the charset in a given Content-Type string. + * + * @param {String} type + * @param {String} charset + * @return {String} + * @api private + */ -/***/ }), -/* 121 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +exports.setCharset = function setCharset(type, charset) { + if (!type || !charset) { + return type; + } + + // parse type + var parsed = contentType.parse(type); + + // set charset + parsed.parameters.charset = charset; -var mapCacheClear = __webpack_require__(812), - mapCacheDelete = __webpack_require__(78), - mapCacheGet = __webpack_require__(604), - mapCacheHas = __webpack_require__(61), - mapCacheSet = __webpack_require__(73); + // format type + return contentType.format(parsed); +}; /** - * Creates a map cache object to store key-value pairs. + * Create an ETag generator function, generating ETags with + * the given options. * + * @param {object} options + * @return {function} * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. */ -function MapCache(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); +function createETagGenerator (options) { + return function generateETag (body, encoding) { + var buf = !Buffer.isBuffer(body) + ? Buffer.from(body, encoding) + : body + + return etag(buf, options) } } -// Add methods to `MapCache`. -MapCache.prototype.clear = mapCacheClear; -MapCache.prototype['delete'] = mapCacheDelete; -MapCache.prototype.get = mapCacheGet; -MapCache.prototype.has = mapCacheHas; -MapCache.prototype.set = mapCacheSet; +/** + * Parse an extended query string with qs. + * + * @return {Object} + * @private + */ + +function parseExtendedQueryString(str) { + return qs.parse(str, { + allowPrototypes: true + }); +} + +/** + * Return new empty object. + * + * @return {Object} + * @api private + */ -module.exports = MapCache; +function newObject() { + return {}; +} /***/ }), +/* 121 */, /* 122 */ /***/ (function(module) { @@ -7621,22 +8162,168 @@ module.exports = {"application/andrew-inset":["ez"],"application/applixware":["a /***/ }), /* 123 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { +/***/ (function(module, __unusedexports, __webpack_require__) { "use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.resolve = void 0; -var resolve_1 = __webpack_require__(977); -var defaultOptions = {}; -exports.resolve = function (appFnId, opts) { - opts = opts || defaultOptions; - // These are mostly to ease testing - var basedir = opts.basedir || process.cwd(); - var resolver = opts.resolver || resolve_1.sync; - return require(resolver(appFnId, { basedir: basedir })); -}; -//# sourceMappingURL=resolver.js.map + +const chalk = __webpack_require__(198) +const jmespath = __webpack_require__(802) +const colors = __webpack_require__(350) +const { ERROR_LIKE_KEYS, MESSAGE_KEY, TIMESTAMP_KEY } = __webpack_require__(819) +const { + isObject, + prettifyErrorLog, + prettifyLevel, + prettifyMessage, + prettifyMetadata, + prettifyObject, + prettifyTime +} = __webpack_require__(586) + +const bourne = __webpack_require__(899) +const jsonParser = input => { + try { + return { value: bourne.parse(input, { protoAction: 'remove' }) } + } catch (err) { + return { err } + } +} + +const defaultOptions = { + colorize: chalk.supportsColor, + crlf: false, + errorLikeObjectKeys: ERROR_LIKE_KEYS, + errorProps: '', + levelFirst: false, + messageKey: MESSAGE_KEY, + messageFormat: false, + timestampKey: TIMESTAMP_KEY, + translateTime: false, + useMetadata: false, + outputStream: process.stdout, + customPrettifiers: {} +} + +module.exports = function prettyFactory (options) { + const opts = Object.assign({}, defaultOptions, options) + const EOL = opts.crlf ? '\r\n' : '\n' + const IDENT = ' ' + const messageKey = opts.messageKey + const levelKey = opts.levelKey + const messageFormat = opts.messageFormat + const timestampKey = opts.timestampKey + const errorLikeObjectKeys = opts.errorLikeObjectKeys + const errorProps = opts.errorProps.split(',') + const customPrettifiers = opts.customPrettifiers + const ignoreKeys = opts.ignore ? new Set(opts.ignore.split(',')) : undefined + + const colorizer = colors(opts.colorize) + const search = opts.search + + return pretty + + function pretty (inputData) { + let log + if (!isObject(inputData)) { + const parsed = jsonParser(inputData) + if (parsed.err || !isObject(parsed.value)) { + // pass through + return inputData + EOL + } + log = parsed.value + } else { + log = inputData + } + + if (search && !jmespath.search(log, search)) { + return + } + + const prettifiedMessage = prettifyMessage({ log, messageKey, colorizer, messageFormat }) + + if (ignoreKeys) { + log = Object.keys(log) + .filter(key => !ignoreKeys.has(key)) + .reduce((res, key) => { + res[key] = log[key] + return res + }, {}) + } + + const prettifiedLevel = prettifyLevel({ log, colorizer, levelKey }) + const prettifiedMetadata = prettifyMetadata({ log }) + const prettifiedTime = prettifyTime({ log, translateFormat: opts.translateTime, timestampKey }) + + let line = '' + if (opts.levelFirst && prettifiedLevel) { + line = `${prettifiedLevel}` + } + + if (prettifiedTime && line === '') { + line = `${prettifiedTime}` + } else if (prettifiedTime) { + line = `${line} ${prettifiedTime}` + } + + if (!opts.levelFirst && prettifiedLevel) { + if (line.length > 0) { + line = `${line} ${prettifiedLevel}` + } else { + line = prettifiedLevel + } + } + + if (prettifiedMetadata) { + if (line.length > 0) { + line = `${line} ${prettifiedMetadata}:` + } else { + line = prettifiedMetadata + } + } + + if (line.endsWith(':') === false && line !== '') { + line += ':' + } + + if (prettifiedMessage) { + if (line.length > 0) { + line = `${line} ${prettifiedMessage}` + } else { + line = prettifiedMessage + } + } + + if (line.length > 0) { + line += EOL + } + + if (log.type === 'Error' && log.stack) { + const prettifiedErrorLog = prettifyErrorLog({ + log, + errorLikeKeys: errorLikeObjectKeys, + errorProperties: errorProps, + ident: IDENT, + eol: EOL + }) + line += prettifiedErrorLog + } else { + const skipKeys = [messageKey, levelKey, timestampKey].filter(key => typeof log[key] === 'string' || typeof log[key] === 'number') + const prettifiedObject = prettifyObject({ + input: log, + skipKeys, + customPrettifiers, + errorLikeKeys: errorLikeObjectKeys, + eol: EOL, + ident: IDENT + }) + line += prettifiedObject + } + + return line + } +} + /***/ }), /* 124 */, @@ -7647,7 +8334,7 @@ exports.resolve = function (appFnId, opts) { var util = __webpack_require__(669); -var isArrayish = __webpack_require__(156); +var isArrayish = __webpack_require__(479); var errorEx = function errorEx(name, properties) { if (!name || name.constructor !== String) { @@ -7789,2515 +8476,1433 @@ module.exports = errorEx; /***/ }), /* 126 */ -/***/ (function(module) { +/***/ (function(__unusedmodule, exports) { -/** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors +/*! + * media-typer + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed */ -/** Used as the size to enable large array optimizations. */ -var LARGE_ARRAY_SIZE = 200; - -/** Used to stand-in for `undefined` hash values. */ -var HASH_UNDEFINED = '__lodash_hash_undefined__'; - -/** Used as references for various `Number` constants. */ -var INFINITY = 1 / 0; - -/** `Object#toString` result references. */ -var funcTag = '[object Function]', - genTag = '[object GeneratorFunction]'; - /** - * Used to match `RegExp` - * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + * RegExp to match *( ";" parameter ) in RFC 2616 sec 3.7 + * + * parameter = token "=" ( token | quoted-string ) + * token = 1* + * separators = "(" | ")" | "<" | ">" | "@" + * | "," | ";" | ":" | "\" | <"> + * | "/" | "[" | "]" | "?" | "=" + * | "{" | "}" | SP | HT + * quoted-string = ( <"> *(qdtext | quoted-pair ) <"> ) + * qdtext = > + * quoted-pair = "\" CHAR + * CHAR = + * TEXT = + * LWS = [CRLF] 1*( SP | HT ) + * CRLF = CR LF + * CR = + * LF = + * SP = + * SHT = + * CTL = + * OCTET = */ -var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; - -/** Used to detect host constructors (Safari). */ -var reIsHostCtor = /^\[object .+?Constructor\]$/; - -/** Detect free variable `global` from Node.js. */ -var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; +var paramRegExp = /; *([!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+) *= *("(?:[ !\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u0020-\u007e])*"|[!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+) */g; +var textRegExp = /^[\u0020-\u007e\u0080-\u00ff]+$/ +var tokenRegExp = /^[!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+$/ -/** Detect free variable `self`. */ -var freeSelf = typeof self == 'object' && self && self.Object === Object && self; +/** + * RegExp to match quoted-pair in RFC 2616 + * + * quoted-pair = "\" CHAR + * CHAR = + */ +var qescRegExp = /\\([\u0000-\u007f])/g; -/** Used as a reference to the global object. */ -var root = freeGlobal || freeSelf || Function('return this')(); +/** + * RegExp to match chars that must be quoted-pair in RFC 2616 + */ +var quoteRegExp = /([\\"])/g; /** - * A specialized version of `_.includes` for arrays without support for - * specifying an index to search from. + * RegExp to match type in RFC 6838 * - * @private - * @param {Array} [array] The array to inspect. - * @param {*} target The value to search for. - * @returns {boolean} Returns `true` if `target` is found, else `false`. + * type-name = restricted-name + * subtype-name = restricted-name + * restricted-name = restricted-name-first *126restricted-name-chars + * restricted-name-first = ALPHA / DIGIT + * restricted-name-chars = ALPHA / DIGIT / "!" / "#" / + * "$" / "&" / "-" / "^" / "_" + * restricted-name-chars =/ "." ; Characters before first dot always + * ; specify a facet name + * restricted-name-chars =/ "+" ; Characters after last plus always + * ; specify a structured syntax suffix + * ALPHA = %x41-5A / %x61-7A ; A-Z / a-z + * DIGIT = %x30-39 ; 0-9 */ -function arrayIncludes(array, value) { - var length = array ? array.length : 0; - return !!length && baseIndexOf(array, value, 0) > -1; -} +var subtypeNameRegExp = /^[A-Za-z0-9][A-Za-z0-9!#$&^_.-]{0,126}$/ +var typeNameRegExp = /^[A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126}$/ +var typeRegExp = /^ *([A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126})\/([A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}) *$/; /** - * This function is like `arrayIncludes` except that it accepts a comparator. - * - * @private - * @param {Array} [array] The array to inspect. - * @param {*} target The value to search for. - * @param {Function} comparator The comparator invoked per element. - * @returns {boolean} Returns `true` if `target` is found, else `false`. + * Module exports. */ -function arrayIncludesWith(array, value, comparator) { - var index = -1, - length = array ? array.length : 0; - while (++index < length) { - if (comparator(value, array[index])) { - return true; - } - } - return false; -} +exports.format = format +exports.parse = parse /** - * The base implementation of `_.findIndex` and `_.findLastIndex` without - * support for iteratee shorthands. + * Format object to media type. * - * @private - * @param {Array} array The array to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {number} fromIndex The index to search from. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {number} Returns the index of the matched value, else `-1`. + * @param {object} obj + * @return {string} + * @api public */ -function baseFindIndex(array, predicate, fromIndex, fromRight) { - var length = array.length, - index = fromIndex + (fromRight ? 1 : -1); - while ((fromRight ? index-- : ++index < length)) { - if (predicate(array[index], index, array)) { - return index; - } +function format(obj) { + if (!obj || typeof obj !== 'object') { + throw new TypeError('argument obj is required') } - return -1; -} -/** - * The base implementation of `_.indexOf` without `fromIndex` bounds checks. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function baseIndexOf(array, value, fromIndex) { - if (value !== value) { - return baseFindIndex(array, baseIsNaN, fromIndex); + var parameters = obj.parameters + var subtype = obj.subtype + var suffix = obj.suffix + var type = obj.type + + if (!type || !typeNameRegExp.test(type)) { + throw new TypeError('invalid type') } - var index = fromIndex - 1, - length = array.length; - while (++index < length) { - if (array[index] === value) { - return index; + if (!subtype || !subtypeNameRegExp.test(subtype)) { + throw new TypeError('invalid subtype') + } + + // format as type/subtype + var string = type + '/' + subtype + + // append +suffix + if (suffix) { + if (!typeNameRegExp.test(suffix)) { + throw new TypeError('invalid suffix') } + + string += '+' + suffix } - return -1; -} -/** - * The base implementation of `_.isNaN` without support for number objects. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - */ -function baseIsNaN(value) { - return value !== value; -} + // append parameters + if (parameters && typeof parameters === 'object') { + var param + var params = Object.keys(parameters).sort() -/** - * Checks if a cache value for `key` exists. - * - * @private - * @param {Object} cache The cache to query. - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function cacheHas(cache, key) { - return cache.has(key); -} + for (var i = 0; i < params.length; i++) { + param = params[i] -/** - * Gets the value at `key` of `object`. - * - * @private - * @param {Object} [object] The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. - */ -function getValue(object, key) { - return object == null ? undefined : object[key]; -} + if (!tokenRegExp.test(param)) { + throw new TypeError('invalid parameter name') + } -/** - * Checks if `value` is a host object in IE < 9. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a host object, else `false`. - */ -function isHostObject(value) { - // Many host objects are `Object` objects that can coerce to strings - // despite having improperly defined `toString` methods. - var result = false; - if (value != null && typeof value.toString != 'function') { - try { - result = !!(value + ''); - } catch (e) {} + string += '; ' + param + '=' + qstring(parameters[param]) + } } - return result; + + return string } /** - * Converts `set` to an array of its values. + * Parse media type to object. * - * @private - * @param {Object} set The set to convert. - * @returns {Array} Returns the values. + * @param {string|object} string + * @return {Object} + * @api public */ -function setToArray(set) { - var index = -1, - result = Array(set.size); - - set.forEach(function(value) { - result[++index] = value; - }); - return result; -} -/** Used for built-in method references. */ -var arrayProto = Array.prototype, - funcProto = Function.prototype, - objectProto = Object.prototype; +function parse(string) { + if (!string) { + throw new TypeError('argument string is required') + } -/** Used to detect overreaching core-js shims. */ -var coreJsData = root['__core-js_shared__']; - -/** Used to detect methods masquerading as native. */ -var maskSrcKey = (function() { - var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); - return uid ? ('Symbol(src)_1.' + uid) : ''; -}()); + // support req/res-like objects as argument + if (typeof string === 'object') { + string = getcontenttype(string) + } -/** Used to resolve the decompiled source of functions. */ -var funcToString = funcProto.toString; + if (typeof string !== 'string') { + throw new TypeError('argument string is required to be a string') + } -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; + var index = string.indexOf(';') + var type = index !== -1 + ? string.substr(0, index) + : string -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; + var key + var match + var obj = splitType(type) + var params = {} + var value -/** Used to detect if a method is native. */ -var reIsNative = RegExp('^' + - funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') - .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' -); + paramRegExp.lastIndex = index -/** Built-in value references. */ -var splice = arrayProto.splice; + while (match = paramRegExp.exec(string)) { + if (match.index !== index) { + throw new TypeError('invalid parameter format') + } -/* Built-in method references that are verified to be native. */ -var Map = getNative(root, 'Map'), - Set = getNative(root, 'Set'), - nativeCreate = getNative(Object, 'create'); + index += match[0].length + key = match[1].toLowerCase() + value = match[2] -/** - * Creates a hash object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ -function Hash(entries) { - var index = -1, - length = entries ? entries.length : 0; + if (value[0] === '"') { + // remove quotes and escapes + value = value + .substr(1, value.length - 2) + .replace(qescRegExp, '$1') + } - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); + params[key] = value } -} - -/** - * Removes all key-value entries from the hash. - * - * @private - * @name clear - * @memberOf Hash - */ -function hashClear() { - this.__data__ = nativeCreate ? nativeCreate(null) : {}; -} - -/** - * Removes `key` and its value from the hash. - * - * @private - * @name delete - * @memberOf Hash - * @param {Object} hash The hash to modify. - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ -function hashDelete(key) { - return this.has(key) && delete this.__data__[key]; -} -/** - * Gets the hash value for `key`. - * - * @private - * @name get - * @memberOf Hash - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ -function hashGet(key) { - var data = this.__data__; - if (nativeCreate) { - var result = data[key]; - return result === HASH_UNDEFINED ? undefined : result; + if (index !== -1 && index !== string.length) { + throw new TypeError('invalid parameter format') } - return hasOwnProperty.call(data, key) ? data[key] : undefined; -} -/** - * Checks if a hash value for `key` exists. - * - * @private - * @name has - * @memberOf Hash - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function hashHas(key) { - var data = this.__data__; - return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key); -} + obj.parameters = params -/** - * Sets the hash `key` to `value`. - * - * @private - * @name set - * @memberOf Hash - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the hash instance. - */ -function hashSet(key, value) { - var data = this.__data__; - data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; - return this; + return obj } -// Add methods to `Hash`. -Hash.prototype.clear = hashClear; -Hash.prototype['delete'] = hashDelete; -Hash.prototype.get = hashGet; -Hash.prototype.has = hashHas; -Hash.prototype.set = hashSet; - /** - * Creates an list cache object. + * Get content-type from req/res objects. * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. + * @param {object} + * @return {Object} + * @api private */ -function ListCache(entries) { - var index = -1, - length = entries ? entries.length : 0; - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); +function getcontenttype(obj) { + if (typeof obj.getHeader === 'function') { + // res-like + return obj.getHeader('content-type') } -} - -/** - * Removes all key-value entries from the list cache. - * - * @private - * @name clear - * @memberOf ListCache - */ -function listCacheClear() { - this.__data__ = []; -} - -/** - * Removes `key` and its value from the list cache. - * - * @private - * @name delete - * @memberOf ListCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ -function listCacheDelete(key) { - var data = this.__data__, - index = assocIndexOf(data, key); - if (index < 0) { - return false; - } - var lastIndex = data.length - 1; - if (index == lastIndex) { - data.pop(); - } else { - splice.call(data, index, 1); + if (typeof obj.headers === 'object') { + // req-like + return obj.headers && obj.headers['content-type'] } - return true; } /** - * Gets the list cache value for `key`. + * Quote a string if necessary. * - * @private - * @name get - * @memberOf ListCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. + * @param {string} val + * @return {string} + * @api private */ -function listCacheGet(key) { - var data = this.__data__, - index = assocIndexOf(data, key); - return index < 0 ? undefined : data[index][1]; -} - -/** - * Checks if a list cache value for `key` exists. - * - * @private - * @name has - * @memberOf ListCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function listCacheHas(key) { - return assocIndexOf(this.__data__, key) > -1; -} +function qstring(val) { + var str = String(val) -/** - * Sets the list cache `key` to `value`. - * - * @private - * @name set - * @memberOf ListCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the list cache instance. - */ -function listCacheSet(key, value) { - var data = this.__data__, - index = assocIndexOf(data, key); - - if (index < 0) { - data.push([key, value]); - } else { - data[index][1] = value; + // no need to quote tokens + if (tokenRegExp.test(str)) { + return str } - return this; -} - -// Add methods to `ListCache`. -ListCache.prototype.clear = listCacheClear; -ListCache.prototype['delete'] = listCacheDelete; -ListCache.prototype.get = listCacheGet; -ListCache.prototype.has = listCacheHas; -ListCache.prototype.set = listCacheSet; - -/** - * Creates a map cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ -function MapCache(entries) { - var index = -1, - length = entries ? entries.length : 0; - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); + if (str.length > 0 && !textRegExp.test(str)) { + throw new TypeError('invalid parameter value') } -} - -/** - * Removes all key-value entries from the map. - * - * @private - * @name clear - * @memberOf MapCache - */ -function mapCacheClear() { - this.__data__ = { - 'hash': new Hash, - 'map': new (Map || ListCache), - 'string': new Hash - }; -} - -/** - * Removes `key` and its value from the map. - * - * @private - * @name delete - * @memberOf MapCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ -function mapCacheDelete(key) { - return getMapData(this, key)['delete'](key); -} -/** - * Gets the map value for `key`. - * - * @private - * @name get - * @memberOf MapCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ -function mapCacheGet(key) { - return getMapData(this, key).get(key); + return '"' + str.replace(quoteRegExp, '\\$1') + '"' } /** - * Checks if a map value for `key` exists. + * Simply "type/subtype+siffx" into parts. * - * @private - * @name has - * @memberOf MapCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + * @param {string} string + * @return {Object} + * @api private */ -function mapCacheHas(key) { - return getMapData(this, key).has(key); -} - -/** - * Sets the map `key` to `value`. - * - * @private - * @name set - * @memberOf MapCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the map cache instance. - */ -function mapCacheSet(key, value) { - getMapData(this, key).set(key, value); - return this; -} - -// Add methods to `MapCache`. -MapCache.prototype.clear = mapCacheClear; -MapCache.prototype['delete'] = mapCacheDelete; -MapCache.prototype.get = mapCacheGet; -MapCache.prototype.has = mapCacheHas; -MapCache.prototype.set = mapCacheSet; -/** - * - * Creates an array cache object to store unique values. - * - * @private - * @constructor - * @param {Array} [values] The values to cache. - */ -function SetCache(values) { - var index = -1, - length = values ? values.length : 0; +function splitType(string) { + var match = typeRegExp.exec(string.toLowerCase()) - this.__data__ = new MapCache; - while (++index < length) { - this.add(values[index]); + if (!match) { + throw new TypeError('invalid media type') } -} - -/** - * Adds `value` to the array cache. - * - * @private - * @name add - * @memberOf SetCache - * @alias push - * @param {*} value The value to cache. - * @returns {Object} Returns the cache instance. - */ -function setCacheAdd(value) { - this.__data__.set(value, HASH_UNDEFINED); - return this; -} - -/** - * Checks if `value` is in the array cache. - * - * @private - * @name has - * @memberOf SetCache - * @param {*} value The value to search for. - * @returns {number} Returns `true` if `value` is found, else `false`. - */ -function setCacheHas(value) { - return this.__data__.has(value); -} -// Add methods to `SetCache`. -SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; -SetCache.prototype.has = setCacheHas; + var type = match[1] + var subtype = match[2] + var suffix -/** - * Gets the index at which the `key` is found in `array` of key-value pairs. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} key The key to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function assocIndexOf(array, key) { - var length = array.length; - while (length--) { - if (eq(array[length][0], key)) { - return length; - } + // suffix after last + + var index = subtype.lastIndexOf('+') + if (index !== -1) { + suffix = subtype.substr(index + 1) + subtype = subtype.substr(0, index) } - return -1; -} -/** - * The base implementation of `_.isNative` without bad shim checks. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a native function, - * else `false`. - */ -function baseIsNative(value) { - if (!isObject(value) || isMasked(value)) { - return false; + var obj = { + type: type, + subtype: subtype, + suffix: suffix } - var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor; - return pattern.test(toSource(value)); + + return obj } -/** - * The base implementation of `_.uniqBy` without support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new duplicate free array. - */ -function baseUniq(array, iteratee, comparator) { - var index = -1, - includes = arrayIncludes, - length = array.length, - isCommon = true, - result = [], - seen = result; - if (comparator) { - isCommon = false; - includes = arrayIncludesWith; - } - else if (length >= LARGE_ARRAY_SIZE) { - var set = iteratee ? null : createSet(array); - if (set) { - return setToArray(set); - } - isCommon = false; - includes = cacheHas; - seen = new SetCache; - } - else { - seen = iteratee ? [] : result; - } - outer: - while (++index < length) { - var value = array[index], - computed = iteratee ? iteratee(value) : value; +/***/ }), +/* 127 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - value = (comparator || value !== 0) ? value : 0; - if (isCommon && computed === computed) { - var seenIndex = seen.length; - while (seenIndex--) { - if (seen[seenIndex] === computed) { - continue outer; - } - } - if (iteratee) { - seen.push(computed); - } - result.push(value); - } - else if (!includes(seen, computed, comparator)) { - if (seen !== result) { - seen.push(computed); - } - result.push(value); - } - } - return result; -} +var core = __webpack_require__(391); -/** - * Creates a set object of `values`. - * - * @private - * @param {Array} values The values to add to the set. - * @returns {Object} Returns the new set. - */ -var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { - return new Set(values); +module.exports = function isCore(x) { + return Object.prototype.hasOwnProperty.call(core, x); }; -/** - * Gets the data for `map`. - * - * @private - * @param {Object} map The map to query. - * @param {string} key The reference key. - * @returns {*} Returns the map data. - */ -function getMapData(map, key) { - var data = map.__data__; - return isKeyable(key) - ? data[typeof key == 'string' ? 'string' : 'hash'] - : data.map; -} - -/** - * Gets the native function at `key` of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the method to get. - * @returns {*} Returns the function if it's native, else `undefined`. - */ -function getNative(object, key) { - var value = getValue(object, key); - return baseIsNative(value) ? value : undefined; -} -/** - * Checks if `value` is suitable for use as unique object key. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is suitable, else `false`. - */ -function isKeyable(value) { - var type = typeof value; - return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') - ? (value !== '__proto__') - : (value === null); -} +/***/ }), +/* 128 */, +/* 129 */ +/***/ (function(module) { -/** - * Checks if `func` has its source masked. - * - * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` is masked, else `false`. - */ -function isMasked(func) { - return !!maskSrcKey && (maskSrcKey in func); -} +module.exports = require("child_process"); -/** - * Converts `func` to its source code. - * - * @private - * @param {Function} func The function to process. - * @returns {string} Returns the source code. - */ -function toSource(func) { - if (func != null) { - try { - return funcToString.call(func); - } catch (e) {} - try { - return (func + ''); - } catch (e) {} - } - return ''; -} +/***/ }), +/* 130 */ +/***/ (function(module) { -/** - * Creates a duplicate-free version of an array, using - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons, in which only the first occurrence of each - * element is kept. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @returns {Array} Returns the new duplicate free array. - * @example - * - * _.uniq([2, 1, 2]); - * // => [2, 1] - */ -function uniq(array) { - return (array && array.length) - ? baseUniq(array) - : []; -} +"use strict"; -/** - * Performs a - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * comparison between two values to determine if they are equivalent. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true - * - * _.eq('a', Object('a')); - * // => false - * - * _.eq(NaN, NaN); - * // => true - */ -function eq(value, other) { - return value === other || (value !== value && other !== other); -} -/** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ -function isFunction(value) { - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 8-9 which returns 'object' for typed array and other constructors. - var tag = isObject(value) ? objectToString.call(value) : ''; - return tag == funcTag || tag == genTag; -} +const pTry = (fn, ...arguments_) => new Promise(resolve => { + resolve(fn(...arguments_)); +}); -/** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ -function isObject(value) { - var type = typeof value; - return !!value && (type == 'object' || type == 'function'); -} +module.exports = pTry; +// TODO: remove this in the next major version +module.exports.default = pTry; -/** - * This method returns `undefined`. - * - * @static - * @memberOf _ - * @since 2.3.0 - * @category Util - * @example - * - * _.times(2, _.noop); - * // => [undefined, undefined] - */ -function noop() { - // No operation performed. -} -module.exports = uniq; +/***/ }), +/* 131 */, +/* 132 */, +/* 133 */ +/***/ (function(module, __unusedexports, __webpack_require__) { +"use strict"; -/***/ }), -/* 127 */ -/***/ (function(module) { -/** - * Creates a unary function that invokes `func` with its argument transformed. - * - * @private - * @param {Function} func The function to wrap. - * @param {Function} transform The argument transform. - * @returns {Function} Returns the new function. - */ -function overArg(func, transform) { - return function(arg) { - return func(transform(arg)); - }; -} +var Type = __webpack_require__(945); -module.exports = overArg; +module.exports = new Type('tag:yaml.org,2002:seq', { + kind: 'sequence', + construct: function (data) { return data !== null ? data : []; } +}); /***/ }), -/* 128 */ -/***/ (function(module, exports, __webpack_require__) { +/* 134 */ +/***/ (function(__unusedmodule, exports) { "use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - - - -/** - * Module dependencies. - * @private - */ -var finalhandler = __webpack_require__(430); -var Router = __webpack_require__(987); -var methods = __webpack_require__(203); -var middleware = __webpack_require__(917); -var query = __webpack_require__(210); -var debug = __webpack_require__(590)('express:application'); -var View = __webpack_require__(75); -var http = __webpack_require__(605); -var compileETag = __webpack_require__(103).compileETag; -var compileQueryParser = __webpack_require__(103).compileQueryParser; -var compileTrust = __webpack_require__(103).compileTrust; -var deprecate = __webpack_require__(418)('express'); -var flatten = __webpack_require__(31); -var merge = __webpack_require__(707); -var resolve = __webpack_require__(622).resolve; -var setPrototypeOf = __webpack_require__(64) -var slice = Array.prototype.slice; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.VERSION = void 0; +// The version is set automatically before publish to npm +exports.VERSION = "10.7.0"; +//# sourceMappingURL=version.js.map -/** - * Application prototype. - */ +/***/ }), +/* 135 */ +/***/ (function(module, __unusedexports, __webpack_require__) { -var app = exports = module.exports = {}; +var fs = __webpack_require__(747); +var path = __webpack_require__(622); +var caller = __webpack_require__(465); +var nodeModulesPaths = __webpack_require__(575); +var normalizeOptions = __webpack_require__(544); +var isCore = __webpack_require__(127); -/** - * Variable for trust proxy inheritance back-compat - * @private - */ +var defaultIsFile = function isFile(file, cb) { + fs.stat(file, function (err, stat) { + if (!err) { + return cb(null, stat.isFile() || stat.isFIFO()); + } + if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false); + return cb(err); + }); +}; -var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default'; +var defaultIsDir = function isDirectory(dir, cb) { + fs.stat(dir, function (err, stat) { + if (!err) { + return cb(null, stat.isDirectory()); + } + if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false); + return cb(err); + }); +}; -/** - * Initialize the server. - * - * - setup default configuration - * - setup default middleware - * - setup route reflection methods - * - * @private - */ - -app.init = function init() { - this.cache = {}; - this.engines = {}; - this.settings = {}; +var maybeUnwrapSymlink = function maybeUnwrapSymlink(x, opts, cb) { + if (opts && opts.preserveSymlinks === false) { + fs.realpath(x, function (realPathErr, realPath) { + if (realPathErr && realPathErr.code !== 'ENOENT') cb(realPathErr); + else cb(null, realPathErr ? x : realPath); + }); + } else { + cb(null, x); + } +}; - this.defaultConfiguration(); +var getPackageCandidates = function getPackageCandidates(x, start, opts) { + var dirs = nodeModulesPaths(start, opts, x); + for (var i = 0; i < dirs.length; i++) { + dirs[i] = path.join(dirs[i], x); + } + return dirs; }; -/** - * Initialize application configuration. - * @private - */ +module.exports = function resolve(x, options, callback) { + var cb = callback; + var opts = options; + if (typeof options === 'function') { + cb = opts; + opts = {}; + } + if (typeof x !== 'string') { + var err = new TypeError('Path must be a string.'); + return process.nextTick(function () { + cb(err); + }); + } -app.defaultConfiguration = function defaultConfiguration() { - var env = process.env.NODE_ENV || 'development'; + opts = normalizeOptions(x, opts); - // default settings - this.enable('x-powered-by'); - this.set('etag', 'weak'); - this.set('env', env); - this.set('query parser', 'extended'); - this.set('subdomain offset', 2); - this.set('trust proxy', false); + var isFile = opts.isFile || defaultIsFile; + var isDirectory = opts.isDirectory || defaultIsDir; + var readFile = opts.readFile || fs.readFile; + var packageIterator = opts.packageIterator; - // trust proxy inherit back-compat - Object.defineProperty(this.settings, trustProxyDefaultSymbol, { - configurable: true, - value: true - }); + var extensions = opts.extensions || ['.js']; + var basedir = opts.basedir || path.dirname(caller()); + var parent = opts.filename || basedir; - debug('booting in %s mode', env); + opts.paths = opts.paths || []; - this.on('mount', function onmount(parent) { - // inherit trust proxy - if (this.settings[trustProxyDefaultSymbol] === true - && typeof parent.settings['trust proxy fn'] === 'function') { - delete this.settings['trust proxy']; - delete this.settings['trust proxy fn']; - } + // ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory + var absoluteStart = path.resolve(basedir); - // inherit protos - setPrototypeOf(this.request, parent.request) - setPrototypeOf(this.response, parent.response) - setPrototypeOf(this.engines, parent.engines) - setPrototypeOf(this.settings, parent.settings) - }); + maybeUnwrapSymlink( + absoluteStart, + opts, + function (err, realStart) { + if (err) cb(err); + else init(realStart); + } + ); - // setup locals - this.locals = Object.create(null); + var res; + function init(basedir) { + if ((/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/).test(x)) { + res = path.resolve(basedir, x); + if (x === '.' || x === '..' || x.slice(-1) === '/') res += '/'; + if ((/\/$/).test(x) && res === basedir) { + loadAsDirectory(res, opts.package, onfile); + } else loadAsFile(res, opts.package, onfile); + } else if (isCore(x)) { + return cb(null, x); + } else loadNodeModules(x, basedir, function (err, n, pkg) { + if (err) cb(err); + else if (n) { + return maybeUnwrapSymlink(n, opts, function (err, realN) { + if (err) { + cb(err); + } else { + cb(null, realN, pkg); + } + }); + } else { + var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'"); + moduleError.code = 'MODULE_NOT_FOUND'; + cb(moduleError); + } + }); + } - // top-most app is mounted at / - this.mountpath = '/'; + function onfile(err, m, pkg) { + if (err) cb(err); + else if (m) cb(null, m, pkg); + else loadAsDirectory(res, function (err, d, pkg) { + if (err) cb(err); + else if (d) { + maybeUnwrapSymlink(d, opts, function (err, realD) { + if (err) { + cb(err); + } else { + cb(null, realD, pkg); + } + }); + } else { + var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'"); + moduleError.code = 'MODULE_NOT_FOUND'; + cb(moduleError); + } + }); + } - // default locals - this.locals.settings = this.settings; + function loadAsFile(x, thePackage, callback) { + var loadAsFilePackage = thePackage; + var cb = callback; + if (typeof loadAsFilePackage === 'function') { + cb = loadAsFilePackage; + loadAsFilePackage = undefined; + } - // default configuration - this.set('view', View); - this.set('views', resolve('views')); - this.set('jsonp callback name', 'callback'); + var exts = [''].concat(extensions); + load(exts, x, loadAsFilePackage); - if (env === 'production') { - this.enable('view cache'); - } + function load(exts, x, loadPackage) { + if (exts.length === 0) return cb(null, undefined, loadPackage); + var file = x + exts[0]; - Object.defineProperty(this, 'router', { - get: function() { - throw new Error('\'app.router\' is deprecated!\nPlease see the 3.x to 4.x migration guide for details on how to update your app.'); + var pkg = loadPackage; + if (pkg) onpkg(null, pkg); + else loadpkg(path.dirname(file), onpkg); + + function onpkg(err, pkg_, dir) { + pkg = pkg_; + if (err) return cb(err); + if (dir && pkg && opts.pathFilter) { + var rfile = path.relative(dir, file); + var rel = rfile.slice(0, rfile.length - exts[0].length); + var r = opts.pathFilter(pkg, x, rel); + if (r) return load( + [''].concat(extensions.slice()), + path.resolve(dir, r), + pkg + ); + } + isFile(file, onex); + } + function onex(err, ex) { + if (err) return cb(err); + if (ex) return cb(null, file, pkg); + load(exts.slice(1), x, pkg); + } + } } - }); -}; -/** - * lazily adds the base router if it has not yet been added. - * - * We cannot add the base router in the defaultConfiguration because - * it reads app settings which might be set after that has run. - * - * @private - */ -app.lazyrouter = function lazyrouter() { - if (!this._router) { - this._router = new Router({ - caseSensitive: this.enabled('case sensitive routing'), - strict: this.enabled('strict routing') - }); + function loadpkg(dir, cb) { + if (dir === '' || dir === '/') return cb(null); + if (process.platform === 'win32' && (/^\w:[/\\]*$/).test(dir)) { + return cb(null); + } + if ((/[/\\]node_modules[/\\]*$/).test(dir)) return cb(null); - this._router.use(query(this.get('query parser fn'))); - this._router.use(middleware.init(this)); - } -}; + maybeUnwrapSymlink(dir, opts, function (unwrapErr, pkgdir) { + if (unwrapErr) return loadpkg(path.dirname(dir), cb); + var pkgfile = path.join(pkgdir, 'package.json'); + isFile(pkgfile, function (err, ex) { + // on err, ex is false + if (!ex) return loadpkg(path.dirname(dir), cb); -/** - * Dispatch a req, res pair into the application. Starts pipeline processing. - * - * If no callback is provided, then default error handlers will respond - * in the event of an error bubbling through the stack. - * - * @private - */ + readFile(pkgfile, function (err, body) { + if (err) cb(err); + try { var pkg = JSON.parse(body); } catch (jsonErr) {} -app.handle = function handle(req, res, callback) { - var router = this._router; + if (pkg && opts.packageFilter) { + pkg = opts.packageFilter(pkg, pkgfile); + } + cb(null, pkg, dir); + }); + }); + }); + } - // final handler - var done = callback || finalhandler(req, res, { - env: this.get('env'), - onerror: logerror.bind(this) - }); + function loadAsDirectory(x, loadAsDirectoryPackage, callback) { + var cb = callback; + var fpkg = loadAsDirectoryPackage; + if (typeof fpkg === 'function') { + cb = fpkg; + fpkg = opts.package; + } - // no routes - if (!router) { - debug('no routes defined on app'); - done(); - return; - } + maybeUnwrapSymlink(x, opts, function (unwrapErr, pkgdir) { + if (unwrapErr) return cb(unwrapErr); + var pkgfile = path.join(pkgdir, 'package.json'); + isFile(pkgfile, function (err, ex) { + if (err) return cb(err); + if (!ex) return loadAsFile(path.join(x, 'index'), fpkg, cb); - router.handle(req, res, done); -}; + readFile(pkgfile, function (err, body) { + if (err) return cb(err); + try { + var pkg = JSON.parse(body); + } catch (jsonErr) {} -/** - * Proxy `Router#use()` to add middleware to the app router. - * See Router#use() documentation for details. - * - * If the _fn_ parameter is an express app, then it will be - * mounted at the _route_ specified. - * - * @public - */ + if (pkg && opts.packageFilter) { + pkg = opts.packageFilter(pkg, pkgfile); + } -app.use = function use(fn) { - var offset = 0; - var path = '/'; + if (pkg && pkg.main) { + if (typeof pkg.main !== 'string') { + var mainError = new TypeError('package “' + pkg.name + '” `main` must be a string'); + mainError.code = 'INVALID_PACKAGE_MAIN'; + return cb(mainError); + } + if (pkg.main === '.' || pkg.main === './') { + pkg.main = 'index'; + } + loadAsFile(path.resolve(x, pkg.main), pkg, function (err, m, pkg) { + if (err) return cb(err); + if (m) return cb(null, m, pkg); + if (!pkg) return loadAsFile(path.join(x, 'index'), pkg, cb); - // default path to '/' - // disambiguate app.use([fn]) - if (typeof fn !== 'function') { - var arg = fn; + var dir = path.resolve(x, pkg.main); + loadAsDirectory(dir, pkg, function (err, n, pkg) { + if (err) return cb(err); + if (n) return cb(null, n, pkg); + loadAsFile(path.join(x, 'index'), pkg, cb); + }); + }); + return; + } - while (Array.isArray(arg) && arg.length !== 0) { - arg = arg[0]; + loadAsFile(path.join(x, '/index'), pkg, cb); + }); + }); + }); } - // first arg is the path - if (typeof arg !== 'function') { - offset = 1; - path = fn; - } - } + function processDirs(cb, dirs) { + if (dirs.length === 0) return cb(null, undefined); + var dir = dirs[0]; - var fns = flatten(slice.call(arguments, offset)); + isDirectory(path.dirname(dir), isdir); - if (fns.length === 0) { - throw new TypeError('app.use() requires a middleware function') - } + function isdir(err, isdir) { + if (err) return cb(err); + if (!isdir) return processDirs(cb, dirs.slice(1)); + loadAsFile(dir, opts.package, onfile); + } - // setup router - this.lazyrouter(); - var router = this._router; + function onfile(err, m, pkg) { + if (err) return cb(err); + if (m) return cb(null, m, pkg); + loadAsDirectory(dir, opts.package, ondir); + } - fns.forEach(function (fn) { - // non-express app - if (!fn || !fn.handle || !fn.set) { - return router.use(path, fn); + function ondir(err, n, pkg) { + if (err) return cb(err); + if (n) return cb(null, n, pkg); + processDirs(cb, dirs.slice(1)); + } + } + function loadNodeModules(x, start, cb) { + var thunk = function () { return getPackageCandidates(x, start, opts); }; + processDirs( + cb, + packageIterator ? packageIterator(x, start, thunk, opts) : thunk() + ); } +}; - debug('.use app under %s', path); - fn.mountpath = path; - fn.parent = this; - // restore .app property on req and res - router.use(path, function mounted_app(req, res, next) { - var orig = req.app; - fn.handle(req, res, function (err) { - setPrototypeOf(req, orig.request) - setPrototypeOf(res, orig.response) - next(err); - }); - }); +/***/ }), +/* 136 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - // mounted an app - fn.emit('mount', this); - }, this); +"use strict"; - return this; -}; +/* eslint no-prototype-builtins: 0 */ +const flatstr = __webpack_require__(649) +const { + lsCacheSym, + levelValSym, + useOnlyCustomLevelsSym, + streamSym, + formattersSym, + hooksSym +} = __webpack_require__(230) +const { noop, genLog } = __webpack_require__(382) + +const levels = { + trace: 10, + debug: 20, + info: 30, + warn: 40, + error: 50, + fatal: 60 +} +const levelMethods = { + fatal: (hook) => { + const logFatal = genLog(levels.fatal, hook) + return function (...args) { + const stream = this[streamSym] + logFatal.call(this, ...args) + if (typeof stream.flushSync === 'function') { + try { + stream.flushSync() + } catch (e) { + // https://github.com/pinojs/pino/pull/740#discussion_r346788313 + } + } + } + }, + error: (hook) => genLog(levels.error, hook), + warn: (hook) => genLog(levels.warn, hook), + info: (hook) => genLog(levels.info, hook), + debug: (hook) => genLog(levels.debug, hook), + trace: (hook) => genLog(levels.trace, hook) +} -/** - * Proxy to the app `Router#route()` - * Returns a new `Route` instance for the _path_. - * - * Routes are isolated middleware stacks for specific paths. - * See the Route api docs for details. - * - * @public - */ +const nums = Object.keys(levels).reduce((o, k) => { + o[levels[k]] = k + return o +}, {}) -app.route = function route(path) { - this.lazyrouter(); - return this._router.route(path); -}; +const initialLsCache = Object.keys(nums).reduce((o, k) => { + o[k] = flatstr('{"level":' + Number(k)) + return o +}, {}) -/** - * Register the given template engine callback `fn` - * as `ext`. - * - * By default will `require()` the engine based on the - * file extension. For example if you try to render - * a "foo.ejs" file Express will invoke the following internally: - * - * app.engine('ejs', require('ejs').__express); - * - * For engines that do not provide `.__express` out of the box, - * or if you wish to "map" a different extension to the template engine - * you may use this method. For example mapping the EJS template engine to - * ".html" files: - * - * app.engine('html', require('ejs').renderFile); - * - * In this case EJS provides a `.renderFile()` method with - * the same signature that Express expects: `(path, options, callback)`, - * though note that it aliases this method as `ejs.__express` internally - * so if you're using ".ejs" extensions you dont need to do anything. - * - * Some template engines do not follow this convention, the - * [Consolidate.js](https://github.com/tj/consolidate.js) - * library was created to map all of node's popular template - * engines to follow this convention, thus allowing them to - * work seamlessly within Express. - * - * @param {String} ext - * @param {Function} fn - * @return {app} for chaining - * @public - */ +function genLsCache (instance) { + const formatter = instance[formattersSym].level + const { labels } = instance.levels + const cache = {} + for (const label in labels) { + const level = formatter(labels[label], Number(label)) + cache[label] = JSON.stringify(level).slice(0, -1) + } + instance[lsCacheSym] = cache + return instance +} -app.engine = function engine(ext, fn) { - if (typeof fn !== 'function') { - throw new Error('callback function required'); +function isStandardLevel (level, useOnlyCustomLevels) { + if (useOnlyCustomLevels) { + return false } - // get file extension - var extension = ext[0] !== '.' - ? '.' + ext - : ext; + switch (level) { + case 'fatal': + case 'error': + case 'warn': + case 'info': + case 'debug': + case 'trace': + return true + default: + return false + } +} - // store engine - this.engines[extension] = fn; +function setLevel (level) { + const { labels, values } = this.levels + if (typeof level === 'number') { + if (labels[level] === undefined) throw Error('unknown level value' + level) + level = labels[level] + } + if (values[level] === undefined) throw Error('unknown level ' + level) + const preLevelVal = this[levelValSym] + const levelVal = this[levelValSym] = values[level] + const useOnlyCustomLevelsVal = this[useOnlyCustomLevelsSym] + const hook = this[hooksSym].logMethod - return this; -}; + for (var key in values) { + if (levelVal > values[key]) { + this[key] = noop + continue + } + this[key] = isStandardLevel(key, useOnlyCustomLevelsVal) ? levelMethods[key](hook) : genLog(values[key], hook) + } -/** - * Proxy to `Router#param()` with one added api feature. The _name_ parameter - * can be an array of names. - * - * See the Router#param() docs for more details. - * - * @param {String|Array} name - * @param {Function} fn - * @return {app} for chaining - * @public - */ + this.emit( + 'level-change', + level, + levelVal, + labels[preLevelVal], + preLevelVal + ) +} -app.param = function param(name, fn) { - this.lazyrouter(); +function getLevel (level) { + const { levels, levelVal } = this + // protection against potential loss of Pino scope from serializers (edge case with circular refs - https://github.com/pinojs/pino/issues/833) + return (levels && levels.labels) ? levels.labels[levelVal] : '' +} - if (Array.isArray(name)) { - for (var i = 0; i < name.length; i++) { - this.param(name[i], fn); +function isLevelEnabled (logLevel) { + const { values } = this.levels + const logLevelVal = values[logLevel] + return logLevelVal !== undefined && (logLevelVal >= this[levelValSym]) +} + +function mappings (customLevels = null, useOnlyCustomLevels = false) { + const customNums = customLevels ? Object.keys(customLevels).reduce((o, k) => { + o[customLevels[k]] = k + return o + }, {}) : null + + const labels = Object.assign( + Object.create(Object.prototype, { Infinity: { value: 'silent' } }), + useOnlyCustomLevels ? null : nums, + customNums + ) + const values = Object.assign( + Object.create(Object.prototype, { silent: { value: Infinity } }), + useOnlyCustomLevels ? null : levels, + customLevels + ) + return { labels, values } +} + +function assertDefaultLevelFound (defaultLevel, customLevels, useOnlyCustomLevels) { + if (typeof defaultLevel === 'number') { + const values = [].concat( + Object.keys(customLevels || {}).map(key => customLevels[key]), + useOnlyCustomLevels ? [] : Object.keys(nums).map(level => +level), + Infinity + ) + if (!values.includes(defaultLevel)) { + throw Error(`default level:${defaultLevel} must be included in custom levels`) } + return + } - return this; + const labels = Object.assign( + Object.create(Object.prototype, { silent: { value: Infinity } }), + useOnlyCustomLevels ? null : levels, + customLevels + ) + if (!(defaultLevel in labels)) { + throw Error(`default level:${defaultLevel} must be included in custom levels`) } +} - this._router.param(name, fn); +function assertNoLevelCollisions (levels, customLevels) { + const { labels, values } = levels + for (const k in customLevels) { + if (k in values) { + throw Error('levels cannot be overridden') + } + if (customLevels[k] in labels) { + throw Error('pre-existing level values cannot be used for new levels') + } + } +} - return this; -}; +module.exports = { + initialLsCache, + genLsCache, + levelMethods, + getLevel, + setLevel, + isLevelEnabled, + mappings, + assertNoLevelCollisions, + assertDefaultLevelFound +} -/** - * Assign `setting` to `val`, or return `setting`'s value. - * - * app.set('foo', 'bar'); - * app.set('foo'); - * // => "bar" - * - * Mounted servers inherit their parent server's settings. - * - * @param {String} setting - * @param {*} [val] - * @return {Server} for chaining - * @public - */ - -app.set = function set(setting, val) { - if (arguments.length === 1) { - // app.get(setting) - return this.settings[setting]; - } - - debug('set "%s" to %o', setting, val); - - // set value - this.settings[setting] = val; - - // trigger matched settings - switch (setting) { - case 'etag': - this.set('etag fn', compileETag(val)); - break; - case 'query parser': - this.set('query parser fn', compileQueryParser(val)); - break; - case 'trust proxy': - this.set('trust proxy fn', compileTrust(val)); - - // trust proxy inherit back-compat - Object.defineProperty(this.settings, trustProxyDefaultSymbol, { - configurable: true, - value: false - }); - - break; - } - - return this; -}; - -/** - * Return the app's absolute pathname - * based on the parent(s) that have - * mounted it. - * - * For example if the application was - * mounted as "/admin", which itself - * was mounted as "/blog" then the - * return value would be "/blog/admin". - * - * @return {String} - * @private - */ - -app.path = function path() { - return this.parent - ? this.parent.path() + this.mountpath - : ''; -}; - -/** - * Check if `setting` is enabled (truthy). - * - * app.enabled('foo') - * // => false - * - * app.enable('foo') - * app.enabled('foo') - * // => true - * - * @param {String} setting - * @return {Boolean} - * @public - */ - -app.enabled = function enabled(setting) { - return Boolean(this.set(setting)); -}; -/** - * Check if `setting` is disabled. - * - * app.disabled('foo') - * // => true - * - * app.enable('foo') - * app.disabled('foo') - * // => false - * - * @param {String} setting - * @return {Boolean} - * @public - */ +/***/ }), +/* 137 */, +/* 138 */, +/* 139 */ +/***/ (function(module, __unusedexports, __webpack_require__) { -app.disabled = function disabled(setting) { - return !this.set(setting); -}; +// Unique ID creation requires a high quality random # generator. In node.js +// this is pretty straight-forward - we use the crypto API. -/** - * Enable `setting`. - * - * @param {String} setting - * @return {app} for chaining - * @public - */ +var crypto = __webpack_require__(417); -app.enable = function enable(setting) { - return this.set(setting, true); +module.exports = function nodeRNG() { + return crypto.randomBytes(16); }; -/** - * Disable `setting`. - * - * @param {String} setting - * @return {app} for chaining - * @public - */ - -app.disable = function disable(setting) { - return this.set(setting, false); -}; -/** - * Delegate `.VERB(...)` calls to `router.VERB(...)`. - */ +/***/ }), +/* 140 */, +/* 141 */, +/* 142 */ +/***/ (function(module, exports, __webpack_require__) { -methods.forEach(function(method){ - app[method] = function(path){ - if (method === 'get' && arguments.length === 1) { - // app.get(setting) - return this.set(path); - } +"use strict"; - this.lazyrouter(); - var route = this._router.route(path); - route[method].apply(route, slice.call(arguments, 1)); - return this; - }; +Object.defineProperty(exports, "__esModule", { + value: true }); +exports.default = void 0; -/** - * Special-cased "all" method, applying the given route `path`, - * middleware, and callback to _every_ HTTP method. - * - * @param {String} path - * @param {Function} ... - * @return {app} for chaining - * @public - */ - -app.all = function all(path) { - this.lazyrouter(); - - var route = this._router.route(path); - var args = slice.call(arguments, 1); - - for (var i = 0; i < methods.length; i++) { - route[methods[i]].apply(route, args); - } - - return this; -}; - -// del -> delete alias - -app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead'); - -/** - * Render the given view `name` name with `options` - * and a callback accepting an error and the - * rendered template string. - * - * Example: - * - * app.render('email', { name: 'Tobi' }, function(err, html){ - * // ... - * }) - * - * @param {String} name - * @param {Object|Function} options or fn - * @param {Function} callback - * @public - */ - -app.render = function render(name, options, callback) { - var cache = this.cache; - var done = callback; - var engines = this.engines; - var opts = options; - var renderOptions = {}; - var view; +var _rng = _interopRequireDefault(__webpack_require__(641)); - // support callback function as second arg - if (typeof options === 'function') { - done = options; - opts = {}; - } +var _bytesToUuid = _interopRequireDefault(__webpack_require__(246)); - // merge app.locals - merge(renderOptions, this.locals); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - // merge options._locals - if (opts._locals) { - merge(renderOptions, opts._locals); - } +// **`v1()` - Generate time-based UUID** +// +// Inspired by https://github.com/LiosK/UUID.js +// and http://docs.python.org/library/uuid.html +var _nodeId; - // merge options - merge(renderOptions, opts); +var _clockseq; // Previous uuid creation time - // set .cache unless explicitly provided - if (renderOptions.cache == null) { - renderOptions.cache = this.enabled('view cache'); - } - // primed cache - if (renderOptions.cache) { - view = cache[name]; - } +var _lastMSecs = 0; +var _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details - // view - if (!view) { - var View = this.get('view'); +function v1(options, buf, offset) { + var i = buf && offset || 0; + var b = buf || []; + options = options || {}; + var node = options.node || _nodeId; + var 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 - view = new View(name, { - defaultEngine: this.get('view engine'), - root: this.get('views'), - engines: engines - }); + if (node == null || clockseq == null) { + var seedBytes = options.random || (options.rng || _rng.default)(); - if (!view.path) { - var dirs = Array.isArray(view.root) && view.root.length > 1 - ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"' - : 'directory "' + view.root + '"' - var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs); - err.view = view; - return done(err); + 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]]; } - // prime the cache - if (renderOptions.cache) { - cache[name] = view; + if (clockseq == null) { + // Per 4.2.2, randomize (14 bit) clockseq + clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; } - } - - // render - tryRender(view, renderOptions, done); -}; - -/** - * Listen for connections. - * - * A node `http.Server` is returned, with this - * application (which is a `Function`) as its - * callback. If you wish to create both an HTTP - * and HTTPS server you may do so with the "http" - * and "https" modules as shown here: - * - * var http = require('http') - * , https = require('https') - * , express = require('express') - * , app = express(); - * - * http.createServer(app).listen(80); - * https.createServer({ ... }, app).listen(443); - * - * @return {http.Server} - * @public - */ - -app.listen = function listen() { - var server = http.createServer(this); - return server.listen.apply(server, arguments); -}; - -/** - * Log error using console.error. - * - * @param {Error} err - * @private - */ - -function logerror(err) { - /* istanbul ignore next */ - if (this.get('env') !== 'test') console.error(err.stack || err.toString()); -} - -/** - * Try rendering a view. - * @private - */ + } // 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. -function tryRender(view, options, callback) { - try { - view.render(options, callback); - } catch (err) { - callback(err); - } -} + var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime(); // Per 4.2.1.2, use count of uuid's generated during the current clock + // cycle to simulate higher resolution clock -/***/ }), -/* 129 */ -/***/ (function(module) { + var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) -module.exports = require("child_process"); + var dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression -/***/ }), -/* 130 */ -/***/ (function(module) { + 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 -/** - * This method returns a new empty array. - * - * @static - * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {Array} Returns the new empty array. - * @example - * - * var arrays = _.times(2, _.stubArray); - * - * console.log(arrays); - * // => [[], []] - * - * console.log(arrays[0] === arrays[1]); - * // => false - */ -function stubArray() { - return []; -} -module.exports = stubArray; + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { + nsecs = 0; + } // Per 4.2.1.2 Throw error if too many uuids are requested -/***/ }), -/* 131 */, -/* 132 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { + if (nsecs >= 10000) { + throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); + } -"use strict"; + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch + msecs += 12219292800000; // `time_low` -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = _default; -exports.URL = exports.DNS = void 0; + var 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` -var _bytesToUuid = _interopRequireDefault(__webpack_require__(759)); + var tmh = msecs / 0x100000000 * 10000 & 0xfffffff; + b[i++] = tmh >>> 8 & 0xff; + b[i++] = tmh & 0xff; // `time_high_and_version` -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + b[i++] = tmh >>> 24 & 0xf | 0x10; // include version -function uuidToBytes(uuid) { - // Note: We assume we're being passed a valid uuid string - var bytes = []; - uuid.replace(/[a-fA-F0-9]{2}/g, function (hex) { - bytes.push(parseInt(hex, 16)); - }); - return bytes; -} + b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) -function stringToBytes(str) { - str = unescape(encodeURIComponent(str)); // UTF8 escape + b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` - var bytes = new Array(str.length); + b[i++] = clockseq & 0xff; // `node` - for (var i = 0; i < str.length; i++) { - bytes[i] = str.charCodeAt(i); + for (var n = 0; n < 6; ++n) { + b[i + n] = node[n]; } - return bytes; + return buf ? buf : (0, _bytesToUuid.default)(b); } -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) { - var generateUUID = function (value, namespace, buf, offset) { - var off = buf && offset || 0; - if (typeof value == 'string') value = stringToBytes(value); - if (typeof namespace == 'string') namespace = uuidToBytes(namespace); - if (!Array.isArray(value)) throw TypeError('value must be an array of bytes'); - if (!Array.isArray(namespace) || namespace.length !== 16) throw TypeError('namespace must be uuid string or an Array of 16 byte values'); // Per 4.3 - - var bytes = hashfunc(namespace.concat(value)); - bytes[6] = bytes[6] & 0x0f | version; - bytes[8] = bytes[8] & 0x3f | 0x80; - - if (buf) { - for (var idx = 0; idx < 16; ++idx) { - buf[off + idx] = bytes[idx]; - } - } - - return buf || (0, _bytesToUuid.default)(bytes); - }; // Function#name is not settable on some platforms (#270) - - - try { - generateUUID.name = name; - } catch (err) {} // For CommonJS default export support - - - generateUUID.DNS = DNS; - generateUUID.URL = URL; - return generateUUID; -} +var _default = v1; +exports.default = _default; +module.exports = exports.default; /***/ }), -/* 133 */ +/* 143 */ /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; - -Object.defineProperty(exports, '__esModule', { value: true }); - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var Bottleneck = _interopDefault(__webpack_require__(532)); - -// @ts-ignore -async function errorRequest(octokit, state, error, options) { - if (!error.request || !error.request.request) { - // address https://github.com/octokit/plugin-retry.js/issues/8 - throw error; - } // retry all >= 400 && not doNotRetry - - - if (error.status >= 400 && !state.doNotRetry.includes(error.status)) { - const retries = options.request.retries != null ? options.request.retries : state.retries; - const retryAfter = Math.pow((options.request.retryCount || 0) + 1, 2); - throw octokit.retry.retryRequest(error, retries, retryAfter); - } // Maybe eventually there will be more cases here - - - throw error; -} - -// @ts-ignore - -async function wrapRequest(state, request, options) { - const limiter = new Bottleneck(); // @ts-ignore - - limiter.on("failed", function (error, info) { - const maxRetries = ~~error.request.request.retries; - const after = ~~error.request.request.retryAfter; - options.request.retryCount = info.retryCount + 1; - - if (maxRetries > info.retryCount) { - // Returning a number instructs the limiter to retry - // the request after that number of milliseconds have passed - return after * state.retryAfterBaseValue; +Object.defineProperty(exports, "__esModule", { value: true }); +const net_1 = __webpack_require__(631); +const utils_1 = __webpack_require__(200); +const tls_1 = __webpack_require__(16); +const StandaloneConnector_1 = __webpack_require__(219); +const SentinelIterator_1 = __webpack_require__(481); +exports.SentinelIterator = SentinelIterator_1.default; +const AbstractConnector_1 = __webpack_require__(94); +const redis_1 = __webpack_require__(837); +const debug = utils_1.Debug("SentinelConnector"); +class SentinelConnector extends AbstractConnector_1.default { + constructor(options) { + super(); + this.options = options; + if (!this.options.sentinels.length) { + throw new Error("Requires at least one sentinel to connect to."); + } + if (!this.options.name) { + throw new Error("Requires the name of master."); + } + this.sentinelIterator = new SentinelIterator_1.default(this.options.sentinels); } - }); - return limiter.schedule(request, options); -} - -const VERSION = "3.0.2"; -function retry(octokit, octokitOptions = {}) { - const state = Object.assign({ - enabled: true, - retryAfterBaseValue: 1000, - doNotRetry: [400, 401, 403, 404, 422], - retries: 3 - }, octokitOptions.retry); - octokit.retry = { - retryRequest: (error, retries, retryAfter) => { - error.request.request = Object.assign({}, error.request.request, { - retries: retries, - retryAfter: retryAfter - }); - return error; - } - }; - - if (!state.enabled) { - return; - } - - octokit.hook.error("request", errorRequest.bind(null, octokit, state)); - octokit.hook.wrap("request", wrapRequest.bind(null, state)); -} -retry.VERSION = VERSION; - -exports.VERSION = VERSION; -exports.retry = retry; -//# sourceMappingURL=index.js.map - - -/***/ }), -/* 134 */, -/* 135 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -var fs = __webpack_require__(747); -var path = __webpack_require__(622); -var caller = __webpack_require__(465); -var nodeModulesPaths = __webpack_require__(455); -var normalizeOptions = __webpack_require__(899); -var isCore = __webpack_require__(353); - -var defaultIsFile = function isFile(file, cb) { - fs.stat(file, function (err, stat) { - if (!err) { - return cb(null, stat.isFile() || stat.isFIFO()); - } - if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false); - return cb(err); - }); -}; - -var defaultIsDir = function isDirectory(dir, cb) { - fs.stat(dir, function (err, stat) { - if (!err) { - return cb(null, stat.isDirectory()); + check(info) { + const roleMatches = !info.role || this.options.role === info.role; + if (!roleMatches) { + debug("role invalid, expected %s, but got %s", this.options.role, info.role); + // Start from the next item. + // Note that `reset` will move the cursor to the previous element, + // so we advance two steps here. + this.sentinelIterator.next(); + this.sentinelIterator.next(); + this.sentinelIterator.reset(true); } - if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false); - return cb(err); - }); -}; - -var maybeUnwrapSymlink = function maybeUnwrapSymlink(x, opts, cb) { - if (opts && opts.preserveSymlinks === false) { - fs.realpath(x, function (realPathErr, realPath) { - if (realPathErr && realPathErr.code !== 'ENOENT') cb(realPathErr); - else cb(null, realPathErr ? x : realPath); - }); - } else { - cb(null, x); - } -}; - -var getPackageCandidates = function getPackageCandidates(x, start, opts) { - var dirs = nodeModulesPaths(start, opts, x); - for (var i = 0; i < dirs.length; i++) { - dirs[i] = path.join(dirs[i], x); - } - return dirs; -}; - -module.exports = function resolve(x, options, callback) { - var cb = callback; - var opts = options; - if (typeof options === 'function') { - cb = opts; - opts = {}; + return roleMatches; } - if (typeof x !== 'string') { - var err = new TypeError('Path must be a string.'); - return process.nextTick(function () { - cb(err); + connect(eventEmitter) { + this.connecting = true; + this.retryAttempts = 0; + let lastError; + const connectToNext = () => new Promise((resolve, reject) => { + const endpoint = this.sentinelIterator.next(); + if (endpoint.done) { + this.sentinelIterator.reset(false); + const retryDelay = typeof this.options.sentinelRetryStrategy === "function" + ? this.options.sentinelRetryStrategy(++this.retryAttempts) + : null; + let errorMsg = typeof retryDelay !== "number" + ? "All sentinels are unreachable and retry is disabled." + : `All sentinels are unreachable. Retrying from scratch after ${retryDelay}ms.`; + if (lastError) { + errorMsg += ` Last error: ${lastError.message}`; + } + debug(errorMsg); + const error = new Error(errorMsg); + if (typeof retryDelay === "number") { + setTimeout(() => { + resolve(connectToNext()); + }, retryDelay); + eventEmitter("error", error); + } + else { + reject(error); + } + return; + } + this.resolve(endpoint.value, (err, resolved) => { + if (!this.connecting) { + reject(new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG)); + return; + } + if (resolved) { + debug("resolved: %s:%s", resolved.host, resolved.port); + if (this.options.enableTLSForSentinelMode && this.options.tls) { + Object.assign(resolved, this.options.tls); + this.stream = tls_1.connect(resolved); + } + else { + this.stream = net_1.createConnection(resolved); + } + this.sentinelIterator.reset(true); + resolve(this.stream); + } + else { + const endpointAddress = endpoint.value.host + ":" + endpoint.value.port; + const errorMsg = err + ? "failed to connect to sentinel " + + endpointAddress + + " because " + + err.message + : "connected to sentinel " + + endpointAddress + + " successfully, but got an invalid reply: " + + resolved; + debug(errorMsg); + eventEmitter("sentinelError", new Error(errorMsg)); + if (err) { + lastError = err; + } + resolve(connectToNext()); + } + }); }); + return connectToNext(); } - - opts = normalizeOptions(x, opts); - - var isFile = opts.isFile || defaultIsFile; - var isDirectory = opts.isDirectory || defaultIsDir; - var readFile = opts.readFile || fs.readFile; - var packageIterator = opts.packageIterator; - - var extensions = opts.extensions || ['.js']; - var basedir = opts.basedir || path.dirname(caller()); - var parent = opts.filename || basedir; - - opts.paths = opts.paths || []; - - // ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory - var absoluteStart = path.resolve(basedir); - - maybeUnwrapSymlink( - absoluteStart, - opts, - function (err, realStart) { - if (err) cb(err); - else init(realStart); + updateSentinels(client, callback) { + if (!this.options.updateSentinels) { + return callback(null); } - ); - - var res; - function init(basedir) { - if ((/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/).test(x)) { - res = path.resolve(basedir, x); - if (x === '.' || x === '..' || x.slice(-1) === '/') res += '/'; - if ((/\/$/).test(x) && res === basedir) { - loadAsDirectory(res, opts.package, onfile); - } else loadAsFile(res, opts.package, onfile); - } else if (isCore(x)) { - return cb(null, x); - } else loadNodeModules(x, basedir, function (err, n, pkg) { - if (err) cb(err); - else if (n) { - return maybeUnwrapSymlink(n, opts, function (err, realN) { - if (err) { - cb(err); - } else { - cb(null, realN, pkg); + client.sentinel("sentinels", this.options.name, (err, result) => { + if (err) { + client.disconnect(); + return callback(err); + } + if (!Array.isArray(result)) { + return callback(null); + } + result + .map(utils_1.packObject) + .forEach((sentinel) => { + const flags = sentinel.flags ? sentinel.flags.split(",") : []; + if (flags.indexOf("disconnected") === -1 && + sentinel.ip && + sentinel.port) { + const endpoint = this.sentinelNatResolve(addressResponseToAddress(sentinel)); + if (this.sentinelIterator.add(endpoint)) { + debug("adding sentinel %s:%s", endpoint.host, endpoint.port); } - }); - } else { - var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'"); - moduleError.code = 'MODULE_NOT_FOUND'; - cb(moduleError); + } + }); + debug("Updated internal sentinels: %s", this.sentinelIterator); + callback(null); + }); + } + resolveMaster(client, callback) { + client.sentinel("get-master-addr-by-name", this.options.name, (err, result) => { + if (err) { + client.disconnect(); + return callback(err); } + this.updateSentinels(client, (err) => { + client.disconnect(); + if (err) { + return callback(err); + } + callback(null, this.sentinelNatResolve(Array.isArray(result) + ? { host: result[0], port: Number(result[1]) } + : null)); + }); }); } - - function onfile(err, m, pkg) { - if (err) cb(err); - else if (m) cb(null, m, pkg); - else loadAsDirectory(res, function (err, d, pkg) { - if (err) cb(err); - else if (d) { - maybeUnwrapSymlink(d, opts, function (err, realD) { - if (err) { - cb(err); - } else { - cb(null, realD, pkg); - } - }); - } else { - var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'"); - moduleError.code = 'MODULE_NOT_FOUND'; - cb(moduleError); + resolveSlave(client, callback) { + client.sentinel("slaves", this.options.name, (err, result) => { + client.disconnect(); + if (err) { + return callback(err); + } + if (!Array.isArray(result)) { + return callback(null, null); } + const availableSlaves = result + .map(utils_1.packObject) + .filter((slave) => slave.flags && !slave.flags.match(/(disconnected|s_down|o_down)/)); + callback(null, this.sentinelNatResolve(selectPreferredSentinel(availableSlaves, this.options.preferredSlaves))); }); } - - function loadAsFile(x, thePackage, callback) { - var loadAsFilePackage = thePackage; - var cb = callback; - if (typeof loadAsFilePackage === 'function') { - cb = loadAsFilePackage; - loadAsFilePackage = undefined; + sentinelNatResolve(item) { + if (!item || !this.options.natMap) + return item; + return this.options.natMap[`${item.host}:${item.port}`] || item; + } + resolve(endpoint, callback) { + const client = new redis_1.default({ + port: endpoint.port || 26379, + host: endpoint.host, + username: this.options.sentinelUsername || null, + password: this.options.sentinelPassword || null, + family: endpoint.family || + (StandaloneConnector_1.isIIpcConnectionOptions(this.options) + ? undefined + : this.options.family), + tls: this.options.sentinelTLS, + retryStrategy: null, + enableReadyCheck: false, + connectTimeout: this.options.connectTimeout, + dropBufferSupport: true, + }); + // ignore the errors since resolve* methods will handle them + client.on("error", noop); + if (this.options.role === "slave") { + this.resolveSlave(client, callback); } - - var exts = [''].concat(extensions); - load(exts, x, loadAsFilePackage); - - function load(exts, x, loadPackage) { - if (exts.length === 0) return cb(null, undefined, loadPackage); - var file = x + exts[0]; - - var pkg = loadPackage; - if (pkg) onpkg(null, pkg); - else loadpkg(path.dirname(file), onpkg); - - function onpkg(err, pkg_, dir) { - pkg = pkg_; - if (err) return cb(err); - if (dir && pkg && opts.pathFilter) { - var rfile = path.relative(dir, file); - var rel = rfile.slice(0, rfile.length - exts[0].length); - var r = opts.pathFilter(pkg, x, rel); - if (r) return load( - [''].concat(extensions.slice()), - path.resolve(dir, r), - pkg - ); + else { + this.resolveMaster(client, callback); + } + } +} +exports.default = SentinelConnector; +function selectPreferredSentinel(availableSlaves, preferredSlaves) { + if (availableSlaves.length === 0) { + return null; + } + let selectedSlave; + if (typeof preferredSlaves === "function") { + selectedSlave = preferredSlaves(availableSlaves); + } + else if (preferredSlaves !== null && typeof preferredSlaves === "object") { + const preferredSlavesArray = Array.isArray(preferredSlaves) + ? preferredSlaves + : [preferredSlaves]; + // sort by priority + preferredSlavesArray.sort((a, b) => { + // default the priority to 1 + if (!a.prio) { + a.prio = 1; + } + if (!b.prio) { + b.prio = 1; + } + // lowest priority first + if (a.prio < b.prio) { + return -1; + } + if (a.prio > b.prio) { + return 1; + } + return 0; + }); + // loop over preferred slaves and return the first match + for (let p = 0; p < preferredSlavesArray.length; p++) { + for (let a = 0; a < availableSlaves.length; a++) { + const slave = availableSlaves[a]; + if (slave.ip === preferredSlavesArray[p].ip) { + if (slave.port === preferredSlavesArray[p].port) { + selectedSlave = slave; + break; + } } - isFile(file, onex); } - function onex(err, ex) { - if (err) return cb(err); - if (ex) return cb(null, file, pkg); - load(exts.slice(1), x, pkg); + if (selectedSlave) { + break; } } } + // if none of the preferred slaves are available, a random available slave is returned + if (!selectedSlave) { + selectedSlave = utils_1.sample(availableSlaves); + } + return addressResponseToAddress(selectedSlave); +} +function addressResponseToAddress(input) { + return { host: input.ip, port: Number(input.port) }; +} +function noop() { } - function loadpkg(dir, cb) { - if (dir === '' || dir === '/') return cb(null); - if (process.platform === 'win32' && (/^\w:[/\\]*$/).test(dir)) { - return cb(null); - } - if ((/[/\\]node_modules[/\\]*$/).test(dir)) return cb(null); - - maybeUnwrapSymlink(dir, opts, function (unwrapErr, pkgdir) { - if (unwrapErr) return loadpkg(path.dirname(dir), cb); - var pkgfile = path.join(pkgdir, 'package.json'); - isFile(pkgfile, function (err, ex) { - // on err, ex is false - if (!ex) return loadpkg(path.dirname(dir), cb); - readFile(pkgfile, function (err, body) { - if (err) cb(err); - try { var pkg = JSON.parse(body); } catch (jsonErr) {} +/***/ }), +/* 144 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { - if (pkg && opts.packageFilter) { - pkg = opts.packageFilter(pkg, pkgfile); +Object.defineProperty(exports, "__esModule", { value: true }); +/* eslint-disable @typescript-eslint/explicit-function-return-type */ +/* eslint-disable @typescript-eslint/typedef */ +/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ +/* eslint-disable @typescript-eslint/no-explicit-any */ +var is_1 = __webpack_require__(613); +/** SyncPromise internal states */ +var States; +(function (States) { + /** Pending */ + States["PENDING"] = "PENDING"; + /** Resolved / OK */ + States["RESOLVED"] = "RESOLVED"; + /** Rejected / Error */ + States["REJECTED"] = "REJECTED"; +})(States || (States = {})); +/** + * Thenable class that behaves like a Promise and follows it's interface + * but is not async internally + */ +var SyncPromise = /** @class */ (function () { + function SyncPromise(executor) { + var _this = this; + this._state = States.PENDING; + this._handlers = []; + /** JSDoc */ + this._resolve = function (value) { + _this._setResult(States.RESOLVED, value); + }; + /** JSDoc */ + this._reject = function (reason) { + _this._setResult(States.REJECTED, reason); + }; + /** JSDoc */ + this._setResult = function (state, value) { + if (_this._state !== States.PENDING) { + return; + } + if (is_1.isThenable(value)) { + value.then(_this._resolve, _this._reject); + return; + } + _this._state = state; + _this._value = value; + _this._executeHandlers(); + }; + // TODO: FIXME + /** JSDoc */ + this._attachHandler = function (handler) { + _this._handlers = _this._handlers.concat(handler); + _this._executeHandlers(); + }; + /** JSDoc */ + this._executeHandlers = function () { + if (_this._state === States.PENDING) { + return; + } + var cachedHandlers = _this._handlers.slice(); + _this._handlers = []; + cachedHandlers.forEach(function (handler) { + if (handler.done) { + return; + } + if (_this._state === States.RESOLVED) { + if (handler.onfulfilled) { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + handler.onfulfilled(_this._value); } - cb(null, pkg, dir); - }); + } + if (_this._state === States.REJECTED) { + if (handler.onrejected) { + handler.onrejected(_this._value); + } + } + handler.done = true; }); - }); - } - - function loadAsDirectory(x, loadAsDirectoryPackage, callback) { - var cb = callback; - var fpkg = loadAsDirectoryPackage; - if (typeof fpkg === 'function') { - cb = fpkg; - fpkg = opts.package; + }; + try { + executor(this._resolve, this._reject); } - - maybeUnwrapSymlink(x, opts, function (unwrapErr, pkgdir) { - if (unwrapErr) return cb(unwrapErr); - var pkgfile = path.join(pkgdir, 'package.json'); - isFile(pkgfile, function (err, ex) { - if (err) return cb(err); - if (!ex) return loadAsFile(path.join(x, 'index'), fpkg, cb); - - readFile(pkgfile, function (err, body) { - if (err) return cb(err); - try { - var pkg = JSON.parse(body); - } catch (jsonErr) {} - - if (pkg && opts.packageFilter) { - pkg = opts.packageFilter(pkg, pkgfile); - } - - if (pkg && pkg.main) { - if (typeof pkg.main !== 'string') { - var mainError = new TypeError('package “' + pkg.name + '” `main` must be a string'); - mainError.code = 'INVALID_PACKAGE_MAIN'; - return cb(mainError); - } - if (pkg.main === '.' || pkg.main === './') { - pkg.main = 'index'; - } - loadAsFile(path.resolve(x, pkg.main), pkg, function (err, m, pkg) { - if (err) return cb(err); - if (m) return cb(null, m, pkg); - if (!pkg) return loadAsFile(path.join(x, 'index'), pkg, cb); - - var dir = path.resolve(x, pkg.main); - loadAsDirectory(dir, pkg, function (err, n, pkg) { - if (err) return cb(err); - if (n) return cb(null, n, pkg); - loadAsFile(path.join(x, 'index'), pkg, cb); - }); - }); + catch (e) { + this._reject(e); + } + } + /** JSDoc */ + SyncPromise.resolve = function (value) { + return new SyncPromise(function (resolve) { + resolve(value); + }); + }; + /** JSDoc */ + SyncPromise.reject = function (reason) { + return new SyncPromise(function (_, reject) { + reject(reason); + }); + }; + /** JSDoc */ + SyncPromise.all = function (collection) { + return new SyncPromise(function (resolve, reject) { + if (!Array.isArray(collection)) { + reject(new TypeError("Promise.all requires an array as input.")); + return; + } + if (collection.length === 0) { + resolve([]); + return; + } + var counter = collection.length; + var resolvedCollection = []; + collection.forEach(function (item, index) { + SyncPromise.resolve(item) + .then(function (value) { + resolvedCollection[index] = value; + counter -= 1; + if (counter !== 0) { return; } - - loadAsFile(path.join(x, '/index'), pkg, cb); - }); + resolve(resolvedCollection); + }) + .then(null, reject); }); }); - } - - function processDirs(cb, dirs) { - if (dirs.length === 0) return cb(null, undefined); - var dir = dirs[0]; - - isDirectory(path.dirname(dir), isdir); - - function isdir(err, isdir) { - if (err) return cb(err); - if (!isdir) return processDirs(cb, dirs.slice(1)); - loadAsFile(dir, opts.package, onfile); - } - - function onfile(err, m, pkg) { - if (err) return cb(err); - if (m) return cb(null, m, pkg); - loadAsDirectory(dir, opts.package, ondir); - } - - function ondir(err, n, pkg) { - if (err) return cb(err); - if (n) return cb(null, n, pkg); - processDirs(cb, dirs.slice(1)); - } - } - function loadNodeModules(x, start, cb) { - var thunk = function () { return getPackageCandidates(x, start, opts); }; - processDirs( - cb, - packageIterator ? packageIterator(x, start, thunk, opts) : thunk() - ); - } -}; - - -/***/ }), -/* 136 */ -/***/ (function(module) { - -(function() { - var base64map - = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/', - - crypt = { - // Bit-wise rotation left - rotl: function(n, b) { - return (n << b) | (n >>> (32 - b)); - }, - - // Bit-wise rotation right - rotr: function(n, b) { - return (n << (32 - b)) | (n >>> b); - }, - - // Swap big-endian to little-endian and vice versa - endian: function(n) { - // If number given, swap endian - if (n.constructor == Number) { - return crypt.rotl(n, 8) & 0x00FF00FF | crypt.rotl(n, 24) & 0xFF00FF00; - } - - // Else, assume array and swap all items - for (var i = 0; i < n.length; i++) - n[i] = crypt.endian(n[i]); - return n; - }, - - // Generate an array of any length of random bytes - randomBytes: function(n) { - for (var bytes = []; n > 0; n--) - bytes.push(Math.floor(Math.random() * 256)); - return bytes; - }, - - // Convert a byte array to big-endian 32-bit words - bytesToWords: function(bytes) { - for (var words = [], i = 0, b = 0; i < bytes.length; i++, b += 8) - words[b >>> 5] |= bytes[i] << (24 - b % 32); - return words; - }, - - // Convert big-endian 32-bit words to a byte array - wordsToBytes: function(words) { - for (var bytes = [], b = 0; b < words.length * 32; b += 8) - bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF); - return bytes; - }, - - // Convert a byte array to a hex string - bytesToHex: function(bytes) { - for (var hex = [], i = 0; i < bytes.length; i++) { - hex.push((bytes[i] >>> 4).toString(16)); - hex.push((bytes[i] & 0xF).toString(16)); - } - return hex.join(''); - }, - - // Convert a hex string to a byte array - hexToBytes: function(hex) { - for (var bytes = [], c = 0; c < hex.length; c += 2) - bytes.push(parseInt(hex.substr(c, 2), 16)); - return bytes; - }, - - // Convert a byte array to a base-64 string - bytesToBase64: function(bytes) { - for (var base64 = [], i = 0; i < bytes.length; i += 3) { - var triplet = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]; - for (var j = 0; j < 4; j++) - if (i * 8 + j * 6 <= bytes.length * 8) - base64.push(base64map.charAt((triplet >>> 6 * (3 - j)) & 0x3F)); - else - base64.push('='); - } - return base64.join(''); - }, - - // Convert a base-64 string to a byte array - base64ToBytes: function(base64) { - // Remove non-base-64 characters - base64 = base64.replace(/[^A-Z0-9+\/]/ig, ''); - - for (var bytes = [], i = 0, imod4 = 0; i < base64.length; - imod4 = ++i % 4) { - if (imod4 == 0) continue; - bytes.push(((base64map.indexOf(base64.charAt(i - 1)) - & (Math.pow(2, -2 * imod4 + 8) - 1)) << (imod4 * 2)) - | (base64map.indexOf(base64.charAt(i)) >>> (6 - imod4 * 2))); - } - return bytes; - } - }; - - module.exports = crypt; -})(); - - -/***/ }), -/* 137 */, -/* 138 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -module.exports = createEventHandler - -const on = __webpack_require__(275) -const receive = __webpack_require__(686) -const removeListener = __webpack_require__(890) - -function createEventHandler (options) { - const state = { - hooks: {} - } - - if (options && options.transform) { - state.transform = options.transform - } - - return { - on: on.bind(null, state), - removeListener: removeListener.bind(null, state), - receive: receive.bind(null, state) - } -} - - -/***/ }), -/* 139 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -// Unique ID creation requires a high quality random # generator. In node.js -// this is pretty straight-forward - we use the crypto API. - -var crypto = __webpack_require__(417); - -module.exports = function nodeRNG() { - return crypto.randomBytes(16); -}; - - -/***/ }), -/* 140 */, -/* 141 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -var Keys = __webpack_require__(786) -var hasKeys = __webpack_require__(170) - -module.exports = extend - -function extend() { - var target = {} - - for (var i = 0; i < arguments.length; i++) { - var source = arguments[i] - - if (!hasKeys(source)) { - continue - } - - var keys = Keys(source) - - for (var j = 0; j < keys.length; j++) { - var name = keys[j] - target[name] = source[name] - } - } - - return target -} - - -/***/ }), -/* 142 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; - - -var utils = __webpack_require__(411); - -var defaultOnConfig = { - console: true, - http: true -}; - -var defaultConfig = { - console: false, - http: false, - pg: false -}; - -function instrument(Raven, config) { - if (config === false) { - return; - } else if (config === true) { - config = defaultOnConfig; - } else { - config = utils.extend({}, defaultConfig, config); - } - - Raven.instrumentedOriginals = []; - Raven.instrumentedModules = []; - - var Module = __webpack_require__(282); - utils.fill( - Module, - '_load', - function(origLoad) { - return function(moduleId, parent, isMain) { - var origModule = origLoad.apply(this, arguments); - if (config[moduleId] && Raven.instrumentedModules.indexOf(moduleId) === -1) { - Raven.instrumentedModules.push(moduleId); - return require('./' + moduleId)(Raven, origModule, Raven.instrumentedOriginals); - } - return origModule; - }; - }, - Raven.instrumentedOriginals - ); - - // special case: since console is built-in and app-level code won't require() it, do that here - if (config.console) { - __webpack_require__(3); - } - - // observation: when the https module does its own require('http'), it *does not* hit our hooked require to instrument http on the fly - // but if we've previously instrumented http, https *does* get our already-instrumented version - // this is because raven's transports are required before this instrumentation takes place, which loads https (and http) - // so module cache will have uninstrumented http; proactively loading it here ensures instrumented version is in module cache - // alternatively we could refactor to load our transports later, but this is easier and doesn't have much drawback - if (config.http) { - __webpack_require__(605); - } -} - -function deinstrument(Raven) { - if (!Raven.instrumentedOriginals) return; - var original; - // eslint-disable-next-line no-cond-assign - while ((original = Raven.instrumentedOriginals.shift())) { - var obj = original[0]; - var name = original[1]; - var orig = original[2]; - obj[name] = orig; - } -} - -module.exports = { - instrument: instrument, - deinstrument: deinstrument -}; - - -/***/ }), -/* 143 */ -/***/ (function(module) { - -/** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ -var isArray = Array.isArray; - -module.exports = isArray; - - -/***/ }), -/* 144 */ -/***/ (function(module) { - -/** - * Helpers. - */ - -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var y = d * 365.25; - -/** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public - */ - -module.exports = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isNaN(val) === false) { - return options.long ? fmtLong(val) : fmtShort(val); - } - throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) - ); -}; - -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ - -function parse(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; - } -} - -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtShort(ms) { - if (ms >= d) { - return Math.round(ms / d) + 'd'; - } - if (ms >= h) { - return Math.round(ms / h) + 'h'; - } - if (ms >= m) { - return Math.round(ms / m) + 'm'; - } - if (ms >= s) { - return Math.round(ms / s) + 's'; - } - return ms + 'ms'; -} - -/** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtLong(ms) { - return plural(ms, d, 'day') || - plural(ms, h, 'hour') || - plural(ms, m, 'minute') || - plural(ms, s, 'second') || - ms + ' ms'; -} - -/** - * Pluralization helper. - */ - -function plural(ms, n, name) { - if (ms < n) { - return; - } - if (ms < n * 1.5) { - return Math.floor(ms / n) + ' ' + name; - } - return Math.ceil(ms / n) + ' ' + name + 's'; -} - + }; + /** JSDoc */ + SyncPromise.prototype.then = function (onfulfilled, onrejected) { + var _this = this; + return new SyncPromise(function (resolve, reject) { + _this._attachHandler({ + done: false, + onfulfilled: function (result) { + if (!onfulfilled) { + // TODO: ¯\_(ツ)_/¯ + // TODO: FIXME + resolve(result); + return; + } + try { + resolve(onfulfilled(result)); + return; + } + catch (e) { + reject(e); + return; + } + }, + onrejected: function (reason) { + if (!onrejected) { + reject(reason); + return; + } + try { + resolve(onrejected(reason)); + return; + } + catch (e) { + reject(e); + return; + } + }, + }); + }); + }; + /** JSDoc */ + SyncPromise.prototype.catch = function (onrejected) { + return this.then(function (val) { return val; }, onrejected); + }; + /** JSDoc */ + SyncPromise.prototype.finally = function (onfinally) { + var _this = this; + return new SyncPromise(function (resolve, reject) { + var val; + var isRejected; + return _this.then(function (value) { + isRejected = false; + val = value; + if (onfinally) { + onfinally(); + } + }, function (reason) { + isRejected = true; + val = reason; + if (onfinally) { + onfinally(); + } + }).then(function () { + if (isRejected) { + reject(val); + return; + } + resolve(val); + }); + }); + }; + /** JSDoc */ + SyncPromise.prototype.toString = function () { + return '[object SyncPromise]'; + }; + return SyncPromise; +}()); +exports.SyncPromise = SyncPromise; +//# sourceMappingURL=syncpromise.js.map /***/ }), /* 145 */ @@ -10306,7 +9911,7 @@ function plural(ms, n, name) { "use strict"; const pump = __webpack_require__(453); -const bufferStream = __webpack_require__(966); +const bufferStream = __webpack_require__(158); class MaxBufferError extends Error { constructor() { @@ -10360,40 +9965,71 @@ module.exports.MaxBufferError = MaxBufferError; /* 146 */ /***/ (function(module, __unusedexports, __webpack_require__) { -var isFunction = __webpack_require__(10), - isLength = __webpack_require__(198); +"use strict"; -/** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ -function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); -} -module.exports = isArrayLike; +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } + +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +var ERR_INVALID_ARG_TYPE = __webpack_require__(954).codes.ERR_INVALID_ARG_TYPE; + +function from(Readable, iterable, opts) { + var iterator; + + if (iterable && typeof iterable.next === 'function') { + iterator = iterable; + } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable); + + var readable = new Readable(_objectSpread({ + objectMode: true + }, opts)); // Reading boolean to protect against _read + // being called before last iteration completion. + + var reading = false; + + readable._read = function () { + if (!reading) { + reading = true; + next(); + } + }; + + function next() { + return _next2.apply(this, arguments); + } + + function _next2() { + _next2 = _asyncToGenerator(function* () { + try { + var _ref = yield iterator.next(), + value = _ref.value, + done = _ref.done; + + if (done) { + readable.push(null); + } else if (readable.push((yield value))) { + next(); + } else { + reading = false; + } + } catch (err) { + readable.destroy(err); + } + }); + return _next2.apply(this, arguments); + } + + return readable; +} +module.exports = from; /***/ }), /* 147 */, @@ -10470,368 +10106,1091 @@ SafeBuffer.allocUnsafeSlow = function (size) { /***/ }), /* 150 */ -/***/ (function(module) { - -module.exports = {"version":"2.19.5"}; - -/***/ }), -/* 151 */, -/* 152 */, -/* 153 */ /***/ (function(module, __unusedexports, __webpack_require__) { -module.exports = verify - -const crypto = __webpack_require__(417) -const Buffer = __webpack_require__(293).Buffer - -const sign = __webpack_require__(216) - -function verify (secret, eventPayload, signature) { - if (!secret || !eventPayload || !signature) { - throw new TypeError('secret, eventPayload & signature required') - } - - const signatureBuffer = Buffer.from(signature) - const verificationBuffer = Buffer.from(sign(secret, eventPayload)) - - if (signatureBuffer.length !== verificationBuffer.length) { - return false - } - - return timingSafeEqual(signatureBuffer, verificationBuffer) -} +/** + * Detect Electron renderer process, which is node, but we should + * treat as a browser. + */ -/* istanbul ignore next */ -function timingSafeEqual (signatureBuffer, verificationBuffer) { - return crypto.timingSafeEqual(signatureBuffer, verificationBuffer) +if (typeof process !== 'undefined' && process.type === 'renderer') { + module.exports = __webpack_require__(548); +} else { + module.exports = __webpack_require__(41); } /***/ }), -/* 154 */ -/***/ (function(__unusedmodule, exports) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.wrapLogger = void 0; -// Return a function that defaults to "info" level, and has properties for -// other levels: -// -// app.log("info") -// app.log.trace("verbose details"); -// -exports.wrapLogger = function (logger, baseLogger) { - var fn = Object.assign(logger.info.bind(logger), { - // Add level methods on the logger - debug: logger.debug.bind(logger), - error: logger.error.bind(logger), - fatal: logger.fatal.bind(logger), - info: logger.info.bind(logger), - trace: logger.trace.bind(logger), - warn: logger.warn.bind(logger), - // Expose `child` method for creating new wrapped loggers - child: function (attrs) { - // Bunyan doesn't allow you to overwrite name… - var name = attrs.name; - delete attrs.name; - var log = logger.child(attrs, true); - // …Sorry, bunyan, doing it anyway - if (name) { - log.fields.name = name; - } - return exports.wrapLogger(log, baseLogger || logger); - }, - // Expose target logger - target: baseLogger || logger - }); - return fn; -}; -//# sourceMappingURL=wrap-logger.js.map - -/***/ }), -/* 155 */, -/* 156 */ +/* 151 */ /***/ (function(module) { -"use strict"; - - -module.exports = function isArrayish(obj) { - if (!obj) { - return false; - } - - return obj instanceof Array || Array.isArray(obj) || - (obj.length >= 0 && obj.splice instanceof Function); -}; - +module.exports = require("dns"); /***/ }), -/* 157 */ -/***/ (function(module) { +/* 152 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { +Object.defineProperty(exports, "__esModule", { value: true }); +var tslib_1 = __webpack_require__(422); +var utils_1 = __webpack_require__(657); +var scope_1 = __webpack_require__(169); /** - * The base implementation of `_.unary` without support for storing metadata. + * API compatibility version of this hub. * - * @private - * @param {Function} func The function to cap arguments for. - * @returns {Function} Returns the new capped function. + * WARNING: This number should only be increased when the global interface + * changes and new methods are introduced. + * + * @hidden */ -function baseUnary(func) { - return function(value) { - return func(value); - }; -} - -module.exports = baseUnary; - - -/***/ }), -/* 158 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; - -const pTry = __webpack_require__(72); - -const pLimit = concurrency => { - if (!((Number.isInteger(concurrency) || concurrency === Infinity) && concurrency > 0)) { - return Promise.reject(new TypeError('Expected `concurrency` to be a number from 1 and up')); - } - - const queue = []; - let activeCount = 0; - - const next = () => { - activeCount--; - - if (queue.length > 0) { - queue.shift()(); - } - }; - - const run = (fn, resolve, ...args) => { - activeCount++; - - const result = pTry(fn, ...args); - - resolve(result); - - result.then(next, next); - }; - - const enqueue = (fn, resolve, ...args) => { - if (activeCount < concurrency) { - run(fn, resolve, ...args); - } else { - queue.push(run.bind(null, fn, resolve, ...args)); - } - }; - - const generator = (fn, ...args) => new Promise(resolve => enqueue(fn, resolve, ...args)); - Object.defineProperties(generator, { - activeCount: { - get: () => activeCount - }, - pendingCount: { - get: () => queue.length - } - }); - - return generator; -}; - -module.exports = pLimit; -module.exports.default = pLimit; - +exports.API_VERSION = 3; +/** + * Default maximum number of breadcrumbs added to an event. Can be overwritten + * with {@link Options.maxBreadcrumbs}. + */ +var DEFAULT_BREADCRUMBS = 100; +/** + * Absolute maximum number of breadcrumbs added to an event. The + * `maxBreadcrumbs` option cannot be higher than this value. + */ +var MAX_BREADCRUMBS = 100; +/** + * @inheritDoc + */ +var Hub = /** @class */ (function () { + /** + * Creates a new instance of the hub, will push one {@link Layer} into the + * internal stack on creation. + * + * @param client bound to the hub. + * @param scope bound to the hub. + * @param version number, higher number means higher priority. + */ + function Hub(client, scope, _version) { + if (scope === void 0) { scope = new scope_1.Scope(); } + if (_version === void 0) { _version = exports.API_VERSION; } + this._version = _version; + /** Is a {@link Layer}[] containing the client and scope */ + this._stack = []; + this._stack.push({ client: client, scope: scope }); + this.bindClient(client); + } + /** + * @inheritDoc + */ + Hub.prototype.isOlderThan = function (version) { + return this._version < version; + }; + /** + * @inheritDoc + */ + Hub.prototype.bindClient = function (client) { + var top = this.getStackTop(); + top.client = client; + if (client && client.setupIntegrations) { + client.setupIntegrations(); + } + }; + /** + * @inheritDoc + */ + Hub.prototype.pushScope = function () { + // We want to clone the content of prev scope + var stack = this.getStack(); + var parentScope = stack.length > 0 ? stack[stack.length - 1].scope : undefined; + var scope = scope_1.Scope.clone(parentScope); + this.getStack().push({ + client: this.getClient(), + scope: scope, + }); + return scope; + }; + /** + * @inheritDoc + */ + Hub.prototype.popScope = function () { + return this.getStack().pop() !== undefined; + }; + /** + * @inheritDoc + */ + Hub.prototype.withScope = function (callback) { + var scope = this.pushScope(); + try { + callback(scope); + } + finally { + this.popScope(); + } + }; + /** + * @inheritDoc + */ + Hub.prototype.getClient = function () { + return this.getStackTop().client; + }; + /** Returns the scope of the top stack. */ + Hub.prototype.getScope = function () { + return this.getStackTop().scope; + }; + /** Returns the scope stack for domains or the process. */ + Hub.prototype.getStack = function () { + return this._stack; + }; + /** Returns the topmost scope layer in the order domain > local > process. */ + Hub.prototype.getStackTop = function () { + return this._stack[this._stack.length - 1]; + }; + /** + * @inheritDoc + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types + Hub.prototype.captureException = function (exception, hint) { + var eventId = (this._lastEventId = utils_1.uuid4()); + var finalHint = hint; + // If there's no explicit hint provided, mimick the same thing that would happen + // in the minimal itself to create a consistent behavior. + // We don't do this in the client, as it's the lowest level API, and doing this, + // would prevent user from having full control over direct calls. + if (!hint) { + var syntheticException = void 0; + try { + throw new Error('Sentry syntheticException'); + } + catch (exception) { + syntheticException = exception; + } + finalHint = { + originalException: exception, + syntheticException: syntheticException, + }; + } + this._invokeClient('captureException', exception, tslib_1.__assign(tslib_1.__assign({}, finalHint), { event_id: eventId })); + return eventId; + }; + /** + * @inheritDoc + */ + Hub.prototype.captureMessage = function (message, level, hint) { + var eventId = (this._lastEventId = utils_1.uuid4()); + var finalHint = hint; + // If there's no explicit hint provided, mimick the same thing that would happen + // in the minimal itself to create a consistent behavior. + // We don't do this in the client, as it's the lowest level API, and doing this, + // would prevent user from having full control over direct calls. + if (!hint) { + var syntheticException = void 0; + try { + throw new Error(message); + } + catch (exception) { + syntheticException = exception; + } + finalHint = { + originalException: message, + syntheticException: syntheticException, + }; + } + this._invokeClient('captureMessage', message, level, tslib_1.__assign(tslib_1.__assign({}, finalHint), { event_id: eventId })); + return eventId; + }; + /** + * @inheritDoc + */ + Hub.prototype.captureEvent = function (event, hint) { + var eventId = (this._lastEventId = utils_1.uuid4()); + this._invokeClient('captureEvent', event, tslib_1.__assign(tslib_1.__assign({}, hint), { event_id: eventId })); + return eventId; + }; + /** + * @inheritDoc + */ + Hub.prototype.lastEventId = function () { + return this._lastEventId; + }; + /** + * @inheritDoc + */ + Hub.prototype.addBreadcrumb = function (breadcrumb, hint) { + var top = this.getStackTop(); + if (!top.scope || !top.client) { + return; + } + // eslint-disable-next-line @typescript-eslint/unbound-method + var _a = (top.client.getOptions && top.client.getOptions()) || {}, _b = _a.beforeBreadcrumb, beforeBreadcrumb = _b === void 0 ? null : _b, _c = _a.maxBreadcrumbs, maxBreadcrumbs = _c === void 0 ? DEFAULT_BREADCRUMBS : _c; + if (maxBreadcrumbs <= 0) { + return; + } + var timestamp = utils_1.timestampWithMs(); + var mergedBreadcrumb = tslib_1.__assign({ timestamp: timestamp }, breadcrumb); + var finalBreadcrumb = beforeBreadcrumb + ? utils_1.consoleSandbox(function () { return beforeBreadcrumb(mergedBreadcrumb, hint); }) + : mergedBreadcrumb; + if (finalBreadcrumb === null) { + return; + } + top.scope.addBreadcrumb(finalBreadcrumb, Math.min(maxBreadcrumbs, MAX_BREADCRUMBS)); + }; + /** + * @inheritDoc + */ + Hub.prototype.setUser = function (user) { + var top = this.getStackTop(); + if (!top.scope) { + return; + } + top.scope.setUser(user); + }; + /** + * @inheritDoc + */ + Hub.prototype.setTags = function (tags) { + var top = this.getStackTop(); + if (!top.scope) { + return; + } + top.scope.setTags(tags); + }; + /** + * @inheritDoc + */ + Hub.prototype.setExtras = function (extras) { + var top = this.getStackTop(); + if (!top.scope) { + return; + } + top.scope.setExtras(extras); + }; + /** + * @inheritDoc + */ + Hub.prototype.setTag = function (key, value) { + var top = this.getStackTop(); + if (!top.scope) { + return; + } + top.scope.setTag(key, value); + }; + /** + * @inheritDoc + */ + Hub.prototype.setExtra = function (key, extra) { + var top = this.getStackTop(); + if (!top.scope) { + return; + } + top.scope.setExtra(key, extra); + }; + /** + * @inheritDoc + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + Hub.prototype.setContext = function (name, context) { + var top = this.getStackTop(); + if (!top.scope) { + return; + } + top.scope.setContext(name, context); + }; + /** + * @inheritDoc + */ + Hub.prototype.configureScope = function (callback) { + var top = this.getStackTop(); + if (top.scope && top.client) { + callback(top.scope); + } + }; + /** + * @inheritDoc + */ + Hub.prototype.run = function (callback) { + var oldHub = makeMain(this); + try { + callback(this); + } + finally { + makeMain(oldHub); + } + }; + /** + * @inheritDoc + */ + Hub.prototype.getIntegration = function (integration) { + var client = this.getClient(); + if (!client) { + return null; + } + try { + return client.getIntegration(integration); + } + catch (_oO) { + utils_1.logger.warn("Cannot retrieve integration " + integration.id + " from the current Hub"); + return null; + } + }; + /** + * @inheritDoc + */ + Hub.prototype.startSpan = function (context) { + return this._callExtensionMethod('startSpan', context); + }; + /** + * @inheritDoc + */ + Hub.prototype.startTransaction = function (context, customSamplingContext) { + return this._callExtensionMethod('startTransaction', context, customSamplingContext); + }; + /** + * @inheritDoc + */ + Hub.prototype.traceHeaders = function () { + return this._callExtensionMethod('traceHeaders'); + }; + /** + * Internal helper function to call a method on the top client if it exists. + * + * @param method The method to call on the client. + * @param args Arguments to pass to the client function. + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + Hub.prototype._invokeClient = function (method) { + var _a; + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + var top = this.getStackTop(); + if (top && top.client && top.client[method]) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any + (_a = top.client)[method].apply(_a, tslib_1.__spread(args, [top.scope])); + } + }; + /** + * Calls global extension method and binding current instance to the function call + */ + // @ts-ignore Function lacks ending return statement and return type does not include 'undefined'. ts(2366) + // eslint-disable-next-line @typescript-eslint/no-explicit-any + Hub.prototype._callExtensionMethod = function (method) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + var carrier = getMainCarrier(); + var sentry = carrier.__SENTRY__; + if (sentry && sentry.extensions && typeof sentry.extensions[method] === 'function') { + return sentry.extensions[method].apply(this, args); + } + utils_1.logger.warn("Extension method " + method + " couldn't be found, doing nothing."); + }; + return Hub; +}()); +exports.Hub = Hub; +/** Returns the global shim registry. */ +function getMainCarrier() { + var carrier = utils_1.getGlobalObject(); + carrier.__SENTRY__ = carrier.__SENTRY__ || { + extensions: {}, + hub: undefined, + }; + return carrier; +} +exports.getMainCarrier = getMainCarrier; +/** + * Replaces the current main hub with the passed one on the global object + * + * @returns The old replaced hub + */ +function makeMain(hub) { + var registry = getMainCarrier(); + var oldHub = getHubFromCarrier(registry); + setHubOnCarrier(registry, hub); + return oldHub; +} +exports.makeMain = makeMain; +/** + * Returns the default hub instance. + * + * If a hub is already registered in the global carrier but this module + * contains a more recent version, it replaces the registered version. + * Otherwise, the currently registered hub will be returned. + */ +function getCurrentHub() { + // Get main carrier (global for every environment) + var registry = getMainCarrier(); + // If there's no hub, or its an old API, assign a new one + if (!hasHubOnCarrier(registry) || getHubFromCarrier(registry).isOlderThan(exports.API_VERSION)) { + setHubOnCarrier(registry, new Hub()); + } + // Prefer domains over global if they are there (applicable only to Node environment) + if (utils_1.isNodeEnv()) { + return getHubFromActiveDomain(registry); + } + // Return hub that lives on a global object + return getHubFromCarrier(registry); +} +exports.getCurrentHub = getCurrentHub; +/** + * Returns the active domain, if one exists + * + * @returns The domain, or undefined if there is no active domain + */ +function getActiveDomain() { + var sentry = getMainCarrier().__SENTRY__; + return sentry && sentry.extensions && sentry.extensions.domain && sentry.extensions.domain.active; +} +exports.getActiveDomain = getActiveDomain; +/** + * Try to read the hub from an active domain, and fallback to the registry if one doesn't exist + * @returns discovered hub + */ +function getHubFromActiveDomain(registry) { + try { + var activeDomain = getActiveDomain(); + // If there's no active domain, just return global hub + if (!activeDomain) { + return getHubFromCarrier(registry); + } + // If there's no hub on current domain, or it's an old API, assign a new one + if (!hasHubOnCarrier(activeDomain) || getHubFromCarrier(activeDomain).isOlderThan(exports.API_VERSION)) { + var registryHubTopStack = getHubFromCarrier(registry).getStackTop(); + setHubOnCarrier(activeDomain, new Hub(registryHubTopStack.client, scope_1.Scope.clone(registryHubTopStack.scope))); + } + // Return hub that lives on a domain + return getHubFromCarrier(activeDomain); + } + catch (_Oo) { + // Return hub that lives on a global object + return getHubFromCarrier(registry); + } +} +/** + * This will tell whether a carrier has a hub on it or not + * @param carrier object + */ +function hasHubOnCarrier(carrier) { + if (carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub) { + return true; + } + return false; +} +/** + * This will create a new {@link Hub} and add to the passed object on + * __SENTRY__.hub. + * @param carrier object + * @hidden + */ +function getHubFromCarrier(carrier) { + if (carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub) { + return carrier.__SENTRY__.hub; + } + carrier.__SENTRY__ = carrier.__SENTRY__ || {}; + carrier.__SENTRY__.hub = new Hub(); + return carrier.__SENTRY__.hub; +} +exports.getHubFromCarrier = getHubFromCarrier; +/** + * This will set passed {@link Hub} on the passed object's __SENTRY__.hub attribute + * @param carrier object + * @param hub Hub + */ +function setHubOnCarrier(carrier, hub) { + if (!carrier) { + return false; + } + carrier.__SENTRY__ = carrier.__SENTRY__ || {}; + carrier.__SENTRY__.hub = hub; + return true; +} +exports.setHubOnCarrier = setHubOnCarrier; +//# sourceMappingURL=hub.js.map /***/ }), -/* 159 */ -/***/ (function(module) { +/* 153 */ +/***/ (function(module, __unusedexports, __webpack_require__) { "use strict"; /*! - * escape-html - * Copyright(c) 2012-2013 TJ Holowaychuk - * Copyright(c) 2015 Andreas Lubbe - * Copyright(c) 2015 Tiancheng "Timothy" Gu + * type-is + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson * MIT Licensed */ /** - * Module variables. + * Module dependencies. * @private */ -var matchHtmlRegExp = /["'&<>]/; +var typer = __webpack_require__(126) +var mime = __webpack_require__(779) /** * Module exports. * @public */ -module.exports = escapeHtml; +module.exports = typeofrequest +module.exports.is = typeis +module.exports.hasBody = hasbody +module.exports.normalize = normalize +module.exports.match = mimeMatch /** - * Escape special characters in the given string of html. + * Compare a `value` content-type with `types`. + * Each `type` can be an extension like `html`, + * a special shortcut like `multipart` or `urlencoded`, + * or a mime type. * - * @param {string} string The string to escape for inserting into HTML - * @return {string} + * If no types match, `false` is returned. + * Otherwise, the first `type` that matches is returned. + * + * @param {String} value + * @param {Array} types * @public */ -function escapeHtml(string) { - var str = '' + string; - var match = matchHtmlRegExp.exec(str); +function typeis (value, types_) { + var i + var types = types_ - if (!match) { - return str; - } + // remove parameters and normalize + var val = tryNormalizeType(value) - var escape; - var html = ''; - var index = 0; - var lastIndex = 0; + // no type or invalid + if (!val) { + return false + } - for (index = match.index; index < str.length; index++) { - switch (str.charCodeAt(index)) { - case 34: // " - escape = '"'; - break; - case 38: // & - escape = '&'; - break; - case 39: // ' - escape = '''; - break; - case 60: // < - escape = '<'; - break; - case 62: // > - escape = '>'; - break; - default: - continue; + // support flattened arguments + if (types && !Array.isArray(types)) { + types = new Array(arguments.length - 1) + for (i = 0; i < types.length; i++) { + types[i] = arguments[i + 1] } + } - if (lastIndex !== index) { - html += str.substring(lastIndex, index); - } + // no types, return the content type + if (!types || !types.length) { + return val + } - lastIndex = index + 1; - html += escape; + var type + for (i = 0; i < types.length; i++) { + if (mimeMatch(normalize(type = types[i]), val)) { + return type[0] === '+' || type.indexOf('*') !== -1 + ? val + : type + } } - return lastIndex !== index - ? html + str.substring(lastIndex, index) - : html; + // no matches + return false } - -/***/ }), -/* 160 */ -/***/ (function(module) { - -/** Used as references for various `Number` constants. */ -var MAX_SAFE_INTEGER = 9007199254740991; - -/** Used to detect unsigned integer values. */ -var reIsUint = /^(?:0|[1-9]\d*)$/; - /** - * Checks if `value` is a valid array-like index. + * Check if a request has a request body. + * A request with a body __must__ either have `transfer-encoding` + * or `content-length` headers set. + * http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.3 * - * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + * @param {Object} request + * @return {Boolean} + * @public */ -function isIndex(value, length) { - var type = typeof value; - length = length == null ? MAX_SAFE_INTEGER : length; - return !!length && - (type == 'number' || - (type != 'symbol' && reIsUint.test(value))) && - (value > -1 && value % 1 == 0 && value < length); +function hasbody (req) { + return req.headers['transfer-encoding'] !== undefined || + !isNaN(req.headers['content-length']) } -module.exports = isIndex; +/** + * Check if the incoming request contains the "Content-Type" + * header field, and it contains any of the give mime `type`s. + * If there is no request body, `null` is returned. + * If there is no content type, `false` is returned. + * Otherwise, it returns the first `type` that matches. + * + * Examples: + * + * // With Content-Type: text/html; charset=utf-8 + * this.is('html'); // => 'html' + * this.is('text/html'); // => 'text/html' + * this.is('text/*', 'application/json'); // => 'text/html' + * + * // When Content-Type is application/json + * this.is('json', 'urlencoded'); // => 'json' + * this.is('application/json'); // => 'application/json' + * this.is('html', 'application/*'); // => 'application/json' + * + * this.is('html'); // => false + * + * @param {String|Array} types... + * @return {String|false|null} + * @public + */ +function typeofrequest (req, types_) { + var types = types_ -/***/ }), -/* 161 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + // no body + if (!hasbody(req)) { + return null + } -var root = __webpack_require__(333); + // support flattened arguments + if (arguments.length > 2) { + types = new Array(arguments.length - 1) + for (var i = 0; i < types.length; i++) { + types[i] = arguments[i + 1] + } + } -/** Built-in value references. */ -var Uint8Array = root.Uint8Array; + // request content type + var value = req.headers['content-type'] -module.exports = Uint8Array; + return typeis(value, types) +} +/** + * Normalize a mime type. + * If it's a shorthand, expand it to a valid mime type. + * + * In general, you probably want: + * + * var type = is(req, ['urlencoded', 'json', 'multipart']); + * + * Then use the appropriate body parsers. + * These three are the most common request body types + * and are thus ensured to work. + * + * @param {String} type + * @private + */ -/***/ }), -/* 162 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +function normalize (type) { + if (typeof type !== 'string') { + // invalid type + return false + } -"use strict"; + switch (type) { + case 'urlencoded': + return 'application/x-www-form-urlencoded' + case 'multipart': + return 'multipart/*' + } -var Buffer = __webpack_require__(215).Buffer; + if (type[0] === '+') { + // "+json" -> "*/*+json" expando + return '*/*' + type + } -// Export Node.js internal encodings. + return type.indexOf('/') === -1 + ? mime.lookup(type) + : type +} -module.exports = { - // Encodings - utf8: { type: "_internal", bomAware: true}, - cesu8: { type: "_internal", bomAware: true}, - unicode11utf8: "utf8", +/** + * Check if `expected` mime type + * matches `actual` mime type with + * wildcard and +suffix support. + * + * @param {String} expected + * @param {String} actual + * @return {Boolean} + * @private + */ - ucs2: { type: "_internal", bomAware: true}, - utf16le: "ucs2", +function mimeMatch (expected, actual) { + // invalid type + if (expected === false) { + return false + } - binary: { type: "_internal" }, - base64: { type: "_internal" }, - hex: { type: "_internal" }, + // split types + var actualParts = actual.split('/') + var expectedParts = expected.split('/') - // Codec. - _internal: InternalCodec, -}; + // invalid format + if (actualParts.length !== 2 || expectedParts.length !== 2) { + return false + } -//------------------------------------------------------------------------------ + // validate type + if (expectedParts[0] !== '*' && expectedParts[0] !== actualParts[0]) { + return false + } -function InternalCodec(codecOptions, iconv) { - this.enc = codecOptions.encodingName; - this.bomAware = codecOptions.bomAware; + // validate suffix wildcard + if (expectedParts[1].substr(0, 2) === '*+') { + return expectedParts[1].length <= actualParts[1].length + 1 && + expectedParts[1].substr(1) === actualParts[1].substr(1 - expectedParts[1].length) + } - if (this.enc === "base64") - this.encoder = InternalEncoderBase64; - else if (this.enc === "cesu8") { - this.enc = "utf8"; // Use utf8 for decoding. - this.encoder = InternalEncoderCesu8; + // validate subtype + if (expectedParts[1] !== '*' && expectedParts[1] !== actualParts[1]) { + return false + } - // Add decoder for versions of Node not supporting CESU-8 - if (Buffer.from('eda0bdedb2a9', 'hex').toString() !== '💩') { - this.decoder = InternalDecoderCesu8; - this.defaultCharUnicode = iconv.defaultCharUnicode; - } - } + return true } -InternalCodec.prototype.encoder = InternalEncoder; -InternalCodec.prototype.decoder = InternalDecoder; +/** + * Normalize a type and remove parameters. + * + * @param {string} value + * @return {string} + * @private + */ -//------------------------------------------------------------------------------ +function normalizeType (value) { + // parse the type + var type = typer.parse(value) -// We use node.js internal decoder. Its signature is the same as ours. -var StringDecoder = __webpack_require__(304).StringDecoder; + // remove the parameters + type.parameters = undefined -if (!StringDecoder.prototype.end) // Node v0.8 doesn't have this method. - StringDecoder.prototype.end = function() {}; + // reformat it + return typer.format(type) +} + +/** + * Try to normalize a type and remove parameters. + * + * @param {string} value + * @return {string} + * @private + */ + +function tryNormalizeType (value) { + if (!value) { + return null + } + + try { + return normalizeType(value) + } catch (err) { + return null + } +} + + +/***/ }), +/* 154 */, +/* 155 */, +/* 156 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; +// Ported from https://github.com/mafintosh/pump with +// permission from the author, Mathias Buus (@mafintosh). + + +var eos; + +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + callback.apply(void 0, arguments); + }; +} + +var _require$codes = __webpack_require__(954).codes, + ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; + +function noop(err) { + // Rethrow the error if it exists to avoid swallowing it + if (err) throw err; +} + +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +} + +function destroyer(stream, reading, writing, callback) { + callback = once(callback); + var closed = false; + stream.on('close', function () { + closed = true; + }); + if (eos === undefined) eos = __webpack_require__(352); + eos(stream, { + readable: reading, + writable: writing + }, function (err) { + if (err) return callback(err); + closed = true; + callback(); + }); + var destroyed = false; + return function (err) { + if (closed) return; + if (destroyed) return; + destroyed = true; // request.destroy just do .end - .abort is what we want + + if (isRequest(stream)) return stream.abort(); + if (typeof stream.destroy === 'function') return stream.destroy(); + callback(err || new ERR_STREAM_DESTROYED('pipe')); + }; +} + +function call(fn) { + fn(); +} + +function pipe(from, to) { + return from.pipe(to); +} + +function popCallback(streams) { + if (!streams.length) return noop; + if (typeof streams[streams.length - 1] !== 'function') return noop; + return streams.pop(); +} + +function pipeline() { + for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { + streams[_key] = arguments[_key]; + } + + var callback = popCallback(streams); + if (Array.isArray(streams[0])) streams = streams[0]; + + if (streams.length < 2) { + throw new ERR_MISSING_ARGS('streams'); + } + + var error; + var destroys = streams.map(function (stream, i) { + var reading = i < streams.length - 1; + var writing = i > 0; + return destroyer(stream, reading, writing, function (err) { + if (!error) error = err; + if (err) destroys.forEach(call); + if (reading) return; + destroys.forEach(call); + callback(error); + }); + }); + return streams.reduce(pipe); +} + +module.exports = pipeline; + +/***/ }), +/* 157 */ +/***/ (function(module, exports, __webpack_require__) { + +var Stream = __webpack_require__(413); +if (process.env.READABLE_STREAM === 'disable' && Stream) { + module.exports = Stream.Readable; + Object.assign(module.exports, Stream); + module.exports.Stream = Stream; +} else { + exports = module.exports = __webpack_require__(786); + exports.Stream = Stream || exports; + exports.Readable = exports; + exports.Writable = __webpack_require__(290); + exports.Duplex = __webpack_require__(238); + exports.Transform = __webpack_require__(339); + exports.PassThrough = __webpack_require__(56); + exports.finished = __webpack_require__(352); + exports.pipeline = __webpack_require__(156); +} + + +/***/ }), +/* 158 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + +const {PassThrough} = __webpack_require__(413); + +module.exports = options => { + options = Object.assign({}, options); + + const {array} = options; + let {encoding} = options; + const buffer = encoding === 'buffer'; + let objectMode = false; + + if (array) { + objectMode = !(encoding || buffer); + } else { + encoding = encoding || 'utf8'; + } + + if (buffer) { + encoding = null; + } + + let len = 0; + const ret = []; + const stream = new PassThrough({objectMode}); + + if (encoding) { + stream.setEncoding(encoding); + } + + stream.on('data', chunk => { + ret.push(chunk); + + if (objectMode) { + len = ret.length; + } else { + len += chunk.length; + } + }); + + stream.getBufferedValue = () => { + if (array) { + return ret; + } + + return buffer ? Buffer.concat(ret, len) : ret.join(''); + }; + + stream.getBufferedLength = () => len; + + return stream; +}; + + +/***/ }), +/* 159 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +Object.defineProperty(exports, "__esModule", { value: true }); +var browsertracing_1 = __webpack_require__(694); +exports.BrowserTracing = browsertracing_1.BrowserTracing; +//# sourceMappingURL=index.js.map + +/***/ }), +/* 160 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, '__esModule', { value: true }); + +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } + +var deprecation = __webpack_require__(692); +var once = _interopDefault(__webpack_require__(49)); + +const logOnce = once(deprecation => console.warn(deprecation)); +/** + * Error with extra properties to help with debugging + */ + +class RequestError extends Error { + constructor(message, statusCode, options) { + super(message); // Maintains proper stack trace (only available on V8) + + /* istanbul ignore next */ + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + + this.name = "HttpError"; + this.status = statusCode; + Object.defineProperty(this, "code", { + get() { + logOnce(new deprecation.Deprecation("[@octokit/request-error] `error.code` is deprecated, use `error.status`.")); + return statusCode; + } + + }); + this.headers = options.headers || {}; // redact request credentials without mutating original request options + + const requestCopy = Object.assign({}, options.request); + + if (options.request.headers.authorization) { + requestCopy.headers = Object.assign({}, options.request.headers, { + authorization: options.request.headers.authorization.replace(/ .*$/, " [REDACTED]") + }); + } + + requestCopy.url = requestCopy.url // client_id & client_secret can be passed as URL query parameters to increase rate limit + // see https://developer.github.com/v3/#increasing-the-unauthenticated-rate-limit-for-oauth-applications + .replace(/\bclient_secret=\w+/g, "client_secret=[REDACTED]") // OAuth tokens can be passed as URL query parameters, although it is not recommended + // see https://developer.github.com/v3/#oauth2-token-sent-in-a-header + .replace(/\baccess_token=\w+/g, "access_token=[REDACTED]"); + this.request = requestCopy; + } + +} + +exports.RequestError = RequestError; +//# sourceMappingURL=index.js.map + + +/***/ }), +/* 161 */, +/* 162 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + +var Buffer = __webpack_require__(215).Buffer; + +// Export Node.js internal encodings. + +module.exports = { + // Encodings + utf8: { type: "_internal", bomAware: true}, + cesu8: { type: "_internal", bomAware: true}, + unicode11utf8: "utf8", + + ucs2: { type: "_internal", bomAware: true}, + utf16le: "ucs2", + + binary: { type: "_internal" }, + base64: { type: "_internal" }, + hex: { type: "_internal" }, + + // Codec. + _internal: InternalCodec, +}; + +//------------------------------------------------------------------------------ + +function InternalCodec(codecOptions, iconv) { + this.enc = codecOptions.encodingName; + this.bomAware = codecOptions.bomAware; + + if (this.enc === "base64") + this.encoder = InternalEncoderBase64; + else if (this.enc === "cesu8") { + this.enc = "utf8"; // Use utf8 for decoding. + this.encoder = InternalEncoderCesu8; + + // Add decoder for versions of Node not supporting CESU-8 + if (Buffer.from('eda0bdedb2a9', 'hex').toString() !== '💩') { + this.decoder = InternalDecoderCesu8; + this.defaultCharUnicode = iconv.defaultCharUnicode; + } + } +} + +InternalCodec.prototype.encoder = InternalEncoder; +InternalCodec.prototype.decoder = InternalDecoder; + +//------------------------------------------------------------------------------ + +// We use node.js internal decoder. Its signature is the same as ours. +var StringDecoder = __webpack_require__(304).StringDecoder; + +if (!StringDecoder.prototype.end) // Node v0.8 doesn't have this method. + StringDecoder.prototype.end = function() {}; function InternalDecoder(options, codec) { @@ -10971,193 +11330,238 @@ InternalDecoderCesu8.prototype.end = function() { /***/ }), -/* 163 */ -/***/ (function(module, exports, __webpack_require__) { +/* 163 */, +/* 164 */ +/***/ (function(module, __unusedexports, __webpack_require__) { "use strict"; +/* eslint no-prototype-builtins: 0 */ +const os = __webpack_require__(87) +const stdSerializers = __webpack_require__(329) +const redaction = __webpack_require__(278) +const time = __webpack_require__(847) +const proto = __webpack_require__(392) +const symbols = __webpack_require__(230) +const { assertDefaultLevelFound, mappings, genLsCache } = __webpack_require__(136) +const { + createArgsNormalizer, + asChindings, + final, + stringify, + buildSafeSonicBoom, + buildFormatters, + noop +} = __webpack_require__(382) +const { version } = __webpack_require__(331) +const { + chindingsSym, + redactFmtSym, + serializersSym, + timeSym, + timeSliceIndexSym, + streamSym, + stringifySym, + stringifiersSym, + setLevelSym, + endSym, + formatOptsSym, + messageKeySym, + nestedKeySym, + mixinSym, + useOnlyCustomLevelsSym, + formattersSym, + hooksSym +} = symbols +const { epochTime, nullTime } = time +const { pid } = process +const hostname = os.hostname() +const defaultErrorSerializer = stdSerializers.err +const defaultOptions = { + level: 'info', + messageKey: 'msg', + nestedKey: null, + enabled: true, + prettyPrint: false, + base: { pid, hostname }, + serializers: Object.assign(Object.create(null), { + err: defaultErrorSerializer + }), + formatters: Object.assign(Object.create(null), { + bindings (bindings) { + return bindings + }, + level (label, number) { + return { level: number } + } + }), + hooks: { + logMethod: undefined + }, + timestamp: epochTime, + name: undefined, + redact: null, + customLevels: null, + levelKey: undefined, + useOnlyCustomLevels: false +} -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = void 0; - -var _rng = _interopRequireDefault(__webpack_require__(552)); - -var _bytesToUuid = _interopRequireDefault(__webpack_require__(759)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -// **`v1()` - Generate time-based UUID** -// -// Inspired by https://github.com/LiosK/UUID.js -// and http://docs.python.org/library/uuid.html -var _nodeId; - -var _clockseq; // Previous uuid creation time - - -var _lastMSecs = 0; -var _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details - -function v1(options, buf, offset) { - var i = buf && offset || 0; - var b = buf || []; - options = options || {}; - var node = options.node || _nodeId; - var 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 - - if (node == null || clockseq == null) { - var seedBytes = options.random || (options.rng || _rng.default)(); - - 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 (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. +const normalize = createArgsNormalizer(defaultOptions) +const serializers = Object.assign(Object.create(null), stdSerializers) - var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime(); // Per 4.2.1.2, use count of uuid's generated during the current clock - // cycle to simulate higher resolution clock +function pino (...args) { + const instance = {} + const { opts, stream } = normalize(instance, ...args) + const { + redact, + crlf, + serializers, + timestamp, + messageKey, + nestedKey, + base, + name, + level, + customLevels, + useLevelLabels, + changeLevelName, + levelKey, + mixin, + useOnlyCustomLevels, + formatters, + hooks + } = opts + + const allFormatters = buildFormatters( + formatters.level, + formatters.bindings, + formatters.log + ) - var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) + if (useLevelLabels && !(changeLevelName || levelKey)) { + process.emitWarning('useLevelLabels is deprecated, use the formatters.level option instead', 'Warning', 'PINODEP001') + allFormatters.level = labelsFormatter + } else if ((changeLevelName || levelKey) && !useLevelLabels) { + process.emitWarning('changeLevelName and levelKey are deprecated, use the formatters.level option instead', 'Warning', 'PINODEP002') + allFormatters.level = levelNameFormatter(changeLevelName || levelKey) + } else if ((changeLevelName || levelKey) && useLevelLabels) { + process.emitWarning('useLevelLabels is deprecated, use the formatters.level option instead', 'Warning', 'PINODEP001') + process.emitWarning('changeLevelName and levelKey are deprecated, use the formatters.level option instead', 'Warning', 'PINODEP002') + allFormatters.level = levelNameLabelFormatter(changeLevelName || levelKey) + } + + if (serializers[Symbol.for('pino.*')]) { + process.emitWarning('The pino.* serializer is deprecated, use the formatters.log options instead', 'Warning', 'PINODEP003') + allFormatters.log = serializers[Symbol.for('pino.*')] + } + + if (!allFormatters.bindings) { + allFormatters.bindings = defaultOptions.formatters.bindings + } + if (!allFormatters.level) { + allFormatters.level = defaultOptions.formatters.level + } + + const stringifiers = redact ? redaction(redact, stringify) : {} + const formatOpts = redact + ? { stringify: stringifiers[redactFmtSym] } + : { stringify } + const end = '}' + (crlf ? '\r\n' : '\n') + const coreChindings = asChindings.bind(null, { + [chindingsSym]: '', + [serializersSym]: serializers, + [stringifiersSym]: stringifiers, + [stringifySym]: stringify, + [formattersSym]: allFormatters + }) + const chindings = base === null ? '' : (name === undefined) + ? coreChindings(base) : coreChindings(Object.assign({}, base, { name })) + const time = (timestamp instanceof Function) + ? timestamp : (timestamp ? epochTime : nullTime) + const timeSliceIndex = time().indexOf(':') + 1 + + if (useOnlyCustomLevels && !customLevels) throw Error('customLevels is required if useOnlyCustomLevels is set true') + if (mixin && typeof mixin !== 'function') throw Error(`Unknown mixin type "${typeof mixin}" - expected "function"`) + + assertDefaultLevelFound(level, customLevels, useOnlyCustomLevels) + const levels = mappings(customLevels, useOnlyCustomLevels) + + Object.assign(instance, { + levels, + [useOnlyCustomLevelsSym]: useOnlyCustomLevels, + [streamSym]: stream, + [timeSym]: time, + [timeSliceIndexSym]: timeSliceIndex, + [stringifySym]: stringify, + [stringifiersSym]: stringifiers, + [endSym]: end, + [formatOptsSym]: formatOpts, + [messageKeySym]: messageKey, + [nestedKeySym]: nestedKey, + [serializersSym]: serializers, + [mixinSym]: mixin, + [chindingsSym]: chindings, + [formattersSym]: allFormatters, + [hooksSym]: hooks, + silent: noop + }) - var dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression + Object.setPrototypeOf(instance, proto()) - 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 + genLsCache(instance) + instance[setLevelSym](level) - if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { - nsecs = 0; - } // Per 4.2.1.2 Throw error if too many uuids are requested + return instance +} +function labelsFormatter (label, number) { + return { level: label } +} - if (nsecs >= 10000) { - throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); +function levelNameFormatter (name) { + return function (label, number) { + return { [name]: number } } +} - _lastMSecs = msecs; - _lastNSecs = nsecs; - _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch - - msecs += 12219292800000; // `time_low` - - var 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` - - var tmh = msecs / 0x100000000 * 10000 & 0xfffffff; - b[i++] = tmh >>> 8 & 0xff; - b[i++] = tmh & 0xff; // `time_high_and_version` - - b[i++] = tmh >>> 24 & 0xf | 0x10; // include version - - b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) - - b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` - - b[i++] = clockseq & 0xff; // `node` - - for (var n = 0; n < 6; ++n) { - b[i + n] = node[n]; +function levelNameLabelFormatter (name) { + return function (label, number) { + return { [name]: label } } - - return buf ? buf : (0, _bytesToUuid.default)(b); } -var _default = v1; -exports.default = _default; -module.exports = exports.default; - -/***/ }), -/* 164 */, -/* 165 */, -/* 166 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -var copyObject = __webpack_require__(765), - keysIn = __webpack_require__(331); - -/** - * The base implementation of `_.assignIn` without support for multiple sources - * or `customizer` functions. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @returns {Object} Returns `object`. - */ -function baseAssignIn(object, source) { - return object && copyObject(source, keysIn(source), object); +pino.extreme = (dest = process.stdout.fd) => { + process.emitWarning( + 'The pino.extreme() option is deprecated and will be removed in v7. Use pino.destination({ sync: false }) instead.', + { code: 'extreme_deprecation' } + ) + return buildSafeSonicBoom({ dest, minLength: 4096, sync: false }) +} +pino.destination = (dest = process.stdout.fd) => { + if (typeof dest === 'object') { + dest.dest = dest.dest || process.stdout.fd + return buildSafeSonicBoom(dest) + } else { + return buildSafeSonicBoom({ dest, minLength: 0, sync: true }) + } } -module.exports = baseAssignIn; - - -/***/ }), -/* 167 */ -/***/ (function(module) { - -var isObject = function isObject(value) { - return value instanceof Object && value.constructor === Object; -}; - -var parseWrapArguments = function parseWrapArguments(args) { - var length = args.length; - var work; - var options = {}; - var cb; - - /** - * As we can receive an unlimited number of keys - * we find the index of the first function which is - * the "work" handler to fetch the keys. - */ - for (var i = 0; i < length; i += 1) { - if (typeof args[i] === 'function') { - if (typeof args[i + 2] === 'function') { - cb = args.pop(); - } else if (typeof args[i + 1] === 'function') { - cb = args.pop(); - } - if (isObject(args[i + 1])) { - options = args.pop(); - } - work = args.pop(); - break; - } - } - - return { - keys: args, - work: work, - options: options, - cb: cb - }; -}; +pino.final = final +pino.levels = mappings() +pino.stdSerializers = serializers +pino.stdTimeFunctions = Object.assign({}, time) +pino.symbols = symbols +pino.version = version -module.exports = { - isObject: isObject, - parseWrapArguments: parseWrapArguments -}; +module.exports = pino /***/ }), +/* 165 */, +/* 166 */, +/* 167 */, /* 168 */ /***/ (function(module) { @@ -11207,3685 +11611,4390 @@ module.exports = opts => { /***/ }), /* 169 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; - - -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } - -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } - -var BottleneckError, DEFAULT_PRIORITY, Job, NUM_PRIORITIES, parser; -NUM_PRIORITIES = 10; -DEFAULT_PRIORITY = 5; -parser = __webpack_require__(714); -BottleneckError = __webpack_require__(212); -Job = class Job { - constructor(task, args, options, jobDefaults, rejectOnDrop, Events, _states, Promise) { - this.task = task; - this.args = args; - this.rejectOnDrop = rejectOnDrop; - this.Events = Events; - this._states = _states; - this.Promise = Promise; - this.options = parser.load(options, jobDefaults); - this.options.priority = this._sanitizePriority(this.options.priority); - - if (this.options.id === jobDefaults.id) { - this.options.id = `${this.options.id}-${this._randomIndex()}`; - } - - this.promise = new this.Promise((_resolve, _reject) => { - this._resolve = _resolve; - this._reject = _reject; - }); - this.retryCount = 0; - } - - _sanitizePriority(priority) { - var sProperty; - sProperty = ~~priority !== priority ? DEFAULT_PRIORITY : priority; - - if (sProperty < 0) { - return 0; - } else if (sProperty > NUM_PRIORITIES - 1) { - return NUM_PRIORITIES - 1; - } else { - return sProperty; - } - } - - _randomIndex() { - return Math.random().toString(36).slice(2); - } - - doDrop({ - error, - message = "This job has been dropped by Bottleneck" - } = {}) { - if (this._states.remove(this.options.id)) { - if (this.rejectOnDrop) { - this._reject(error != null ? error : new BottleneckError(message)); - } - - this.Events.trigger("dropped", { - args: this.args, - options: this.options, - task: this.task, - promise: this.promise - }); - return true; - } else { - return false; - } - } - - _assertStatus(expected) { - var status; - status = this._states.jobStatus(this.options.id); +/***/ (function(__unusedmodule, exports, __webpack_require__) { - if (!(status === expected || expected === "DONE" && status === null)) { - throw new BottleneckError(`Invalid job status ${status}, expected ${expected}. Please open an issue at https://github.com/SGrondin/bottleneck/issues`); +Object.defineProperty(exports, "__esModule", { value: true }); +var tslib_1 = __webpack_require__(422); +var utils_1 = __webpack_require__(657); +/** + * Holds additional event information. {@link Scope.applyToEvent} will be + * called by the client before an event will be sent. + */ +var Scope = /** @class */ (function () { + function Scope() { + /** Flag if notifiying is happening. */ + this._notifyingListeners = false; + /** Callback for client to receive scope changes. */ + this._scopeListeners = []; + /** Callback list that will be called after {@link applyToEvent}. */ + this._eventProcessors = []; + /** Array of breadcrumbs. */ + this._breadcrumbs = []; + /** User */ + this._user = {}; + /** Tags */ + this._tags = {}; + /** Extra */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._extra = {}; + /** Contexts */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._contexts = {}; } - } - - doReceive() { - this._states.start(this.options.id); - - return this.Events.trigger("received", { - args: this.args, - options: this.options - }); - } - - doQueue(reachedHWM, blocked) { - this._assertStatus("RECEIVED"); - - this._states.next(this.options.id); - - return this.Events.trigger("queued", { - args: this.args, - options: this.options, - reachedHWM, - blocked - }); - } - - doRun() { - if (this.retryCount === 0) { - this._assertStatus("QUEUED"); - - this._states.next(this.options.id); - } else { - this._assertStatus("EXECUTING"); - } - - return this.Events.trigger("scheduled", { - args: this.args, - options: this.options - }); - } - - doExecute(chained, clearGlobalState, run, free) { - var _this = this; + /** + * Inherit values from the parent scope. + * @param scope to clone. + */ + Scope.clone = function (scope) { + var newScope = new Scope(); + if (scope) { + newScope._breadcrumbs = tslib_1.__spread(scope._breadcrumbs); + newScope._tags = tslib_1.__assign({}, scope._tags); + newScope._extra = tslib_1.__assign({}, scope._extra); + newScope._contexts = tslib_1.__assign({}, scope._contexts); + newScope._user = scope._user; + newScope._level = scope._level; + newScope._span = scope._span; + newScope._transactionName = scope._transactionName; + newScope._fingerprint = scope._fingerprint; + newScope._eventProcessors = tslib_1.__spread(scope._eventProcessors); + } + return newScope; + }; + /** + * Add internal on change listener. Used for sub SDKs that need to store the scope. + * @hidden + */ + Scope.prototype.addScopeListener = function (callback) { + this._scopeListeners.push(callback); + }; + /** + * @inheritDoc + */ + Scope.prototype.addEventProcessor = function (callback) { + this._eventProcessors.push(callback); + return this; + }; + /** + * @inheritDoc + */ + Scope.prototype.setUser = function (user) { + this._user = user || {}; + this._notifyScopeListeners(); + return this; + }; + /** + * @inheritDoc + */ + Scope.prototype.setTags = function (tags) { + this._tags = tslib_1.__assign(tslib_1.__assign({}, this._tags), tags); + this._notifyScopeListeners(); + return this; + }; + /** + * @inheritDoc + */ + Scope.prototype.setTag = function (key, value) { + var _a; + this._tags = tslib_1.__assign(tslib_1.__assign({}, this._tags), (_a = {}, _a[key] = value, _a)); + this._notifyScopeListeners(); + return this; + }; + /** + * @inheritDoc + */ + Scope.prototype.setExtras = function (extras) { + this._extra = tslib_1.__assign(tslib_1.__assign({}, this._extra), extras); + this._notifyScopeListeners(); + return this; + }; + /** + * @inheritDoc + */ + Scope.prototype.setExtra = function (key, extra) { + var _a; + this._extra = tslib_1.__assign(tslib_1.__assign({}, this._extra), (_a = {}, _a[key] = extra, _a)); + this._notifyScopeListeners(); + return this; + }; + /** + * @inheritDoc + */ + Scope.prototype.setFingerprint = function (fingerprint) { + this._fingerprint = fingerprint; + this._notifyScopeListeners(); + return this; + }; + /** + * @inheritDoc + */ + Scope.prototype.setLevel = function (level) { + this._level = level; + this._notifyScopeListeners(); + return this; + }; + /** + * @inheritDoc + */ + Scope.prototype.setTransactionName = function (name) { + this._transactionName = name; + this._notifyScopeListeners(); + return this; + }; + /** + * Can be removed in major version. + * @deprecated in favor of {@link this.setTransactionName} + */ + Scope.prototype.setTransaction = function (name) { + return this.setTransactionName(name); + }; + /** + * @inheritDoc + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + Scope.prototype.setContext = function (key, context) { + var _a; + this._contexts = tslib_1.__assign(tslib_1.__assign({}, this._contexts), (_a = {}, _a[key] = context, _a)); + this._notifyScopeListeners(); + return this; + }; + /** + * @inheritDoc + */ + Scope.prototype.setSpan = function (span) { + this._span = span; + this._notifyScopeListeners(); + return this; + }; + /** + * @inheritDoc + */ + Scope.prototype.getSpan = function () { + return this._span; + }; + /** + * @inheritDoc + */ + Scope.prototype.getTransaction = function () { + var span = this.getSpan(); + if (span && span.spanRecorder && span.spanRecorder.spans[0]) { + return span.spanRecorder.spans[0]; + } + return undefined; + }; + /** + * @inheritDoc + */ + Scope.prototype.update = function (captureContext) { + if (!captureContext) { + return this; + } + if (typeof captureContext === 'function') { + var updatedScope = captureContext(this); + return updatedScope instanceof Scope ? updatedScope : this; + } + if (captureContext instanceof Scope) { + this._tags = tslib_1.__assign(tslib_1.__assign({}, this._tags), captureContext._tags); + this._extra = tslib_1.__assign(tslib_1.__assign({}, this._extra), captureContext._extra); + this._contexts = tslib_1.__assign(tslib_1.__assign({}, this._contexts), captureContext._contexts); + if (captureContext._user) { + this._user = captureContext._user; + } + if (captureContext._level) { + this._level = captureContext._level; + } + if (captureContext._fingerprint) { + this._fingerprint = captureContext._fingerprint; + } + } + else if (utils_1.isPlainObject(captureContext)) { + // eslint-disable-next-line no-param-reassign + captureContext = captureContext; + this._tags = tslib_1.__assign(tslib_1.__assign({}, this._tags), captureContext.tags); + this._extra = tslib_1.__assign(tslib_1.__assign({}, this._extra), captureContext.extra); + this._contexts = tslib_1.__assign(tslib_1.__assign({}, this._contexts), captureContext.contexts); + if (captureContext.user) { + this._user = captureContext.user; + } + if (captureContext.level) { + this._level = captureContext.level; + } + if (captureContext.fingerprint) { + this._fingerprint = captureContext.fingerprint; + } + } + return this; + }; + /** + * @inheritDoc + */ + Scope.prototype.clear = function () { + this._breadcrumbs = []; + this._tags = {}; + this._extra = {}; + this._user = {}; + this._contexts = {}; + this._level = undefined; + this._transactionName = undefined; + this._fingerprint = undefined; + this._span = undefined; + this._notifyScopeListeners(); + return this; + }; + /** + * @inheritDoc + */ + Scope.prototype.addBreadcrumb = function (breadcrumb, maxBreadcrumbs) { + var mergedBreadcrumb = tslib_1.__assign({ timestamp: utils_1.timestampWithMs() }, breadcrumb); + this._breadcrumbs = + maxBreadcrumbs !== undefined && maxBreadcrumbs >= 0 + ? tslib_1.__spread(this._breadcrumbs, [mergedBreadcrumb]).slice(-maxBreadcrumbs) + : tslib_1.__spread(this._breadcrumbs, [mergedBreadcrumb]); + this._notifyScopeListeners(); + return this; + }; + /** + * @inheritDoc + */ + Scope.prototype.clearBreadcrumbs = function () { + this._breadcrumbs = []; + this._notifyScopeListeners(); + return this; + }; + /** + * Applies the current context and fingerprint to the event. + * Note that breadcrumbs will be added by the client. + * Also if the event has already breadcrumbs on it, we do not merge them. + * @param event Event + * @param hint May contain additional informartion about the original exception. + * @hidden + */ + Scope.prototype.applyToEvent = function (event, hint) { + if (this._extra && Object.keys(this._extra).length) { + event.extra = tslib_1.__assign(tslib_1.__assign({}, this._extra), event.extra); + } + if (this._tags && Object.keys(this._tags).length) { + event.tags = tslib_1.__assign(tslib_1.__assign({}, this._tags), event.tags); + } + if (this._user && Object.keys(this._user).length) { + event.user = tslib_1.__assign(tslib_1.__assign({}, this._user), event.user); + } + if (this._contexts && Object.keys(this._contexts).length) { + event.contexts = tslib_1.__assign(tslib_1.__assign({}, this._contexts), event.contexts); + } + if (this._level) { + event.level = this._level; + } + if (this._transactionName) { + event.transaction = this._transactionName; + } + // We want to set the trace context for normal events only if there isn't already + // a trace context on the event. There is a product feature in place where we link + // errors with transaction and it relys on that. + if (this._span) { + event.contexts = tslib_1.__assign({ trace: this._span.getTraceContext() }, event.contexts); + } + this._applyFingerprint(event); + event.breadcrumbs = tslib_1.__spread((event.breadcrumbs || []), this._breadcrumbs); + event.breadcrumbs = event.breadcrumbs.length > 0 ? event.breadcrumbs : undefined; + return this._notifyEventProcessors(tslib_1.__spread(getGlobalEventProcessors(), this._eventProcessors), event, hint); + }; + /** + * This will be called after {@link applyToEvent} is finished. + */ + Scope.prototype._notifyEventProcessors = function (processors, event, hint, index) { + var _this = this; + if (index === void 0) { index = 0; } + return new utils_1.SyncPromise(function (resolve, reject) { + var processor = processors[index]; + if (event === null || typeof processor !== 'function') { + resolve(event); + } + else { + var result = processor(tslib_1.__assign({}, event), hint); + if (utils_1.isThenable(result)) { + result + .then(function (final) { return _this._notifyEventProcessors(processors, final, hint, index + 1).then(resolve); }) + .then(null, reject); + } + else { + _this._notifyEventProcessors(processors, result, hint, index + 1) + .then(resolve) + .then(null, reject); + } + } + }); + }; + /** + * This will be called on every set call. + */ + Scope.prototype._notifyScopeListeners = function () { + var _this = this; + if (!this._notifyingListeners) { + this._notifyingListeners = true; + setTimeout(function () { + _this._scopeListeners.forEach(function (callback) { + callback(_this); + }); + _this._notifyingListeners = false; + }); + } + }; + /** + * Applies fingerprint from the scope to the event if there's one, + * uses message if there's one instead or get rid of empty fingerprint + */ + Scope.prototype._applyFingerprint = function (event) { + // Make sure it's an array first and we actually have something in place + event.fingerprint = event.fingerprint + ? Array.isArray(event.fingerprint) + ? event.fingerprint + : [event.fingerprint] + : []; + // If we have something on the scope, then merge it with event + if (this._fingerprint) { + event.fingerprint = event.fingerprint.concat(this._fingerprint); + } + // If we have no data at all, remove empty array default + if (event.fingerprint && !event.fingerprint.length) { + delete event.fingerprint; + } + }; + return Scope; +}()); +exports.Scope = Scope; +/** + * Retruns the global event processors. + */ +function getGlobalEventProcessors() { + var global = utils_1.getGlobalObject(); + global.__SENTRY__ = global.__SENTRY__ || {}; + global.__SENTRY__.globalEventProcessors = global.__SENTRY__.globalEventProcessors || []; + return global.__SENTRY__.globalEventProcessors; +} +/** + * Add a EventProcessor to be kept globally. + * @param callback EventProcessor to add + */ +function addGlobalEventProcessor(callback) { + getGlobalEventProcessors().push(callback); +} +exports.addGlobalEventProcessor = addGlobalEventProcessor; +//# sourceMappingURL=scope.js.map - return _asyncToGenerator(function* () { - var error, eventInfo, passed; +/***/ }), +/* 170 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { - if (_this.retryCount === 0) { - _this._assertStatus("RUNNING"); +/*global exports*/ +var SignStream = __webpack_require__(495); +var VerifyStream = __webpack_require__(716); - _this._states.next(_this.options.id); - } else { - _this._assertStatus("EXECUTING"); - } +var ALGORITHMS = [ + 'HS256', 'HS384', 'HS512', + 'RS256', 'RS384', 'RS512', + 'PS256', 'PS384', 'PS512', + 'ES256', 'ES384', 'ES512' +]; - eventInfo = { - args: _this.args, - options: _this.options, - retryCount: _this.retryCount - }; +exports.ALGORITHMS = ALGORITHMS; +exports.sign = SignStream.sign; +exports.verify = VerifyStream.verify; +exports.decode = VerifyStream.decode; +exports.isValid = VerifyStream.isValid; +exports.createSign = function createSign(opts) { + return new SignStream(opts); +}; +exports.createVerify = function createVerify(opts) { + return new VerifyStream(opts); +}; - _this.Events.trigger("executing", eventInfo); - try { - passed = yield chained != null ? chained.schedule(_this.options, _this.task, ..._this.args) : _this.task(..._this.args); +/***/ }), +/* 171 */, +/* 172 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { - if (clearGlobalState()) { - _this.doDone(eventInfo); +Object.defineProperty(exports, "__esModule", { value: true }); +var tslib_1 = __webpack_require__(422); +var hub_1 = __webpack_require__(698); +var utils_1 = __webpack_require__(657); +exports.installedIntegrations = []; +/** Gets integration to install */ +function getIntegrationsToSetup(options) { + var defaultIntegrations = (options.defaultIntegrations && tslib_1.__spread(options.defaultIntegrations)) || []; + var userIntegrations = options.integrations; + var integrations = []; + if (Array.isArray(userIntegrations)) { + var userIntegrationsNames_1 = userIntegrations.map(function (i) { return i.name; }); + var pickedIntegrationsNames_1 = []; + // Leave only unique default integrations, that were not overridden with provided user integrations + defaultIntegrations.forEach(function (defaultIntegration) { + if (userIntegrationsNames_1.indexOf(defaultIntegration.name) === -1 && + pickedIntegrationsNames_1.indexOf(defaultIntegration.name) === -1) { + integrations.push(defaultIntegration); + pickedIntegrationsNames_1.push(defaultIntegration.name); + } + }); + // Don't add same user integration twice + userIntegrations.forEach(function (userIntegration) { + if (pickedIntegrationsNames_1.indexOf(userIntegration.name) === -1) { + integrations.push(userIntegration); + pickedIntegrationsNames_1.push(userIntegration.name); + } + }); + } + else if (typeof userIntegrations === 'function') { + integrations = userIntegrations(defaultIntegrations); + integrations = Array.isArray(integrations) ? integrations : [integrations]; + } + else { + integrations = tslib_1.__spread(defaultIntegrations); + } + // Make sure that if present, `Debug` integration will always run last + var integrationsNames = integrations.map(function (i) { return i.name; }); + var alwaysLastToRun = 'Debug'; + if (integrationsNames.indexOf(alwaysLastToRun) !== -1) { + integrations.push.apply(integrations, tslib_1.__spread(integrations.splice(integrationsNames.indexOf(alwaysLastToRun), 1))); + } + return integrations; +} +exports.getIntegrationsToSetup = getIntegrationsToSetup; +/** Setup given integration */ +function setupIntegration(integration) { + if (exports.installedIntegrations.indexOf(integration.name) !== -1) { + return; + } + integration.setupOnce(hub_1.addGlobalEventProcessor, hub_1.getCurrentHub); + exports.installedIntegrations.push(integration.name); + utils_1.logger.log("Integration installed: " + integration.name); +} +exports.setupIntegration = setupIntegration; +/** + * Given a list of integration instances this installs them all. When `withDefaults` is set to `true` then all default + * integrations are added unless they were already provided before. + * @param integrations array of integration instances + * @param withDefault should enable default integrations + */ +function setupIntegrations(options) { + var integrations = {}; + getIntegrationsToSetup(options).forEach(function (integration) { + integrations[integration.name] = integration; + setupIntegration(integration); + }); + return integrations; +} +exports.setupIntegrations = setupIntegrations; +//# sourceMappingURL=integration.js.map - yield free(_this.options, eventInfo); +/***/ }), +/* 173 */, +/* 174 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { - _this._assertStatus("DONE"); +"use strict"; - return _this._resolve(passed); +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ManifestCreation = void 0; +const fs_1 = __importDefault(__webpack_require__(747)); +const js_yaml_1 = __importDefault(__webpack_require__(186)); +const path_1 = __importDefault(__webpack_require__(622)); +const update_dotenv_1 = __importDefault(__webpack_require__(836)); +const probot_octokit_1 = __webpack_require__(388); +class ManifestCreation { + get pkg() { + let pkg; + try { + pkg = require(path_1.default.join(process.cwd(), "package.json")); } - } catch (error1) { - error = error1; - return _this._onFailure(error, eventInfo, clearGlobalState, run, free); - } - })(); - } - - doExpire(clearGlobalState, run, free) { - var error, eventInfo; - - if (this._states.jobStatus(this.options.id === "RUNNING")) { - this._states.next(this.options.id); + catch (e) { + pkg = {}; + } + return pkg; } + async createWebhookChannel() { + try { + // tslint:disable:no-var-requires + const SmeeClient = __webpack_require__(902); + await this.updateEnv({ + WEBHOOK_PROXY_URL: await SmeeClient.createChannel(), + }); + } + catch (error) { + // Smee is not available, so we'll just move on + // tslint:disable:no-console + console.warn("Unable to connect to smee.io, try restarting your server."); + } + } + getManifest(pkg, baseUrl) { + let manifest = {}; + try { + const file = fs_1.default.readFileSync(path_1.default.join(process.cwd(), "app.yml"), "utf8"); + manifest = js_yaml_1.default.safeLoad(file); + } + catch (error) { + // App config does not exist, which is ok. + if (error.code !== "ENOENT") { + throw error; + } + } + const generatedManifest = JSON.stringify(Object.assign({ + description: manifest.description || pkg.description, + hook_attributes: { + url: process.env.WEBHOOK_PROXY_URL || `${baseUrl}/`, + }, + name: process.env.PROJECT_DOMAIN || manifest.name || pkg.name, + public: manifest.public || true, + redirect_url: `${baseUrl}/probot/setup`, + // TODO: add setup url + // setup_url:`${baseUrl}/probot/success`, + url: manifest.url || pkg.homepage || pkg.repository, + version: "v1", + }, manifest)); + return generatedManifest; + } + async createAppFromCode(code) { + const github = new probot_octokit_1.ProbotOctokit(); + const options = { + code, + mediaType: { + previews: ["fury"], + }, + ...(process.env.GHE_HOST && { + baseUrl: `${process.env.GHE_PROTOCOL || "https"}://${process.env.GHE_HOST}/api/v3`, + }), + }; + const response = await github.request("POST /app-manifests/:code/conversions", options); + const { id, webhook_secret, pem } = response.data; + await this.updateEnv({ + APP_ID: id.toString(), + PRIVATE_KEY: `"${pem}"`, + WEBHOOK_SECRET: webhook_secret, + }); + return response.data.html_url; + } + async updateEnv(env) { + // Needs to be public due to tests + return update_dotenv_1.default(env); + } + get createAppUrl() { + const githubHost = process.env.GHE_HOST || `github.com`; + return `${process.env.GHE_PROTOCOL || "https"}://${githubHost}/settings/apps/new`; + } +} +exports.ManifestCreation = ManifestCreation; +//# sourceMappingURL=manifest-creation.js.map - this._assertStatus("EXECUTING"); +/***/ }), +/* 175 */, +/* 176 */, +/* 177 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { - eventInfo = { - args: this.args, - options: this.options, - retryCount: this.retryCount - }; - error = new BottleneckError(`This job timed out after ${this.options.expiration} ms.`); - return this._onFailure(error, eventInfo, clearGlobalState, run, free); - } +Object.defineProperty(exports, "__esModule", { value: true }); +var base_1 = __webpack_require__(916); +exports.BaseTransport = base_1.BaseTransport; +var http_1 = __webpack_require__(799); +exports.HTTPTransport = http_1.HTTPTransport; +var https_1 = __webpack_require__(775); +exports.HTTPSTransport = https_1.HTTPSTransport; +//# sourceMappingURL=index.js.map - _onFailure(error, eventInfo, clearGlobalState, run, free) { - var _this2 = this; +/***/ }), +/* 178 */, +/* 179 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { - return _asyncToGenerator(function* () { - var retry, retryAfter; +"use strict"; - if (clearGlobalState()) { - retry = yield _this2.Events.trigger("failed", error, eventInfo); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.webhookTransform = void 0; +const get_authenticated_octokit_for_event_1 = __webpack_require__(538); +const context_1 = __webpack_require__(596); +/** + * Probot's transform option, which extends the `event` object that is passed + * to webhook event handlers by `@octokit/webhooks` + * @see https://github.com/octokit/webhooks.js/#constructor + */ +async function webhookTransform(state, event) { + const log = state.log.child({ name: "event", id: event.id }); + const github = await get_authenticated_octokit_for_event_1.getAuthenticatedOctokitForEvent(state, event); + return new context_1.Context(event, github, log); +} +exports.webhookTransform = webhookTransform; +//# sourceMappingURL=octokit-webhooks-transform.js.map - if (retry != null) { - retryAfter = ~~retry; +/***/ }), +/* 180 */, +/* 181 */ +/***/ (function(module) { - _this2.Events.trigger("retry", `Retrying ${_this2.options.id} after ${retryAfter} ms`, eventInfo); +"use strict"; - _this2.retryCount++; - return run(retryAfter); - } else { - _this2.doDone(eventInfo); - yield free(_this2.options, eventInfo); +/* global SharedArrayBuffer, Atomics */ - _this2._assertStatus("DONE"); +if (typeof SharedArrayBuffer !== 'undefined' && typeof Atomics !== 'undefined') { + const nil = new Int32Array(new SharedArrayBuffer(4)) - return _this2._reject(error); - } + function sleep (ms) { + // also filters out NaN, non-number types, including empty strings, but allows bigints + const valid = ms > 0 && ms < Infinity + if (valid === false) { + if (typeof ms !== 'number' && typeof ms !== 'bigint') { + throw TypeError('sleep: ms must be a number') } - })(); + throw RangeError('sleep: ms must be a number that is greater than 0 but less than Infinity') + } + + Atomics.wait(nil, 0, 0, Number(ms)) } + module.exports = sleep +} else { - doDone(eventInfo) { - this._assertStatus("EXECUTING"); + function sleep (ms) { + // also filters out NaN, non-number types, including empty strings, but allows bigints + const valid = ms > 0 && ms < Infinity + if (valid === false) { + if (typeof ms !== 'number' && typeof ms !== 'bigint') { + throw TypeError('sleep: ms must be a number') + } + throw RangeError('sleep: ms must be a number that is greater than 0 but less than Infinity') + } + const target = Date.now() + Number(ms) + while (target > Date.now()){} + } - this._states.next(this.options.id); + module.exports = sleep - return this.Events.trigger("done", eventInfo); - } +} -}; -module.exports = Job; /***/ }), -/* 170 */ +/* 182 */, +/* 183 */, +/* 184 */ /***/ (function(module) { -module.exports = hasKeys - -function hasKeys(source) { - return source !== null && - (typeof source === "object" || - typeof source === "function") -} - +module.exports = require("vm"); /***/ }), -/* 171 */, -/* 172 */, -/* 173 */, -/* 174 */, -/* 175 */, -/* 176 */, -/* 177 */, -/* 178 */, -/* 179 */, -/* 180 */ +/* 185 */, +/* 186 */ /***/ (function(module, __unusedexports, __webpack_require__) { "use strict"; -var common = __webpack_require__(740); +var yaml = __webpack_require__(777); -function Mark(name, buffer, position, line, column) { - this.name = name; - this.buffer = buffer; - this.position = position; - this.line = line; - this.column = column; -} +module.exports = yaml; -Mark.prototype.getSnippet = function getSnippet(indent, maxLength) { - var head, start, tail, end, snippet; +/***/ }), +/* 187 */, +/* 188 */, +/* 189 */, +/* 190 */, +/* 191 */ +/***/ (function(module) { - if (!this.buffer) return null; +module.exports = require("querystring"); - indent = indent || 4; - maxLength = maxLength || 75; +/***/ }), +/* 192 */ +/***/ (function(module) { - head = ''; - start = this.position; +"use strict"; - while (start > 0 && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(start - 1)) === -1) { - start -= 1; - if (this.position - start > (maxLength / 2 - 1)) { - head = ' ... '; - start += 5; - break; - } - } - tail = ''; - end = this.position; +function getParamSize(keySize) { + var result = ((keySize / 8) | 0) + (keySize % 8 === 0 ? 0 : 1); + return result; +} - while (end < this.buffer.length && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(end)) === -1) { - end += 1; - if (end - this.position > (maxLength / 2 - 1)) { - tail = ' ... '; - end -= 5; - break; - } - } +var paramBytesForAlg = { + ES256: getParamSize(256), + ES384: getParamSize(384), + ES512: getParamSize(521) +}; - snippet = this.buffer.slice(start, end); +function getParamBytesForAlg(alg) { + var paramBytes = paramBytesForAlg[alg]; + if (paramBytes) { + return paramBytes; + } - return common.repeat(' ', indent) + head + snippet + tail + '\n' + - common.repeat(' ', indent + this.position - start + head.length) + '^'; -}; + throw new Error('Unknown algorithm "' + alg + '"'); +} +module.exports = getParamBytesForAlg; -Mark.prototype.toString = function toString(compact) { - var snippet, where = ''; - if (this.name) { - where += 'in "' + this.name + '" '; - } +/***/ }), +/* 193 */, +/* 194 */, +/* 195 */, +/* 196 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { - where += 'at line ' + (this.line + 1) + ', column ' + (this.column + 1); +Object.defineProperty(exports, "__esModule", { value: true }); +var minimal_1 = __webpack_require__(923); +exports.addBreadcrumb = minimal_1.addBreadcrumb; +exports.captureException = minimal_1.captureException; +exports.captureEvent = minimal_1.captureEvent; +exports.captureMessage = minimal_1.captureMessage; +exports.configureScope = minimal_1.configureScope; +exports.startTransaction = minimal_1.startTransaction; +exports.setContext = minimal_1.setContext; +exports.setExtra = minimal_1.setExtra; +exports.setExtras = minimal_1.setExtras; +exports.setTag = minimal_1.setTag; +exports.setTags = minimal_1.setTags; +exports.setUser = minimal_1.setUser; +exports.withScope = minimal_1.withScope; +var hub_1 = __webpack_require__(698); +exports.addGlobalEventProcessor = hub_1.addGlobalEventProcessor; +exports.getCurrentHub = hub_1.getCurrentHub; +exports.getHubFromCarrier = hub_1.getHubFromCarrier; +exports.Hub = hub_1.Hub; +exports.makeMain = hub_1.makeMain; +exports.Scope = hub_1.Scope; +var api_1 = __webpack_require__(318); +exports.API = api_1.API; +var baseclient_1 = __webpack_require__(533); +exports.BaseClient = baseclient_1.BaseClient; +var basebackend_1 = __webpack_require__(409); +exports.BaseBackend = basebackend_1.BaseBackend; +var request_1 = __webpack_require__(772); +exports.eventToSentryRequest = request_1.eventToSentryRequest; +var sdk_1 = __webpack_require__(651); +exports.initAndBind = sdk_1.initAndBind; +var noop_1 = __webpack_require__(594); +exports.NoopTransport = noop_1.NoopTransport; +var Integrations = __webpack_require__(505); +exports.Integrations = Integrations; +//# sourceMappingURL=index.js.map - if (!compact) { - snippet = this.getSnippet(); +/***/ }), +/* 197 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - if (snippet) { - where += ':\n' + snippet; - } - } +module.exports = isexe +isexe.sync = sync - return where; -}; +var fs = __webpack_require__(747) + +function isexe (path, options, cb) { + fs.stat(path, function (er, stat) { + cb(er, er ? false : checkStat(stat, options)) + }) +} +function sync (path, options) { + return checkStat(fs.statSync(path), options) +} -module.exports = Mark; +function checkStat (stat, options) { + return stat.isFile() && checkMode(stat, options) +} + +function checkMode (stat, options) { + var mod = stat.mode + var uid = stat.uid + var gid = stat.gid + + var myUid = options.uid !== undefined ? + options.uid : process.getuid && process.getuid() + var myGid = options.gid !== undefined ? + options.gid : process.getgid && process.getgid() + + var u = parseInt('100', 8) + var g = parseInt('010', 8) + var o = parseInt('001', 8) + var ug = u | g + + var ret = (mod & o) || + (mod & g) && gid === myGid || + (mod & u) && uid === myUid || + (mod & ug) && myUid === 0 + + return ret +} /***/ }), -/* 181 */ +/* 198 */ /***/ (function(module, __unusedexports, __webpack_require__) { "use strict"; +const ansiStyles = __webpack_require__(663); +const {stdout: stdoutColor, stderr: stderrColor} = __webpack_require__(247); +const { + stringReplaceAll, + stringEncaseCRLFWithFirstIndex +} = __webpack_require__(529); + +const {isArray} = Array; + +// `supportsColor.level` → `ansiStyles.color[name]` mapping +const levelMapping = [ + 'ansi', + 'ansi', + 'ansi256', + 'ansi16m' +]; -var Type = __webpack_require__(945); +const styles = Object.create(null); -var _hasOwnProperty = Object.prototype.hasOwnProperty; -var _toString = Object.prototype.toString; +const applyOptions = (object, options = {}) => { + if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) { + throw new Error('The `level` option should be an integer from 0 to 3'); + } -function resolveYamlOmap(data) { - if (data === null) return true; + // Detect level if not set manually + const colorLevel = stdoutColor ? stdoutColor.level : 0; + object.level = options.level === undefined ? colorLevel : options.level; +}; - var objectKeys = [], index, length, pair, pairKey, pairHasKey, - object = data; +class ChalkClass { + constructor(options) { + // eslint-disable-next-line no-constructor-return + return chalkFactory(options); + } +} - for (index = 0, length = object.length; index < length; index += 1) { - pair = object[index]; - pairHasKey = false; +const chalkFactory = options => { + const chalk = {}; + applyOptions(chalk, options); - if (_toString.call(pair) !== '[object Object]') return false; + chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_); - for (pairKey in pair) { - if (_hasOwnProperty.call(pair, pairKey)) { - if (!pairHasKey) pairHasKey = true; - else return false; - } - } + Object.setPrototypeOf(chalk, Chalk.prototype); + Object.setPrototypeOf(chalk.template, chalk); - if (!pairHasKey) return false; + chalk.template.constructor = () => { + throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.'); + }; - if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); - else return false; - } + chalk.template.Instance = ChalkClass; - return true; -} + return chalk.template; +}; -function constructYamlOmap(data) { - return data !== null ? data : []; +function Chalk(options) { + return chalkFactory(options); } -module.exports = new Type('tag:yaml.org,2002:omap', { - kind: 'sequence', - resolve: resolveYamlOmap, - construct: constructYamlOmap -}); +for (const [styleName, style] of Object.entries(ansiStyles)) { + styles[styleName] = { + get() { + const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty); + Object.defineProperty(this, styleName, {value: builder}); + return builder; + } + }; +} +styles.visible = { + get() { + const builder = createBuilder(this, this._styler, true); + Object.defineProperty(this, 'visible', {value: builder}); + return builder; + } +}; -/***/ }), -/* 182 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256']; -"use strict"; +for (const model of usedModels) { + styles[model] = { + get() { + const {level} = this; + return function (...arguments_) { + const styler = createStyler(ansiStyles.color[levelMapping[level]][model](...arguments_), ansiStyles.color.close, this._styler); + return createBuilder(this, styler, this._isEmpty); + }; + } + }; +} +for (const model of usedModels) { + const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); + styles[bgModel] = { + get() { + const {level} = this; + return function (...arguments_) { + const styler = createStyler(ansiStyles.bgColor[levelMapping[level]][model](...arguments_), ansiStyles.bgColor.close, this._styler); + return createBuilder(this, styler, this._isEmpty); + }; + } + }; +} -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } - -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } - -var BottleneckError, LocalDatastore, parser; -parser = __webpack_require__(714); -BottleneckError = __webpack_require__(212); -LocalDatastore = class LocalDatastore { - constructor(instance, storeOptions, storeInstanceOptions) { - this.instance = instance; - this.storeOptions = storeOptions; - this.clientId = this.instance._randomIndex(); - parser.load(storeInstanceOptions, storeInstanceOptions, this); - this._nextRequest = this._lastReservoirRefresh = this._lastReservoirIncrease = Date.now(); - this._running = 0; - this._done = 0; - this._unblockTime = 0; - this.ready = this.Promise.resolve(); - this.clients = {}; - - this._startHeartbeat(); - } +const proto = Object.defineProperties(() => {}, { + ...styles, + level: { + enumerable: true, + get() { + return this._generator.level; + }, + set(level) { + this._generator.level = level; + } + } +}); - _startHeartbeat() { - var base; +const createStyler = (open, close, parent) => { + let openAll; + let closeAll; + if (parent === undefined) { + openAll = open; + closeAll = close; + } else { + openAll = parent.openAll + open; + closeAll = close + parent.closeAll; + } - if (this.heartbeat == null && (this.storeOptions.reservoirRefreshInterval != null && this.storeOptions.reservoirRefreshAmount != null || this.storeOptions.reservoirIncreaseInterval != null && this.storeOptions.reservoirIncreaseAmount != null)) { - return typeof (base = this.heartbeat = setInterval(() => { - var amount, incr, maximum, now, reservoir; - now = Date.now(); + return { + open, + close, + openAll, + closeAll, + parent + }; +}; - if (this.storeOptions.reservoirRefreshInterval != null && now >= this._lastReservoirRefresh + this.storeOptions.reservoirRefreshInterval) { - this._lastReservoirRefresh = now; - this.storeOptions.reservoir = this.storeOptions.reservoirRefreshAmount; +const createBuilder = (self, _styler, _isEmpty) => { + const builder = (...arguments_) => { + if (isArray(arguments_[0]) && isArray(arguments_[0].raw)) { + // Called as a template literal, for example: chalk.red`2 + 3 = {bold ${2+3}}` + return applyStyle(builder, chalkTag(builder, ...arguments_)); + } - this.instance._drainAll(this.computeCapacity()); - } + // Single argument is hot path, implicit coercion is faster than anything + // eslint-disable-next-line no-implicit-coercion + return applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' ')); + }; - if (this.storeOptions.reservoirIncreaseInterval != null && now >= this._lastReservoirIncrease + this.storeOptions.reservoirIncreaseInterval) { - var _this$storeOptions = this.storeOptions; - amount = _this$storeOptions.reservoirIncreaseAmount; - maximum = _this$storeOptions.reservoirIncreaseMaximum; - reservoir = _this$storeOptions.reservoir; - this._lastReservoirIncrease = now; - incr = maximum != null ? Math.min(amount, maximum - reservoir) : amount; + // We alter the prototype because we must return a function, but there is + // no way to create a function with a different prototype + Object.setPrototypeOf(builder, proto); - if (incr > 0) { - this.storeOptions.reservoir += incr; - return this.instance._drainAll(this.computeCapacity()); - } - } - }, this.heartbeatInterval)).unref === "function" ? base.unref() : void 0; - } else { - return clearInterval(this.heartbeat); - } - } + builder._generator = self; + builder._styler = _styler; + builder._isEmpty = _isEmpty; - __publish__(message) { - var _this = this; + return builder; +}; - return _asyncToGenerator(function* () { - yield _this.yieldLoop(); - return _this.instance.Events.trigger("message", message.toString()); - })(); - } +const applyStyle = (self, string) => { + if (self.level <= 0 || !string) { + return self._isEmpty ? '' : string; + } - __disconnect__(flush) { - var _this2 = this; + let styler = self._styler; - return _asyncToGenerator(function* () { - yield _this2.yieldLoop(); - clearInterval(_this2.heartbeat); - return _this2.Promise.resolve(); - })(); - } + if (styler === undefined) { + return string; + } - yieldLoop(t = 0) { - return new this.Promise(function (resolve, reject) { - return setTimeout(resolve, t); - }); - } + const {openAll, closeAll} = styler; + if (string.indexOf('\u001B') !== -1) { + while (styler !== undefined) { + // Replace any instances already present with a re-opening code + // otherwise only the part of the string until said closing code + // will be colored, and the rest will simply be 'plain'. + string = stringReplaceAll(string, styler.close, styler.open); - computePenalty() { - var ref; - return (ref = this.storeOptions.penalty) != null ? ref : 15 * this.storeOptions.minTime || 5000; - } + styler = styler.parent; + } + } - __updateSettings__(options) { - var _this3 = this; + // We can move both next actions out of loop, because remaining actions in loop won't have + // any/visible effect on parts we add here. Close the styling before a linebreak and reopen + // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92 + const lfIndex = string.indexOf('\n'); + if (lfIndex !== -1) { + string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex); + } - return _asyncToGenerator(function* () { - yield _this3.yieldLoop(); - parser.overwrite(options, options, _this3.storeOptions); + return openAll + string + closeAll; +}; - _this3._startHeartbeat(); +let template; +const chalkTag = (chalk, ...strings) => { + const [firstString] = strings; - _this3.instance._drainAll(_this3.computeCapacity()); + if (!isArray(firstString) || !isArray(firstString.raw)) { + // If chalk() was called by itself or with a string, + // return the string itself as a string. + return strings.join(' '); + } - return true; - })(); - } + const arguments_ = strings.slice(1); + const parts = [firstString.raw[0]]; - __running__() { - var _this4 = this; + for (let i = 1; i < firstString.length; i++) { + parts.push( + String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'), + String(firstString.raw[i]) + ); + } - return _asyncToGenerator(function* () { - yield _this4.yieldLoop(); - return _this4._running; - })(); - } + if (template === undefined) { + template = __webpack_require__(451); + } - __queued__() { - var _this5 = this; + return template(chalk, parts.join('')); +}; - return _asyncToGenerator(function* () { - yield _this5.yieldLoop(); - return _this5.instance.queued(); - })(); - } +Object.defineProperties(Chalk.prototype, styles); - __done__() { - var _this6 = this; +const chalk = Chalk(); // eslint-disable-line new-cap +chalk.supportsColor = stdoutColor; +chalk.stderr = Chalk({level: stderrColor ? stderrColor.level : 0}); // eslint-disable-line new-cap +chalk.stderr.supportsColor = stderrColor; - return _asyncToGenerator(function* () { - yield _this6.yieldLoop(); - return _this6._done; - })(); - } +module.exports = chalk; - __groupCheck__(time) { - var _this7 = this; - return _asyncToGenerator(function* () { - yield _this7.yieldLoop(); - return _this7._nextRequest + _this7.timeout < time; - })(); - } +/***/ }), +/* 199 */, +/* 200 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { - computeCapacity() { - var maxConcurrent, reservoir; - var _this$storeOptions2 = this.storeOptions; - maxConcurrent = _this$storeOptions2.maxConcurrent; - reservoir = _this$storeOptions2.reservoir; +"use strict"; - if (maxConcurrent != null && reservoir != null) { - return Math.min(maxConcurrent - this._running, reservoir); - } else if (maxConcurrent != null) { - return maxConcurrent - this._running; - } else if (reservoir != null) { - return reservoir; - } else { - return null; +Object.defineProperty(exports, "__esModule", { value: true }); +const url_1 = __webpack_require__(835); +const lodash_1 = __webpack_require__(928); +exports.defaults = lodash_1.defaults; +exports.noop = lodash_1.noop; +exports.flatten = lodash_1.flatten; +const debug_1 = __webpack_require__(828); +exports.Debug = debug_1.default; +/** + * Test if two buffers are equal + * + * @export + * @param {Buffer} a + * @param {Buffer} b + * @returns {boolean} Whether the two buffers are equal + */ +function bufferEqual(a, b) { + if (typeof a.equals === "function") { + return a.equals(b); } - } - - conditionsCheck(weight) { - var capacity; - capacity = this.computeCapacity(); - return capacity == null || weight <= capacity; - } - - __incrementReservoir__(incr) { - var _this8 = this; - - return _asyncToGenerator(function* () { - var reservoir; - yield _this8.yieldLoop(); - reservoir = _this8.storeOptions.reservoir += incr; - - _this8.instance._drainAll(_this8.computeCapacity()); - - return reservoir; - })(); - } - - __currentReservoir__() { - var _this9 = this; - - return _asyncToGenerator(function* () { - yield _this9.yieldLoop(); - return _this9.storeOptions.reservoir; - })(); - } - - isBlocked(now) { - return this._unblockTime >= now; - } - - check(weight, now) { - return this.conditionsCheck(weight) && this._nextRequest - now <= 0; - } - - __check__(weight) { - var _this10 = this; - - return _asyncToGenerator(function* () { - var now; - yield _this10.yieldLoop(); - now = Date.now(); - return _this10.check(weight, now); - })(); - } - - __register__(index, weight, expiration) { - var _this11 = this; - - return _asyncToGenerator(function* () { - var now, wait; - yield _this11.yieldLoop(); - now = Date.now(); - - if (_this11.conditionsCheck(weight)) { - _this11._running += weight; - - if (_this11.storeOptions.reservoir != null) { - _this11.storeOptions.reservoir -= weight; + if (a.length !== b.length) { + return false; + } + for (let i = 0; i < a.length; ++i) { + if (a[i] !== b[i]) { + return false; } - - wait = Math.max(_this11._nextRequest - now, 0); - _this11._nextRequest = now + wait + _this11.storeOptions.minTime; - return { - success: true, - wait, - reservoir: _this11.storeOptions.reservoir - }; - } else { - return { - success: false - }; - } - })(); - } - - strategyIsBlock() { - return this.storeOptions.strategy === 3; - } - - __submit__(queueLength, weight) { - var _this12 = this; - - return _asyncToGenerator(function* () { - var blocked, now, reachedHWM; - yield _this12.yieldLoop(); - - if (_this12.storeOptions.maxConcurrent != null && weight > _this12.storeOptions.maxConcurrent) { - throw new BottleneckError(`Impossible to add a job having a weight of ${weight} to a limiter having a maxConcurrent setting of ${_this12.storeOptions.maxConcurrent}`); - } - - now = Date.now(); - reachedHWM = _this12.storeOptions.highWater != null && queueLength === _this12.storeOptions.highWater && !_this12.check(weight, now); - blocked = _this12.strategyIsBlock() && (reachedHWM || _this12.isBlocked(now)); - - if (blocked) { - _this12._unblockTime = now + _this12.computePenalty(); - _this12._nextRequest = _this12._unblockTime + _this12.storeOptions.minTime; - - _this12.instance._dropAllQueued(); - } - - return { - reachedHWM, - blocked, - strategy: _this12.storeOptions.strategy - }; - })(); - } - - __free__(index, weight) { - var _this13 = this; - - return _asyncToGenerator(function* () { - yield _this13.yieldLoop(); - _this13._running -= weight; - _this13._done += weight; - - _this13.instance._drainAll(_this13.computeCapacity()); - - return { - running: _this13._running - }; - })(); - } - -}; -module.exports = LocalDatastore; - -/***/ }), -/* 183 */ -/***/ (function(module) { - + } + return true; +} +exports.bufferEqual = bufferEqual; /** - * This method returns `false`. + * Convert a buffer to string, supports buffer array * - * @static - * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {boolean} Returns `false`. + * @param {*} value - The input value + * @param {string} encoding - string encoding + * @return {*} The result * @example - * - * _.times(2, _.stubFalse); - * // => [false, false] + * ```js + * var input = [Buffer.from('foo'), [Buffer.from('bar')]] + * var res = convertBufferToString(input, 'utf8') + * expect(res).to.eql(['foo', ['bar']]) + * ``` + * @private */ -function stubFalse() { - return false; -} - -module.exports = stubFalse; - - -/***/ }), -/* 184 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -/*eslint no-unused-vars:0*/ -var Lru = __webpack_require__(116); -var cloneDeep = __webpack_require__(482); -var utils = __webpack_require__(167); -var isObject = utils.isObject; - -function clone(object) { - if (typeof object === 'object' && object !== null) { - return cloneDeep(object); +function convertBufferToString(value, encoding) { + if (value instanceof Buffer) { + return value.toString(encoding); } - return object; + if (Array.isArray(value)) { + const length = value.length; + const res = Array(length); + for (let i = 0; i < length; ++i) { + res[i] = + value[i] instanceof Buffer && encoding === "utf8" + ? value[i].toString() + : convertBufferToString(value[i], encoding); + } + return res; + } + return value; } - +exports.convertBufferToString = convertBufferToString; /** - * Wrapper for lru-cache. - * NOTE: If you want to use a memory store, you want to write your own to have full - * control over its behavior. E.g., you might need the extra Promise overhead or - * you may want to clone objects a certain way before storing. - * - * @param {object} args - Args passed to underlying lru-cache, plus additional optional args: - * @param {boolean} [args.shouldCloneBeforeSet=true] - Whether to clone the data being stored. - * Default: true - * @param {boolean} [args.usePromises=true] - Whether to enable the use of Promises. Default: true - */ -var memoryStore = function(args) { - args = args || {}; - var self = {}; - self.name = 'memory'; - var Promise = args.promiseDependency || global.Promise; - self.usePromises = !(typeof Promise === 'undefined' || args.noPromises); - self.shouldCloneBeforeSet = args.shouldCloneBeforeSet !== false; // clone by default - - var ttl = args.ttl; - var lruOpts = { - max: args.max || 500, - maxAge: (ttl || ttl === 0) ? ttl * 1000 : null, - dispose: args.dispose, - length: args.length, - stale: args.stale, - updateAgeOnGet: args.updateAgeOnGet || false - }; - - var lruCache = new Lru(lruOpts); - - var setMultipleKeys = function setMultipleKeys(keysValues, maxAge) { - var length = keysValues.length; - var values = []; - for (var i = 0; i < length; i += 2) { - lruCache.set(keysValues[i], keysValues[i + 1], maxAge); - values.push(keysValues[i + 1]); - } - return values; - }; - - self.set = function(key, value, options, cb) { - if (self.shouldCloneBeforeSet) { - value = clone(value); - } - - if (typeof options === 'function') { - cb = options; - options = {}; - } - options = options || {}; - - var maxAge = (options.ttl || options.ttl === 0) ? options.ttl * 1000 : lruOpts.maxAge; - - lruCache.set(key, value, maxAge); - if (cb) { - process.nextTick(cb.bind(null, null)); - } else if (self.usePromises) { - return Promise.resolve(value); - } - }; - - self.mset = function() { - var args = Array.prototype.slice.apply(arguments); - var cb; - var options = {}; - - if (typeof args[args.length - 1] === 'function') { - cb = args.pop(); - } - - if (args.length % 2 > 0 && isObject(args[args.length - 1])) { - options = args.pop(); - } - - var maxAge = (options.ttl || options.ttl === 0) ? options.ttl * 1000 : lruOpts.maxAge; - - var values = setMultipleKeys(args, maxAge); - - if (cb) { - process.nextTick(cb.bind(null, null)); - } else if (self.usePromises) { - return Promise.resolve(values); - } - }; - - self.get = function(key, options, cb) { - if (typeof options === 'function') { - cb = options; - } - var value = lruCache.get(key); - - if (cb) { - process.nextTick(cb.bind(null, null, value)); - } else if (self.usePromises) { - return Promise.resolve(value); - } else { - return value; - } - }; - - self.mget = function() { - var args = Array.prototype.slice.apply(arguments); - var cb; - var options = {}; - - if (typeof args[args.length - 1] === 'function') { - cb = args.pop(); - } - - if (isObject(args[args.length - 1])) { - options = args.pop(); - } - - var values = args.map(function(key) { - return lruCache.get(key); - }); - - if (cb) { - process.nextTick(cb.bind(null, null, values)); - } else if (self.usePromises) { - return Promise.resolve(values); - } else { - return values; - } - }; - - self.del = function() { - var args = Array.prototype.slice.apply(arguments); - var cb; - var options = {}; - - if (typeof args[args.length - 1] === 'function') { - cb = args.pop(); - } - - if (isObject(args[args.length - 1])) { - options = args.pop(); - } - - if (Array.isArray(args[0])) { - args = args[0]; - } - - args.forEach(function(key) { - lruCache.del(key); - }); - - if (cb) { - process.nextTick(cb.bind(null, null)); - } else if (self.usePromises) { - return Promise.resolve(); - } - }; - - self.reset = function(cb) { - lruCache.reset(); - if (cb) { - process.nextTick(cb.bind(null, null)); - } else if (self.usePromises) { - return Promise.resolve(); + * Convert a list of results to node-style + * + * @param {Array} arr - The input value + * @return {Array} The output value + * @example + * ```js + * var input = ['a', 'b', new Error('c'), 'd'] + * var output = exports.wrapMultiResult(input) + * expect(output).to.eql([[null, 'a'], [null, 'b'], [new Error('c')], [null, 'd']) + * ``` + * @private + */ +function wrapMultiResult(arr) { + // When using WATCH/EXEC transactions, the EXEC will return + // a null instead of an array + if (!arr) { + return null; + } + const result = []; + const length = arr.length; + for (let i = 0; i < length; ++i) { + const item = arr[i]; + if (item instanceof Error) { + result.push([item]); } - }; - - self.keys = function(cb) { - var keys = lruCache.keys(); - if (cb) { - process.nextTick(cb.bind(null, null, keys)); - } else if (self.usePromises) { - return Promise.resolve(keys); - } else { - return keys; + else { + result.push([null, item]); } - }; - - return self; -}; - -var methods = { - create: function(args) { - return memoryStore(args); } -}; - -module.exports = methods; - - -/***/ }), -/* 185 */, -/* 186 */ -/***/ (function(module) { - -/*! - * toidentifier - * Copyright(c) 2016 Douglas Christopher Wilson - * MIT Licensed - */ - + return result; +} +exports.wrapMultiResult = wrapMultiResult; /** - * Module exports. - * @public + * Detect the argument is a int + * + * @param {string} value + * @return {boolean} Whether the value is a int + * @example + * ```js + * > isInt('123') + * true + * > isInt('123.3') + * false + * > isInt('1x') + * false + * > isInt(123) + * true + * > isInt(true) + * false + * ``` + * @private */ - -module.exports = toIdentifier - +function isInt(value) { + const x = parseFloat(value); + return !isNaN(value) && (x | 0) === x; +} +exports.isInt = isInt; /** - * Trasform the given string into a JavaScript identifier + * Pack an array to an Object * - * @param {string} str - * @returns {string} - * @public + * @param {array} array + * @return {object} + * @example + * ```js + * > packObject(['a', 'b', 'c', 'd']) + * { a: 'b', c: 'd' } + * ``` */ - -function toIdentifier (str) { - return str - .split(' ') - .map(function (token) { - return token.slice(0, 1).toUpperCase() + token.slice(1) - }) - .join('') - .replace(/[^ _0-9a-z]/gi, '') -} +function packObject(array) { + const result = {}; + const length = array.length; + for (let i = 1; i < length; i += 2) { + result[array[i - 1]] = array[i]; + } + return result; +} +exports.packObject = packObject; +/** + * Return a callback with timeout + * + * @param {function} callback + * @param {number} timeout + * @return {function} + */ +function timeout(callback, timeout) { + let timer; + const run = function () { + if (timer) { + clearTimeout(timer); + timer = null; + callback.apply(this, arguments); + } + }; + timer = setTimeout(run, timeout, new Error("timeout")); + return run; +} +exports.timeout = timeout; +/** + * Convert an object to an array + * + * @param {object} obj + * @return {array} + * @example + * ```js + * > convertObjectToArray({ a: '1' }) + * ['a', '1'] + * ``` + */ +function convertObjectToArray(obj) { + const result = []; + const keys = Object.keys(obj); + for (let i = 0, l = keys.length; i < l; i++) { + result.push(keys[i], obj[keys[i]]); + } + return result; +} +exports.convertObjectToArray = convertObjectToArray; +/** + * Convert a map to an array + * + * @param {Map} map + * @return {array} + * @example + * ```js + * > convertObjectToArray(new Map([[1, '2']])) + * [1, '2'] + * ``` + */ +function convertMapToArray(map) { + const result = []; + let pos = 0; + map.forEach(function (value, key) { + result[pos] = key; + result[pos + 1] = value; + pos += 2; + }); + return result; +} +exports.convertMapToArray = convertMapToArray; +/** + * Convert a non-string arg to a string + * + * @param {*} arg + * @return {string} + */ +function toArg(arg) { + if (arg === null || typeof arg === "undefined") { + return ""; + } + return String(arg); +} +exports.toArg = toArg; +/** + * Optimize error stack + * + * @param {Error} error - actually error + * @param {string} friendlyStack - the stack that more meaningful + * @param {string} filterPath - only show stacks with the specified path + */ +function optimizeErrorStack(error, friendlyStack, filterPath) { + const stacks = friendlyStack.split("\n"); + let lines = ""; + let i; + for (i = 1; i < stacks.length; ++i) { + if (stacks[i].indexOf(filterPath) === -1) { + break; + } + } + for (let j = i; j < stacks.length; ++j) { + lines += "\n" + stacks[j]; + } + const pos = error.stack.indexOf("\n"); + error.stack = error.stack.slice(0, pos) + lines; + return error; +} +exports.optimizeErrorStack = optimizeErrorStack; +/** + * Parse the redis protocol url + * + * @param {string} url - the redis protocol url + * @return {Object} + */ +function parseURL(url) { + if (isInt(url)) { + return { port: url }; + } + let parsed = url_1.parse(url, true, true); + if (!parsed.slashes && url[0] !== "/") { + url = "//" + url; + parsed = url_1.parse(url, true, true); + } + const result = {}; + if (parsed.auth) { + const parsedAuth = parsed.auth.split(":"); + result.password = parsedAuth[1]; + } + if (parsed.pathname) { + if (parsed.protocol === "redis:" || parsed.protocol === "rediss:") { + if (parsed.pathname.length > 1) { + result.db = parsed.pathname.slice(1); + } + } + else { + result.path = parsed.pathname; + } + } + if (parsed.host) { + result.host = parsed.hostname; + } + if (parsed.port) { + result.port = parsed.port; + } + lodash_1.defaults(result, parsed.query); + return result; +} +exports.parseURL = parseURL; +/** + * Get a random element from `array` + * + * @export + * @template T + * @param {T[]} array the array + * @param {number} [from=0] start index + * @returns {T} + */ +function sample(array, from = 0) { + const length = array.length; + if (from >= length) { + return; + } + return array[from + Math.floor(Math.random() * (length - from))]; +} +exports.sample = sample; +/** + * Shuffle the array using the Fisher-Yates Shuffle. + * This method will mutate the original array. + * + * @export + * @template T + * @param {T[]} array + * @returns {T[]} + */ +function shuffle(array) { + let counter = array.length; + // While there are elements in the array + while (counter > 0) { + // Pick a random index + const index = Math.floor(Math.random() * counter); + // Decrease counter by 1 + counter--; + // And swap the last element with it + [array[counter], array[index]] = [array[index], array[counter]]; + } + return array; +} +exports.shuffle = shuffle; +/** + * Error message for connection being disconnected + */ +exports.CONNECTION_CLOSED_ERROR_MSG = "Connection is closed."; +function zipMap(keys, values) { + const map = new Map(); + keys.forEach((key, index) => { + map.set(key, values[index]); + }); + return map; +} +exports.zipMap = zipMap; /***/ }), -/* 187 */, -/* 188 */, -/* 189 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { +/* 201 */ +/***/ (function(module, __unusedexports, __webpack_require__) { "use strict"; -var Buffer = __webpack_require__(215).Buffer; +const os = __webpack_require__(87); -// Multibyte codec. In this scheme, a character is represented by 1 or more bytes. -// Our codec supports UTF-16 surrogates, extensions for GB18030 and unicode sequences. -// To save memory and loading time, we read table files only when requested. +const extractPathRegex = /\s+at.*(?:\(|\s)(.*)\)?/; +const pathRegex = /^(?:(?:(?:node|(?:internal\/[\w/]*|.*node_modules\/(?:babel-polyfill|pirates)\/.*)?\w+)\.js:\d+:\d+)|native)/; +const homeDir = typeof os.homedir === 'undefined' ? '' : os.homedir(); -exports._dbcs = DBCSCodec; +module.exports = (stack, options) => { + options = Object.assign({pretty: false}, options); -var UNASSIGNED = -1, - GB18030_CODE = -2, - SEQ_START = -10, - NODE_START = -1000, - UNASSIGNED_NODE = new Array(0x100), - DEF_CHAR = -1; + return stack.replace(/\\/g, '/') + .split('\n') + .filter(line => { + const pathMatches = line.match(extractPathRegex); + if (pathMatches === null || !pathMatches[1]) { + return true; + } -for (var i = 0; i < 0x100; i++) - UNASSIGNED_NODE[i] = UNASSIGNED; + const match = pathMatches[1]; + // Electron + if ( + match.includes('.app/Contents/Resources/electron.asar') || + match.includes('.app/Contents/Resources/default_app.asar') + ) { + return false; + } -// Class DBCSCodec reads and initializes mapping tables. -function DBCSCodec(codecOptions, iconv) { - this.encodingName = codecOptions.encodingName; - if (!codecOptions) - throw new Error("DBCS codec is called without the data.") - if (!codecOptions.table) - throw new Error("Encoding '" + this.encodingName + "' has no data."); + return !pathRegex.test(match); + }) + .filter(line => line.trim() !== '') + .map(line => { + if (options.pretty) { + return line.replace(extractPathRegex, (m, p1) => m.replace(p1, p1.replace(homeDir, '~'))); + } - // Load tables. - var mappingTable = codecOptions.table(); + return line; + }) + .join('\n'); +}; - // Decode tables: MBCS -> Unicode. +/***/ }), +/* 202 */, +/* 203 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - // decodeTables is a trie, encoded as an array of arrays of integers. Internal arrays are trie nodes and all have len = 256. - // Trie root is decodeTables[0]. - // Values: >= 0 -> unicode character code. can be > 0xFFFF - // == UNASSIGNED -> unknown/unassigned sequence. - // == GB18030_CODE -> this is the end of a GB18030 4-byte sequence. - // <= NODE_START -> index of the next node in our trie to process next byte. - // <= SEQ_START -> index of the start of a character code sequence, in decodeTableSeq. - this.decodeTables = []; - this.decodeTables[0] = UNASSIGNED_NODE.slice(0); // Create root node. +"use strict"; +/*! + * methods + * Copyright(c) 2013-2014 TJ Holowaychuk + * Copyright(c) 2015-2016 Douglas Christopher Wilson + * MIT Licensed + */ - // Sometimes a MBCS char corresponds to a sequence of unicode chars. We store them as arrays of integers here. - this.decodeTableSeq = []; - // Actual mapping tables consist of chunks. Use them to fill up decode tables. - for (var i = 0; i < mappingTable.length; i++) - this._addDecodeChunk(mappingTable[i]); - this.defaultCharUnicode = iconv.defaultCharUnicode; +/** + * Module dependencies. + * @private + */ - - // Encode tables: Unicode -> DBCS. +var http = __webpack_require__(605); - // `encodeTable` is array mapping from unicode char to encoded char. All its values are integers for performance. - // Because it can be sparse, it is represented as array of buckets by 256 chars each. Bucket can be null. - // Values: >= 0 -> it is a normal char. Write the value (if <=256 then 1 byte, if <=65536 then 2 bytes, etc.). - // == UNASSIGNED -> no conversion found. Output a default char. - // <= SEQ_START -> it's an index in encodeTableSeq, see below. The character starts a sequence. - this.encodeTable = []; - - // `encodeTableSeq` is used when a sequence of unicode characters is encoded as a single code. We use a tree of - // objects where keys correspond to characters in sequence and leafs are the encoded dbcs values. A special DEF_CHAR key - // means end of sequence (needed when one sequence is a strict subsequence of another). - // Objects are kept separately from encodeTable to increase performance. - this.encodeTableSeq = []; +/** + * Module exports. + * @public + */ - // Some chars can be decoded, but need not be encoded. - var skipEncodeChars = {}; - if (codecOptions.encodeSkipVals) - for (var i = 0; i < codecOptions.encodeSkipVals.length; i++) { - var val = codecOptions.encodeSkipVals[i]; - if (typeof val === 'number') - skipEncodeChars[val] = true; - else - for (var j = val.from; j <= val.to; j++) - skipEncodeChars[j] = true; - } - - // Use decode trie to recursively fill out encode tables. - this._fillEncodeTable(0, 0, skipEncodeChars); +module.exports = getCurrentNodeMethods() || getBasicNodeMethods(); - // Add more encoding pairs when needed. - if (codecOptions.encodeAdd) { - for (var uChar in codecOptions.encodeAdd) - if (Object.prototype.hasOwnProperty.call(codecOptions.encodeAdd, uChar)) - this._setEncodeChar(uChar.charCodeAt(0), codecOptions.encodeAdd[uChar]); - } +/** + * Get the current Node.js methods. + * @private + */ - this.defCharSB = this.encodeTable[0][iconv.defaultCharSingleByte.charCodeAt(0)]; - if (this.defCharSB === UNASSIGNED) this.defCharSB = this.encodeTable[0]['?']; - if (this.defCharSB === UNASSIGNED) this.defCharSB = "?".charCodeAt(0); +function getCurrentNodeMethods() { + return http.METHODS && http.METHODS.map(function lowerCaseMethod(method) { + return method.toLowerCase(); + }); +} +/** + * Get the "basic" Node.js methods, a snapshot from Node.js 0.10. + * @private + */ - // Load & create GB18030 tables when needed. - if (typeof codecOptions.gb18030 === 'function') { - this.gb18030 = codecOptions.gb18030(); // Load GB18030 ranges. +function getBasicNodeMethods() { + return [ + 'get', + 'post', + 'put', + 'head', + 'delete', + 'options', + 'trace', + 'copy', + 'lock', + 'mkcol', + 'move', + 'purge', + 'propfind', + 'proppatch', + 'unlock', + 'report', + 'mkactivity', + 'checkout', + 'merge', + 'm-search', + 'notify', + 'subscribe', + 'unsubscribe', + 'patch', + 'search', + 'connect' + ]; +} - // Add GB18030 decode tables. - var thirdByteNodeIdx = this.decodeTables.length; - var thirdByteNode = this.decodeTables[thirdByteNodeIdx] = UNASSIGNED_NODE.slice(0); - var fourthByteNodeIdx = this.decodeTables.length; - var fourthByteNode = this.decodeTables[fourthByteNodeIdx] = UNASSIGNED_NODE.slice(0); +/***/ }), +/* 204 */, +/* 205 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - for (var i = 0x81; i <= 0xFE; i++) { - var secondByteNodeIdx = NODE_START - this.decodeTables[0][i]; - var secondByteNode = this.decodeTables[secondByteNodeIdx]; - for (var j = 0x30; j <= 0x39; j++) - secondByteNode[j] = NODE_START - thirdByteNodeIdx; - } - for (var i = 0x81; i <= 0xFE; i++) - thirdByteNode[i] = NODE_START - fourthByteNodeIdx; - for (var i = 0x30; i <= 0x39; i++) - fourthByteNode[i] = GB18030_CODE - } -} +"use strict"; -DBCSCodec.prototype.encoder = DBCSEncoder; -DBCSCodec.prototype.decoder = DBCSDecoder; -// Decoder helpers -DBCSCodec.prototype._getDecodeTrieNode = function(addr) { - var bytes = []; - for (; addr > 0; addr >>= 8) - bytes.push(addr & 0xFF); - if (bytes.length == 0) - bytes.push(0); +const { createContext, runInContext } = __webpack_require__(184) - var node = this.decodeTables[0]; - for (var i = bytes.length-1; i > 0; i--) { // Traverse nodes deeper into the trie. - var val = node[bytes[i]]; +module.exports = validator - if (val == UNASSIGNED) { // Create new node. - node[bytes[i]] = NODE_START - this.decodeTables.length; - this.decodeTables.push(node = UNASSIGNED_NODE.slice(0)); - } - else if (val <= NODE_START) { // Existing node. - node = this.decodeTables[NODE_START - val]; - } - else - throw new Error("Overwrite byte in " + this.encodingName + ", addr: " + addr.toString(16)); - } - return node; +function validator (opts = {}) { + const { + ERR_PATHS_MUST_BE_STRINGS = () => 'fast-redact - Paths must be strings', + ERR_INVALID_PATH = (s) => `fast-redact – Invalid path (${s})` + } = opts + + return function validate ({ paths }) { + paths.forEach((s) => { + if (typeof s !== 'string') { + throw Error(ERR_PATHS_MUST_BE_STRINGS()) + } + try { + if (/〇/.test(s)) throw Error() + const proxy = new Proxy({}, { get: () => proxy, set: () => { throw Error() } }) + const expr = (s[0] === '[' ? '' : '.') + s.replace(/^\*/, '〇').replace(/\.\*/g, '.〇').replace(/\[\*\]/g, '[〇]') + if (/\n|\r|;/.test(expr)) throw Error() + if (/\/\*/.test(expr)) throw Error() + runInContext(` + (function () { + 'use strict' + o${expr} + if ([o${expr}].length !== 1) throw Error() + })() + `, createContext({ o: proxy, 〇: null }), { + codeGeneration: { strings: false, wasm: false } + }) + } catch (e) { + throw Error(ERR_INVALID_PATH(s)) + } + }) + } } -DBCSCodec.prototype._addDecodeChunk = function(chunk) { - // First element of chunk is the hex mbcs code where we start. - var curAddr = parseInt(chunk[0], 16); - - // Choose the decoding node where we'll write our chars. - var writeTable = this._getDecodeTrieNode(curAddr); - curAddr = curAddr & 0xFF; +/***/ }), +/* 206 */, +/* 207 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { - // Write all other elements of the chunk to the table. - for (var k = 1; k < chunk.length; k++) { - var part = chunk[k]; - if (typeof part === "string") { // String, write as-is. - for (var l = 0; l < part.length;) { - var code = part.charCodeAt(l++); - if (0xD800 <= code && code < 0xDC00) { // Decode surrogate - var codeTrail = part.charCodeAt(l++); - if (0xDC00 <= codeTrail && codeTrail < 0xE000) - writeTable[curAddr++] = 0x10000 + (code - 0xD800) * 0x400 + (codeTrail - 0xDC00); - else - throw new Error("Incorrect surrogate pair in " + this.encodingName + " at chunk " + chunk[0]); - } - else if (0x0FF0 < code && code <= 0x0FFF) { // Character sequence (our own encoding used) - var len = 0xFFF - code + 2; - var seq = []; - for (var m = 0; m < len; m++) - seq.push(part.charCodeAt(l++)); // Simple variation: don't support surrogates or subsequences in seq. +"use strict"; - writeTable[curAddr++] = SEQ_START - this.decodeTableSeq.length; - this.decodeTableSeq.push(seq); - } - else - writeTable[curAddr++] = code; // Basic char +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = __webpack_require__(109); +function throwLater(e) { + setTimeout(function () { + throw e; + }, 0); +} +function asCallback(promise, nodeback, options) { + if (typeof nodeback === 'function') { + promise.then((val) => { + let ret; + if (options !== undefined && Object(options).spread && Array.isArray(val)) { + ret = utils_1.tryCatch(nodeback).apply(undefined, [null].concat(val)); } - } - else if (typeof part === "number") { // Integer, meaning increasing sequence starting with prev character. - var charCode = writeTable[curAddr - 1] + 1; - for (var l = 0; l < part; l++) - writeTable[curAddr++] = charCode++; - } - else - throw new Error("Incorrect type '" + typeof part + "' given in " + this.encodingName + " at chunk " + chunk[0]); + else { + ret = val === undefined + ? utils_1.tryCatch(nodeback)(null) + : utils_1.tryCatch(nodeback)(null, val); + } + if (ret === utils_1.errorObj) { + throwLater(ret.e); + } + }, (cause) => { + if (!cause) { + const newReason = new Error(cause + ''); + Object.assign(newReason, { cause }); + cause = newReason; + } + const ret = utils_1.tryCatch(nodeback)(cause); + if (ret === utils_1.errorObj) { + throwLater(ret.e); + } + }); } - if (curAddr > 0xFF) - throw new Error("Incorrect chunk in " + this.encodingName + " at addr " + chunk[0] + ": too long" + curAddr); + return promise; } +exports.default = asCallback; -// Encoder helpers -DBCSCodec.prototype._getEncodeBucket = function(uCode) { - var high = uCode >> 8; // This could be > 0xFF because of astral characters. - if (this.encodeTable[high] === undefined) - this.encodeTable[high] = UNASSIGNED_NODE.slice(0); // Create bucket on demand. - return this.encodeTable[high]; -} -DBCSCodec.prototype._setEncodeChar = function(uCode, dbcsCode) { - var bucket = this._getEncodeBucket(uCode); - var low = uCode & 0xFF; - if (bucket[low] <= SEQ_START) - this.encodeTableSeq[SEQ_START-bucket[low]][DEF_CHAR] = dbcsCode; // There's already a sequence, set a single-char subsequence of it. - else if (bucket[low] == UNASSIGNED) - bucket[low] = dbcsCode; -} +/***/ }), +/* 208 */, +/* 209 */ +/***/ (function(module, exports, __webpack_require__) { -DBCSCodec.prototype._setEncodeSequence = function(seq, dbcsCode) { - - // Get the root of character tree according to first character of the sequence. - var uCode = seq[0]; - var bucket = this._getEncodeBucket(uCode); - var low = uCode & 0xFF; - var node; - if (bucket[low] <= SEQ_START) { - // There's already a sequence with - use it. - node = this.encodeTableSeq[SEQ_START-bucket[low]]; - } - else { - // There was no sequence object - allocate a new one. - node = {}; - if (bucket[low] !== UNASSIGNED) node[DEF_CHAR] = bucket[low]; // If a char was set before - make it a single-char subsequence. - bucket[low] = SEQ_START - this.encodeTableSeq.length; - this.encodeTableSeq.push(node); - } - - // Traverse the character tree, allocating new nodes as needed. - for (var j = 1; j < seq.length-1; j++) { - var oldVal = node[uCode]; - if (typeof oldVal === 'object') - node = oldVal; - else { - node = node[uCode] = {} - if (oldVal !== undefined) - node[DEF_CHAR] = oldVal - } - } +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + * + * Expose `debug()` as the module. + */ - // Set the leaf to given dbcsCode. - uCode = seq[seq.length-1]; - node[uCode] = dbcsCode; -} +exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; +exports.coerce = coerce; +exports.disable = disable; +exports.enable = enable; +exports.enabled = enabled; +exports.humanize = __webpack_require__(848); -DBCSCodec.prototype._fillEncodeTable = function(nodeIdx, prefix, skipEncodeChars) { - var node = this.decodeTables[nodeIdx]; - for (var i = 0; i < 0x100; i++) { - var uCode = node[i]; - var mbCode = prefix + i; - if (skipEncodeChars[mbCode]) - continue; +/** + * The currently active debug mode names, and names to skip. + */ - if (uCode >= 0) - this._setEncodeChar(uCode, mbCode); - else if (uCode <= NODE_START) - this._fillEncodeTable(NODE_START - uCode, mbCode << 8, skipEncodeChars); - else if (uCode <= SEQ_START) - this._setEncodeSequence(this.decodeTableSeq[SEQ_START - uCode], mbCode); - } -} +exports.names = []; +exports.skips = []; +/** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ +exports.formatters = {}; -// == Encoder ================================================================== +/** + * Previous log timestamp. + */ -function DBCSEncoder(options, codec) { - // Encoder state - this.leadSurrogate = -1; - this.seqObj = undefined; - - // Static data - this.encodeTable = codec.encodeTable; - this.encodeTableSeq = codec.encodeTableSeq; - this.defaultCharSingleByte = codec.defCharSB; - this.gb18030 = codec.gb18030; -} +var prevTime; -DBCSEncoder.prototype.write = function(str) { - var newBuf = Buffer.alloc(str.length * (this.gb18030 ? 4 : 3)), - leadSurrogate = this.leadSurrogate, - seqObj = this.seqObj, nextChar = -1, - i = 0, j = 0; +/** + * Select a color. + * @param {String} namespace + * @return {Number} + * @api private + */ - while (true) { - // 0. Get next character. - if (nextChar === -1) { - if (i == str.length) break; - var uCode = str.charCodeAt(i++); - } - else { - var uCode = nextChar; - nextChar = -1; - } +function selectColor(namespace) { + var hash = 0, i; - // 1. Handle surrogates. - if (0xD800 <= uCode && uCode < 0xE000) { // Char is one of surrogates. - if (uCode < 0xDC00) { // We've got lead surrogate. - if (leadSurrogate === -1) { - leadSurrogate = uCode; - continue; - } else { - leadSurrogate = uCode; - // Double lead surrogate found. - uCode = UNASSIGNED; - } - } else { // We've got trail surrogate. - if (leadSurrogate !== -1) { - uCode = 0x10000 + (leadSurrogate - 0xD800) * 0x400 + (uCode - 0xDC00); - leadSurrogate = -1; - } else { - // Incomplete surrogate pair - only trail surrogate found. - uCode = UNASSIGNED; - } - - } - } - else if (leadSurrogate !== -1) { - // Incomplete surrogate pair - only lead surrogate found. - nextChar = uCode; uCode = UNASSIGNED; // Write an error, then current char. - leadSurrogate = -1; - } + for (i in namespace) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } - // 2. Convert uCode character. - var dbcsCode = UNASSIGNED; - if (seqObj !== undefined && uCode != UNASSIGNED) { // We are in the middle of the sequence - var resCode = seqObj[uCode]; - if (typeof resCode === 'object') { // Sequence continues. - seqObj = resCode; - continue; + return exports.colors[Math.abs(hash) % exports.colors.length]; +} - } else if (typeof resCode == 'number') { // Sequence finished. Write it. - dbcsCode = resCode; +/** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ - } else if (resCode == undefined) { // Current character is not part of the sequence. +function createDebug(namespace) { - // Try default character for this sequence - resCode = seqObj[DEF_CHAR]; - if (resCode !== undefined) { - dbcsCode = resCode; // Found. Write it. - nextChar = uCode; // Current character will be written too in the next iteration. + function debug() { + // disabled? + if (!debug.enabled) return; - } else { - // TODO: What if we have no default? (resCode == undefined) - // Then, we should write first char of the sequence as-is and try the rest recursively. - // Didn't do it for now because no encoding has this situation yet. - // Currently, just skip the sequence and write current char. - } - } - seqObj = undefined; - } - else if (uCode >= 0) { // Regular character - var subtable = this.encodeTable[uCode >> 8]; - if (subtable !== undefined) - dbcsCode = subtable[uCode & 0xFF]; - - if (dbcsCode <= SEQ_START) { // Sequence start - seqObj = this.encodeTableSeq[SEQ_START-dbcsCode]; - continue; - } + var self = debug; - if (dbcsCode == UNASSIGNED && this.gb18030) { - // Use GB18030 algorithm to find character(s) to write. - var idx = findIdx(this.gb18030.uChars, uCode); - if (idx != -1) { - var dbcsCode = this.gb18030.gbChars[idx] + (uCode - this.gb18030.uChars[idx]); - newBuf[j++] = 0x81 + Math.floor(dbcsCode / 12600); dbcsCode = dbcsCode % 12600; - newBuf[j++] = 0x30 + Math.floor(dbcsCode / 1260); dbcsCode = dbcsCode % 1260; - newBuf[j++] = 0x81 + Math.floor(dbcsCode / 10); dbcsCode = dbcsCode % 10; - newBuf[j++] = 0x30 + dbcsCode; - continue; - } - } - } + // set `diff` timestamp + var curr = +new Date(); + var ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; - // 3. Write dbcsCode character. - if (dbcsCode === UNASSIGNED) - dbcsCode = this.defaultCharSingleByte; - - if (dbcsCode < 0x100) { - newBuf[j++] = dbcsCode; - } - else if (dbcsCode < 0x10000) { - newBuf[j++] = dbcsCode >> 8; // high byte - newBuf[j++] = dbcsCode & 0xFF; // low byte - } - else { - newBuf[j++] = dbcsCode >> 16; - newBuf[j++] = (dbcsCode >> 8) & 0xFF; - newBuf[j++] = dbcsCode & 0xFF; - } + // turn the `arguments` into a proper Array + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; } - this.seqObj = seqObj; - this.leadSurrogate = leadSurrogate; - return newBuf.slice(0, j); -} - -DBCSEncoder.prototype.end = function() { - if (this.leadSurrogate === -1 && this.seqObj === undefined) - return; // All clean. Most often case. - - var newBuf = Buffer.alloc(10), j = 0; - - if (this.seqObj) { // We're in the sequence. - var dbcsCode = this.seqObj[DEF_CHAR]; - if (dbcsCode !== undefined) { // Write beginning of the sequence. - if (dbcsCode < 0x100) { - newBuf[j++] = dbcsCode; - } - else { - newBuf[j++] = dbcsCode >> 8; // high byte - newBuf[j++] = dbcsCode & 0xFF; // low byte - } - } else { - // See todo above. - } - this.seqObj = undefined; - } + args[0] = exports.coerce(args[0]); - if (this.leadSurrogate !== -1) { - // Incomplete surrogate pair - only lead surrogate found. - newBuf[j++] = this.defaultCharSingleByte; - this.leadSurrogate = -1; + if ('string' !== typeof args[0]) { + // anything else let's inspect with %O + args.unshift('%O'); } - - return newBuf.slice(0, j); -} -// Export for testing -DBCSEncoder.prototype.findIdx = findIdx; + // apply any `formatters` transformations + var index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { + // if we encounter an escaped % then don't increase the array index + if (match === '%%') return match; + index++; + var formatter = exports.formatters[format]; + if ('function' === typeof formatter) { + var val = args[index]; + match = formatter.call(self, val); + // now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); -// == Decoder ================================================================== + // apply env-specific formatting (colors, etc.) + exports.formatArgs.call(self, args); -function DBCSDecoder(options, codec) { - // Decoder state - this.nodeIdx = 0; - this.prevBuf = Buffer.alloc(0); + var logFn = debug.log || exports.log || console.log.bind(console); + logFn.apply(self, args); + } - // Static data - this.decodeTables = codec.decodeTables; - this.decodeTableSeq = codec.decodeTableSeq; - this.defaultCharUnicode = codec.defaultCharUnicode; - this.gb18030 = codec.gb18030; -} + debug.namespace = namespace; + debug.enabled = exports.enabled(namespace); + debug.useColors = exports.useColors(); + debug.color = selectColor(namespace); -DBCSDecoder.prototype.write = function(buf) { - var newBuf = Buffer.alloc(buf.length*2), - nodeIdx = this.nodeIdx, - prevBuf = this.prevBuf, prevBufOffset = this.prevBuf.length, - seqStart = -this.prevBuf.length, // idx of the start of current parsed sequence. - uCode; + // env-specific initialization logic for debug instances + if ('function' === typeof exports.init) { + exports.init(debug); + } - if (prevBufOffset > 0) // Make prev buf overlap a little to make it easier to slice later. - prevBuf = Buffer.concat([prevBuf, buf.slice(0, 10)]); - - for (var i = 0, j = 0; i < buf.length; i++) { - var curByte = (i >= 0) ? buf[i] : prevBuf[i + prevBufOffset]; + return debug; +} - // Lookup in current trie node. - var uCode = this.decodeTables[nodeIdx][curByte]; +/** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ - if (uCode >= 0) { - // Normal character, just use it. - } - else if (uCode === UNASSIGNED) { // Unknown char. - // TODO: Callback with seq. - //var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset); - i = seqStart; // Try to parse again, after skipping first byte of the sequence ('i' will be incremented by 'for' cycle). - uCode = this.defaultCharUnicode.charCodeAt(0); - } - else if (uCode === GB18030_CODE) { - var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset); - var ptr = (curSeq[0]-0x81)*12600 + (curSeq[1]-0x30)*1260 + (curSeq[2]-0x81)*10 + (curSeq[3]-0x30); - var idx = findIdx(this.gb18030.gbChars, ptr); - uCode = this.gb18030.uChars[idx] + ptr - this.gb18030.gbChars[idx]; - } - else if (uCode <= NODE_START) { // Go to next trie node. - nodeIdx = NODE_START - uCode; - continue; - } - else if (uCode <= SEQ_START) { // Output a sequence of chars. - var seq = this.decodeTableSeq[SEQ_START - uCode]; - for (var k = 0; k < seq.length - 1; k++) { - uCode = seq[k]; - newBuf[j++] = uCode & 0xFF; - newBuf[j++] = uCode >> 8; - } - uCode = seq[seq.length-1]; - } - else - throw new Error("iconv-lite internal error: invalid decoding table value " + uCode + " at " + nodeIdx + "/" + curByte); +function enable(namespaces) { + exports.save(namespaces); - // Write the character to buffer, handling higher planes using surrogate pair. - if (uCode > 0xFFFF) { - uCode -= 0x10000; - var uCodeLead = 0xD800 + Math.floor(uCode / 0x400); - newBuf[j++] = uCodeLead & 0xFF; - newBuf[j++] = uCodeLead >> 8; + exports.names = []; + exports.skips = []; - uCode = 0xDC00 + uCode % 0x400; - } - newBuf[j++] = uCode & 0xFF; - newBuf[j++] = uCode >> 8; + var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + var len = split.length; - // Reset trie node. - nodeIdx = 0; seqStart = i+1; + for (var i = 0; i < len; i++) { + if (!split[i]) continue; // ignore empty strings + namespaces = split[i].replace(/\*/g, '.*?'); + if (namespaces[0] === '-') { + exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + exports.names.push(new RegExp('^' + namespaces + '$')); } - - this.nodeIdx = nodeIdx; - this.prevBuf = (seqStart >= 0) ? buf.slice(seqStart) : prevBuf.slice(seqStart + prevBufOffset); - return newBuf.slice(0, j).toString('ucs2'); + } } -DBCSDecoder.prototype.end = function() { - var ret = ''; - - // Try to parse all remaining chars. - while (this.prevBuf.length > 0) { - // Skip 1 character in the buffer. - ret += this.defaultCharUnicode; - var buf = this.prevBuf.slice(1); - - // Parse remaining as usual. - this.prevBuf = Buffer.alloc(0); - this.nodeIdx = 0; - if (buf.length > 0) - ret += this.write(buf); - } +/** + * Disable debug output. + * + * @api public + */ - this.nodeIdx = 0; - return ret; +function disable() { + exports.enable(''); } -// Binary search for GB18030. Returns largest i such that table[i] <= val. -function findIdx(table, val) { - if (table[0] > val) - return -1; +/** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ - var l = 0, r = table.length; - while (l < r-1) { // always table[l] <= val < table[r] - var mid = l + Math.floor((r-l+1)/2); - if (table[mid] <= val) - l = mid; - else - r = mid; +function enabled(name) { + var i, len; + for (i = 0, len = exports.skips.length; i < len; i++) { + if (exports.skips[i].test(name)) { + return false; } - return l; + } + for (i = 0, len = exports.names.length; i < len; i++) { + if (exports.names[i].test(name)) { + return true; + } + } + return false; } +/** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; +} -/***/ }), -/* 190 */, -/* 191 */ -/***/ (function(module) { - -module.exports = require("querystring"); /***/ }), -/* 192 */ -/***/ (function(module) { +/* 210 */ +/***/ (function(module, __unusedexports, __webpack_require__) { "use strict"; +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ -function getParamSize(keySize) { - var result = ((keySize / 8) | 0) + (keySize % 8 === 0 ? 0 : 1); - return result; -} -var paramBytesForAlg = { - ES256: getParamSize(256), - ES384: getParamSize(384), - ES512: getParamSize(521) -}; +/** + * Module dependencies. + */ -function getParamBytesForAlg(alg) { - var paramBytes = paramBytesForAlg[alg]; - if (paramBytes) { - return paramBytes; - } +var merge = __webpack_require__(707) +var parseUrl = __webpack_require__(768); +var qs = __webpack_require__(386); - throw new Error('Unknown algorithm "' + alg + '"'); -} +/** + * @param {Object} options + * @return {Function} + * @api public + */ -module.exports = getParamBytesForAlg; +module.exports = function query(options) { + var opts = merge({}, options) + var queryparse = qs.parse; + if (typeof options === 'function') { + queryparse = options; + opts = undefined; + } -/***/ }), -/* 193 */, -/* 194 */, -/* 195 */, -/* 196 */ -/***/ (function(__unusedmodule, __unusedexports, __webpack_require__) { + if (opts !== undefined && opts.allowPrototypes === undefined) { + // back-compat for qs module + opts.allowPrototypes = true; + } -const Layer = __webpack_require__(805); -const Router = __webpack_require__(987); + return function query(req, res, next){ + if (!req.query) { + var val = parseUrl(req).query; + req.query = queryparse(val, opts); + } -const last = (arr = []) => arr[arr.length - 1]; -const noop = Function.prototype; + next(); + }; +}; -function copyFnProps(oldFn, newFn) { - Object.keys(oldFn).forEach((key) => { - newFn[key] = oldFn[key]; - }); - return newFn; + +/***/ }), +/* 211 */ +/***/ (function(module) { + +"use strict"; + + +/** + * Expose `arrayFlatten`. + */ +module.exports = arrayFlatten + +/** + * Recursive flatten function with depth. + * + * @param {Array} array + * @param {Array} result + * @param {Number} depth + * @return {Array} + */ +function flattenWithDepth (array, result, depth) { + for (var i = 0; i < array.length; i++) { + var value = array[i] + + if (depth > 0 && Array.isArray(value)) { + flattenWithDepth(value, result, depth - 1) + } else { + result.push(value) + } + } + + return result } -function wrap(fn) { - const newFn = function newFn(...args) { - const ret = fn.apply(this, args); - const next = (args.length === 5 ? args[2] : last(args)) || noop; - if (ret && ret.catch) ret.catch(err => next(err)); - return ret; - }; - Object.defineProperty(newFn, 'length', { - value: fn.length, - writable: false, - }); - return copyFnProps(fn, newFn); +/** + * Recursive flatten function. Omitting depth is slightly faster. + * + * @param {Array} array + * @param {Array} result + * @return {Array} + */ +function flattenForever (array, result) { + for (var i = 0; i < array.length; i++) { + var value = array[i] + + if (Array.isArray(value)) { + flattenForever(value, result) + } else { + result.push(value) + } + } + + return result } -function patchRouterParam() { - const originalParam = Router.prototype.constructor.param; - Router.prototype.constructor.param = function param(name, fn) { - fn = wrap(fn); - return originalParam.call(this, name, fn); - }; +/** + * Flatten an array, with the ability to define a depth. + * + * @param {Array} array + * @param {Number} depth + * @return {Array} + */ +function arrayFlatten (array, depth) { + if (depth == null) { + return flattenForever(array, []) + } + + return flattenWithDepth(array, [], depth) } -Object.defineProperty(Layer.prototype, 'handle', { - enumerable: true, - get() { - return this.__handle; - }, - set(fn) { - fn = wrap(fn); - this.__handle = fn; - }, -}); -patchRouterParam(); +/***/ }), +/* 212 */ +/***/ (function(module) { + +"use strict"; + + +var BottleneckError; +BottleneckError = class BottleneckError extends Error {}; +module.exports = BottleneckError; + +/***/ }), +/* 213 */ +/***/ (function(module) { +module.exports = require("punycode"); /***/ }), -/* 197 */ +/* 214 */, +/* 215 */ /***/ (function(module, __unusedexports, __webpack_require__) { -module.exports = isexe -isexe.sync = sync +"use strict"; +/* eslint-disable node/no-deprecated-api */ -var fs = __webpack_require__(747) -function isexe (path, options, cb) { - fs.stat(path, function (er, stat) { - cb(er, er ? false : checkStat(stat, options)) - }) -} -function sync (path, options) { - return checkStat(fs.statSync(path), options) +var buffer = __webpack_require__(293) +var Buffer = buffer.Buffer + +var safer = {} + +var key + +for (key in buffer) { + if (!buffer.hasOwnProperty(key)) continue + if (key === 'SlowBuffer' || key === 'Buffer') continue + safer[key] = buffer[key] } -function checkStat (stat, options) { - return stat.isFile() && checkMode(stat, options) +var Safer = safer.Buffer = {} +for (key in Buffer) { + if (!Buffer.hasOwnProperty(key)) continue + if (key === 'allocUnsafe' || key === 'allocUnsafeSlow') continue + Safer[key] = Buffer[key] } -function checkMode (stat, options) { - var mod = stat.mode - var uid = stat.uid - var gid = stat.gid +safer.Buffer.prototype = Buffer.prototype - var myUid = options.uid !== undefined ? - options.uid : process.getuid && process.getuid() - var myGid = options.gid !== undefined ? - options.gid : process.getgid && process.getgid() +if (!Safer.from || Safer.from === Uint8Array.from) { + Safer.from = function (value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof value) + } + if (value && typeof value.length === 'undefined') { + throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type ' + typeof value) + } + return Buffer(value, encodingOrOffset, length) + } +} - var u = parseInt('100', 8) - var g = parseInt('010', 8) - var o = parseInt('001', 8) - var ug = u | g +if (!Safer.alloc) { + Safer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size) + } + if (size < 0 || size >= 2 * (1 << 30)) { + throw new RangeError('The value "' + size + '" is invalid for option "size"') + } + var buf = Buffer(size) + if (!fill || fill.length === 0) { + buf.fill(0) + } else if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + return buf + } +} - var ret = (mod & o) || - (mod & g) && gid === myGid || - (mod & u) && uid === myUid || - (mod & ug) && myUid === 0 +if (!safer.kStringMaxLength) { + try { + safer.kStringMaxLength = process.binding('buffer').kStringMaxLength + } catch (e) { + // we can't determine kStringMaxLength in environments where process.binding + // is unsupported, so let's not set it + } +} - return ret +if (!safer.constants) { + safer.constants = { + MAX_LENGTH: safer.kMaxLength + } + if (safer.kStringMaxLength) { + safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength + } } +module.exports = safer + /***/ }), -/* 198 */ -/***/ (function(module) { +/* 216 */ +/***/ (function(module, __unusedexports, __webpack_require__) { -/** Used as references for various `Number` constants. */ -var MAX_SAFE_INTEGER = 9007199254740991; +"use strict"; -/** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ -function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; -} +const pTry = __webpack_require__(130); + +const pLimit = concurrency => { + if (!((Number.isInteger(concurrency) || concurrency === Infinity) && concurrency > 0)) { + return Promise.reject(new TypeError('Expected `concurrency` to be a number from 1 and up')); + } -module.exports = isLength; + const queue = []; + let activeCount = 0; + + const next = () => { + activeCount--; + + if (queue.length > 0) { + queue.shift()(); + } + }; + + const run = (fn, resolve, ...args) => { + activeCount++; + + const result = pTry(fn, ...args); + + resolve(result); + + result.then(next, next); + }; + + const enqueue = (fn, resolve, ...args) => { + if (activeCount < concurrency) { + run(fn, resolve, ...args); + } else { + queue.push(run.bind(null, fn, resolve, ...args)); + } + }; + + const generator = (fn, ...args) => new Promise(resolve => enqueue(fn, resolve, ...args)); + Object.defineProperties(generator, { + activeCount: { + get: () => activeCount + }, + pendingCount: { + get: () => queue.length + } + }); + + return generator; +}; + +module.exports = pLimit; +module.exports.default = pLimit; /***/ }), -/* 199 */, -/* 200 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { +/* 217 */, +/* 218 */ +/***/ (function(module) { "use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const url_1 = __webpack_require__(835); -const lodash_1 = __webpack_require__(961); -exports.defaults = lodash_1.defaults; -exports.noop = lodash_1.noop; -exports.flatten = lodash_1.flatten; -const debug_1 = __webpack_require__(828); -exports.Debug = debug_1.default; + /** - * Test if two buffers are equal - * - * @export - * @param {Buffer} a - * @param {Buffer} b - * @returns {boolean} Whether the two buffers are equal + * Custom implementation of a double ended queue. */ -function bufferEqual(a, b) { - if (typeof a.equals === "function") { - return a.equals(b); - } - if (a.length !== b.length) { - return false; - } - for (let i = 0; i < a.length; ++i) { - if (a[i] !== b[i]) { - return false; - } - } - return true; +function Denque(array) { + this._head = 0; + this._tail = 0; + this._capacityMask = 0x3; + this._list = new Array(4); + if (Array.isArray(array)) { + this._fromArray(array); + } } -exports.bufferEqual = bufferEqual; + /** - * Convert a buffer to string, supports buffer array - * - * @param {*} value - The input value - * @param {string} encoding - string encoding - * @return {*} The result - * @example - * ```js - * var input = [Buffer.from('foo'), [Buffer.from('bar')]] - * var res = convertBufferToString(input, 'utf8') - * expect(res).to.eql(['foo', ['bar']]) - * ``` - * @private + * ------------- + * PUBLIC API + * ------------- */ -function convertBufferToString(value, encoding) { - if (value instanceof Buffer) { - return value.toString(encoding); - } - if (Array.isArray(value)) { - const length = value.length; - const res = Array(length); - for (let i = 0; i < length; ++i) { - res[i] = - value[i] instanceof Buffer && encoding === "utf8" - ? value[i].toString() - : convertBufferToString(value[i], encoding); - } - return res; - } - return value; -} -exports.convertBufferToString = convertBufferToString; + /** - * Convert a list of results to node-style - * - * @param {Array} arr - The input value - * @return {Array} The output value - * @example - * ```js - * var input = ['a', 'b', new Error('c'), 'd'] - * var output = exports.wrapMultiResult(input) - * expect(output).to.eql([[null, 'a'], [null, 'b'], [new Error('c')], [null, 'd']) - * ``` - * @private + * Returns the item at the specified index from the list. + * 0 is the first element, 1 is the second, and so on... + * Elements at negative values are that many from the end: -1 is one before the end + * (the last element), -2 is two before the end (one before last), etc. + * @param index + * @returns {*} */ -function wrapMultiResult(arr) { - // When using WATCH/EXEC transactions, the EXEC will return - // a null instead of an array - if (!arr) { - return null; - } - const result = []; - const length = arr.length; - for (let i = 0; i < length; ++i) { - const item = arr[i]; - if (item instanceof Error) { - result.push([item]); - } - else { - result.push([null, item]); - } - } - return result; -} -exports.wrapMultiResult = wrapMultiResult; +Denque.prototype.peekAt = function peekAt(index) { + var i = index; + // expect a number or return undefined + if ((i !== (i | 0))) { + return void 0; + } + var len = this.size(); + if (i >= len || i < -len) return undefined; + if (i < 0) i += len; + i = (this._head + i) & this._capacityMask; + return this._list[i]; +}; + /** - * Detect the argument is a int - * - * @param {string} value - * @return {boolean} Whether the value is a int - * @example - * ```js - * > isInt('123') - * true - * > isInt('123.3') - * false - * > isInt('1x') - * false - * > isInt(123) - * true - * > isInt(true) - * false - * ``` - * @private + * Alias for peakAt() + * @param i + * @returns {*} */ -function isInt(value) { - const x = parseFloat(value); - return !isNaN(value) && (x | 0) === x; -} -exports.isInt = isInt; +Denque.prototype.get = function get(i) { + return this.peekAt(i); +}; + /** - * Pack an array to an Object - * - * @param {array} array - * @return {object} - * @example - * ```js - * > packObject(['a', 'b', 'c', 'd']) - * { a: 'b', c: 'd' } - * ``` + * Returns the first item in the list without removing it. + * @returns {*} */ -function packObject(array) { - const result = {}; - const length = array.length; - for (let i = 1; i < length; i += 2) { - result[array[i - 1]] = array[i]; - } - return result; -} -exports.packObject = packObject; +Denque.prototype.peek = function peek() { + if (this._head === this._tail) return undefined; + return this._list[this._head]; +}; + /** - * Return a callback with timeout - * - * @param {function} callback - * @param {number} timeout - * @return {function} + * Alias for peek() + * @returns {*} */ -function timeout(callback, timeout) { - let timer; - const run = function () { - if (timer) { - clearTimeout(timer); - timer = null; - callback.apply(this, arguments); - } - }; - timer = setTimeout(run, timeout, new Error("timeout")); - return run; -} -exports.timeout = timeout; +Denque.prototype.peekFront = function peekFront() { + return this.peek(); +}; + /** - * Convert an object to an array - * - * @param {object} obj - * @return {array} - * @example - * ```js - * > convertObjectToArray({ a: '1' }) - * ['a', '1'] - * ``` + * Returns the item that is at the back of the queue without removing it. + * Uses peekAt(-1) */ -function convertObjectToArray(obj) { - const result = []; - const keys = Object.keys(obj); - for (let i = 0, l = keys.length; i < l; i++) { - result.push(keys[i], obj[keys[i]]); - } - return result; -} -exports.convertObjectToArray = convertObjectToArray; +Denque.prototype.peekBack = function peekBack() { + return this.peekAt(-1); +}; + /** - * Convert a map to an array - * - * @param {Map} map - * @return {array} - * @example - * ```js - * > convertObjectToArray(new Map([[1, '2']])) - * [1, '2'] - * ``` + * Returns the current length of the queue + * @return {Number} */ -function convertMapToArray(map) { - const result = []; - let pos = 0; - map.forEach(function (value, key) { - result[pos] = key; - result[pos + 1] = value; - pos += 2; - }); - return result; -} -exports.convertMapToArray = convertMapToArray; +Object.defineProperty(Denque.prototype, 'length', { + get: function length() { + return this.size(); + } +}); + /** - * Convert a non-string arg to a string - * - * @param {*} arg - * @return {string} + * Return the number of items on the list, or 0 if empty. + * @returns {number} */ -function toArg(arg) { - if (arg === null || typeof arg === "undefined") { - return ""; - } - return String(arg); -} -exports.toArg = toArg; +Denque.prototype.size = function size() { + if (this._head === this._tail) return 0; + if (this._head < this._tail) return this._tail - this._head; + else return this._capacityMask + 1 - (this._head - this._tail); +}; + /** - * Optimize error stack - * - * @param {Error} error - actually error - * @param {string} friendlyStack - the stack that more meaningful - * @param {string} filterPath - only show stacks with the specified path + * Add an item at the beginning of the list. + * @param item */ -function optimizeErrorStack(error, friendlyStack, filterPath) { - const stacks = friendlyStack.split("\n"); - let lines = ""; - let i; - for (i = 1; i < stacks.length; ++i) { - if (stacks[i].indexOf(filterPath) === -1) { - break; - } +Denque.prototype.unshift = function unshift(item) { + if (item === undefined) return this.size(); + var len = this._list.length; + this._head = (this._head - 1 + len) & this._capacityMask; + this._list[this._head] = item; + if (this._tail === this._head) this._growArray(); + if (this._head < this._tail) return this._tail - this._head; + else return this._capacityMask + 1 - (this._head - this._tail); +}; + +/** + * Remove and return the first item on the list, + * Returns undefined if the list is empty. + * @returns {*} + */ +Denque.prototype.shift = function shift() { + var head = this._head; + if (head === this._tail) return undefined; + var item = this._list[head]; + this._list[head] = undefined; + this._head = (head + 1) & this._capacityMask; + if (head < 2 && this._tail > 10000 && this._tail <= this._list.length >>> 2) this._shrinkArray(); + return item; +}; + +/** + * Add an item to the bottom of the list. + * @param item + */ +Denque.prototype.push = function push(item) { + if (item === undefined) return this.size(); + var tail = this._tail; + this._list[tail] = item; + this._tail = (tail + 1) & this._capacityMask; + if (this._tail === this._head) { + this._growArray(); + } + + if (this._head < this._tail) return this._tail - this._head; + else return this._capacityMask + 1 - (this._head - this._tail); +}; + +/** + * Remove and return the last item on the list. + * Returns undefined if the list is empty. + * @returns {*} + */ +Denque.prototype.pop = function pop() { + var tail = this._tail; + if (tail === this._head) return undefined; + var len = this._list.length; + this._tail = (tail - 1 + len) & this._capacityMask; + var item = this._list[this._tail]; + this._list[this._tail] = undefined; + if (this._head < 2 && tail > 10000 && tail <= len >>> 2) this._shrinkArray(); + return item; +}; + +/** + * Remove and return the item at the specified index from the list. + * Returns undefined if the list is empty. + * @param index + * @returns {*} + */ +Denque.prototype.removeOne = function removeOne(index) { + var i = index; + // expect a number or return undefined + if ((i !== (i | 0))) { + return void 0; + } + if (this._head === this._tail) return void 0; + var size = this.size(); + var len = this._list.length; + if (i >= size || i < -size) return void 0; + if (i < 0) i += size; + i = (this._head + i) & this._capacityMask; + var item = this._list[i]; + var k; + if (index < size / 2) { + for (k = index; k > 0; k--) { + this._list[i] = this._list[i = (i - 1 + len) & this._capacityMask]; } - for (let j = i; j < stacks.length; ++j) { - lines += "\n" + stacks[j]; + this._list[i] = void 0; + this._head = (this._head + 1 + len) & this._capacityMask; + } else { + for (k = size - 1 - index; k > 0; k--) { + this._list[i] = this._list[i = ( i + 1 + len) & this._capacityMask]; } - const pos = error.stack.indexOf("\n"); - error.stack = error.stack.slice(0, pos) + lines; - return error; -} -exports.optimizeErrorStack = optimizeErrorStack; + this._list[i] = void 0; + this._tail = (this._tail - 1 + len) & this._capacityMask; + } + return item; +}; + /** - * Parse the redis protocol url - * - * @param {string} url - the redis protocol url - * @return {Object} + * Remove number of items from the specified index from the list. + * Returns array of removed items. + * Returns undefined if the list is empty. + * @param index + * @param count + * @returns {array} */ -function parseURL(url) { - if (isInt(url)) { - return { port: url }; - } - let parsed = url_1.parse(url, true, true); - if (!parsed.slashes && url[0] !== "/") { - url = "//" + url; - parsed = url_1.parse(url, true, true); +Denque.prototype.remove = function remove(index, count) { + var i = index; + var removed; + var del_count = count; + // expect a number or return undefined + if ((i !== (i | 0))) { + return void 0; + } + if (this._head === this._tail) return void 0; + var size = this.size(); + var len = this._list.length; + if (i >= size || i < -size || count < 1) return void 0; + if (i < 0) i += size; + if (count === 1 || !count) { + removed = new Array(1); + removed[0] = this.removeOne(i); + return removed; + } + if (i === 0 && i + count >= size) { + removed = this.toArray(); + this.clear(); + return removed; + } + if (i + count > size) count = size - i; + var k; + removed = new Array(count); + for (k = 0; k < count; k++) { + removed[k] = this._list[(this._head + i + k) & this._capacityMask]; + } + i = (this._head + i) & this._capacityMask; + if (index + count === size) { + this._tail = (this._tail - count + len) & this._capacityMask; + for (k = count; k > 0; k--) { + this._list[i = (i + 1 + len) & this._capacityMask] = void 0; } - const result = {}; - if (parsed.auth) { - const parsedAuth = parsed.auth.split(":"); - result.password = parsedAuth[1]; + return removed; + } + if (index === 0) { + this._head = (this._head + count + len) & this._capacityMask; + for (k = count - 1; k > 0; k--) { + this._list[i = (i + 1 + len) & this._capacityMask] = void 0; } - if (parsed.pathname) { - if (parsed.protocol === "redis:" || parsed.protocol === "rediss:") { - if (parsed.pathname.length > 1) { - result.db = parsed.pathname.slice(1); - } - } - else { - result.path = parsed.pathname; - } + return removed; + } + if (i < size / 2) { + this._head = (this._head + index + count + len) & this._capacityMask; + for (k = index; k > 0; k--) { + this.unshift(this._list[i = (i - 1 + len) & this._capacityMask]); } - if (parsed.host) { - result.host = parsed.hostname; + i = (this._head - 1 + len) & this._capacityMask; + while (del_count > 0) { + this._list[i = (i - 1 + len) & this._capacityMask] = void 0; + del_count--; } - if (parsed.port) { - result.port = parsed.port; + if (index < 0) this._tail = i; + } else { + this._tail = i; + i = (i + count + len) & this._capacityMask; + for (k = size - (count + index); k > 0; k--) { + this.push(this._list[i++]); } - lodash_1.defaults(result, parsed.query); - return result; -} -exports.parseURL = parseURL; -/** - * Get a random element from `array` - * - * @export - * @template T - * @param {T[]} array the array - * @param {number} [from=0] start index - * @returns {T} - */ -function sample(array, from = 0) { - const length = array.length; - if (from >= length) { - return; + i = this._tail; + while (del_count > 0) { + this._list[i = (i + 1 + len) & this._capacityMask] = void 0; + del_count--; } - return array[from + Math.floor(Math.random() * (length - from))]; -} -exports.sample = sample; + } + if (this._head < 2 && this._tail > 10000 && this._tail <= len >>> 2) this._shrinkArray(); + return removed; +}; + /** - * Shuffle the array using the Fisher-Yates Shuffle. - * This method will mutate the original array. + * Native splice implementation. + * Remove number of items from the specified index from the list and/or add new elements. + * Returns array of removed items or empty array if count == 0. + * Returns undefined if the list is empty. * - * @export - * @template T - * @param {T[]} array - * @returns {T[]} - */ -function shuffle(array) { - let counter = array.length; - // While there are elements in the array - while (counter > 0) { - // Pick a random index - const index = Math.floor(Math.random() * counter); - // Decrease counter by 1 - counter--; - // And swap the last element with it - [array[counter], array[index]] = [array[index], array[counter]]; - } - return array; -} -exports.shuffle = shuffle; -/** - * Error message for connection being disconnected + * @param index + * @param count + * @param {...*} [elements] + * @returns {array} */ -exports.CONNECTION_CLOSED_ERROR_MSG = "Connection is closed."; -function zipMap(keys, values) { - const map = new Map(); - keys.forEach((key, index) => { - map.set(key, values[index]); - }); - return map; -} -exports.zipMap = zipMap; - - -/***/ }), -/* 201 */, -/* 202 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; - - -// Original repository: https://github.com/defunctzombie/node-lsmod/ -// -// [2018-02-09] @kamilogorek - Handle scoped packages structure - -// builtin -var fs = __webpack_require__(747); -var path = __webpack_require__(622); - -// node 0.6 support -fs.existsSync = fs.existsSync || path.existsSync; - -// mainPaths are the paths where our mainprog will be able to load from -// we store these to avoid grabbing the modules that were loaded as a result -// of a dependency module loading its dependencies, we only care about deps our -// mainprog loads -var mainPaths = (require.main && require.main.paths) || []; - -module.exports = function() { - var paths = Object.keys(require.cache || []); - - // module information - var infos = {}; - - // paths we have already inspected to avoid traversing again - var seen = {}; - - paths.forEach(function(p) { - /* eslint-disable consistent-return */ - - var dir = p; - - (function updir() { - var orig = dir; - dir = path.dirname(orig); - - if (/@[^/]+$/.test(dir)) { - dir = path.dirname(dir); +Denque.prototype.splice = function splice(index, count) { + var i = index; + // expect a number or return undefined + if ((i !== (i | 0))) { + return void 0; + } + var size = this.size(); + if (i < 0) i += size; + if (i > size) return void 0; + if (arguments.length > 2) { + var k; + var temp; + var removed; + var arg_len = arguments.length; + var len = this._list.length; + var arguments_index = 2; + if (!size || i < size / 2) { + temp = new Array(i); + for (k = 0; k < i; k++) { + temp[k] = this._list[(this._head + k) & this._capacityMask]; } - - if (!dir || orig === dir || seen[orig]) { - return; - } else if (mainPaths.indexOf(dir) < 0) { - return updir(); + if (count === 0) { + removed = []; + if (i > 0) { + this._head = (this._head + i + len) & this._capacityMask; + } + } else { + removed = this.remove(i, count); + this._head = (this._head + i + len) & this._capacityMask; } - - var pkgfile = path.join(orig, 'package.json'); - var exists = fs.existsSync(pkgfile); - - seen[orig] = true; - - // travel up the tree if no package.json here - if (!exists) { - return updir(); + while (arg_len > arguments_index) { + this.unshift(arguments[--arg_len]); } - - try { - var info = JSON.parse(fs.readFileSync(pkgfile, 'utf8')); - infos[info.name] = info.version; - } catch (e) {} - })(); - - /* eslint-enable consistent-return */ - }); - - return infos; + for (k = i; k > 0; k--) { + this.unshift(temp[k - 1]); + } + } else { + temp = new Array(size - (i + count)); + var leng = temp.length; + for (k = 0; k < leng; k++) { + temp[k] = this._list[(this._head + i + count + k) & this._capacityMask]; + } + if (count === 0) { + removed = []; + if (i != size) { + this._tail = (this._head + i + len) & this._capacityMask; + } + } else { + removed = this.remove(i, count); + this._tail = (this._tail - leng + len) & this._capacityMask; + } + while (arguments_index < arg_len) { + this.push(arguments[arguments_index++]); + } + for (k = 0; k < leng; k++) { + this.push(temp[k]); + } + } + return removed; + } else { + return this.remove(i, count); + } }; - -/***/ }), -/* 203 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; -/*! - * methods - * Copyright(c) 2013-2014 TJ Holowaychuk - * Copyright(c) 2015-2016 Douglas Christopher Wilson - * MIT Licensed +/** + * Soft clear - does not reset capacity. */ - - +Denque.prototype.clear = function clear() { + this._head = 0; + this._tail = 0; +}; /** - * Module dependencies. - * @private + * Returns true or false whether the list is empty. + * @returns {boolean} */ - -var http = __webpack_require__(605); +Denque.prototype.isEmpty = function isEmpty() { + return this._head === this._tail; +}; /** - * Module exports. - * @public + * Returns an array of all queue items. + * @returns {Array} */ +Denque.prototype.toArray = function toArray() { + return this._copyArray(false); +}; -module.exports = getCurrentNodeMethods() || getBasicNodeMethods(); +/** + * ------------- + * INTERNALS + * ------------- + */ /** - * Get the current Node.js methods. + * Fills the queue with items from an array + * For use in the constructor + * @param array * @private */ +Denque.prototype._fromArray = function _fromArray(array) { + for (var i = 0; i < array.length; i++) this.push(array[i]); +}; -function getCurrentNodeMethods() { - return http.METHODS && http.METHODS.map(function lowerCaseMethod(method) { - return method.toLowerCase(); - }); -} +/** + * + * @param fullCopy + * @returns {Array} + * @private + */ +Denque.prototype._copyArray = function _copyArray(fullCopy) { + var newArray = []; + var list = this._list; + var len = list.length; + var i; + if (fullCopy || this._head > this._tail) { + for (i = this._head; i < len; i++) newArray.push(list[i]); + for (i = 0; i < this._tail; i++) newArray.push(list[i]); + } else { + for (i = this._head; i < this._tail; i++) newArray.push(list[i]); + } + return newArray; +}; /** - * Get the "basic" Node.js methods, a snapshot from Node.js 0.10. + * Grows the internal list array. * @private */ +Denque.prototype._growArray = function _growArray() { + if (this._head) { + // copy existing data, head to end, then beginning to tail. + this._list = this._copyArray(true); + this._head = 0; + } -function getBasicNodeMethods() { - return [ - 'get', - 'post', - 'put', - 'head', - 'delete', - 'options', - 'trace', - 'copy', - 'lock', - 'mkcol', - 'move', - 'purge', - 'propfind', - 'proppatch', - 'unlock', - 'report', - 'mkactivity', - 'checkout', - 'merge', - 'm-search', - 'notify', - 'subscribe', - 'unsubscribe', - 'patch', - 'search', - 'connect' - ]; -} - + // head is at 0 and array is now full, safe to extend + this._tail = this._list.length; -/***/ }), -/* 204 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + this._list.length *= 2; + this._capacityMask = (this._capacityMask << 1) | 1; +}; -var overArg = __webpack_require__(127); +/** + * Shrinks the internal list array. + * @private + */ +Denque.prototype._shrinkArray = function _shrinkArray() { + this._list.length >>>= 1; + this._capacityMask >>>= 1; +}; -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeKeys = overArg(Object.keys, Object); -module.exports = nativeKeys; +module.exports = Denque; /***/ }), -/* 205 */, -/* 206 */, -/* 207 */ +/* 219 */ /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -const utils_1 = __webpack_require__(109); -function throwLater(e) { - setTimeout(function () { - throw e; - }, 0); +const net_1 = __webpack_require__(631); +const tls_1 = __webpack_require__(16); +const utils_1 = __webpack_require__(200); +const AbstractConnector_1 = __webpack_require__(94); +function isIIpcConnectionOptions(value) { + return value.path; } -function asCallback(promise, nodeback, options) { - if (typeof nodeback === 'function') { - promise.then((val) => { - let ret; - if (options !== undefined && Object(options).spread && Array.isArray(val)) { - ret = utils_1.tryCatch(nodeback).apply(undefined, [null].concat(val)); - } - else { - ret = val === undefined - ? utils_1.tryCatch(nodeback)(null) - : utils_1.tryCatch(nodeback)(null, val); - } - if (ret === utils_1.errorObj) { - throwLater(ret.e); +exports.isIIpcConnectionOptions = isIIpcConnectionOptions; +class StandaloneConnector extends AbstractConnector_1.default { + constructor(options) { + super(); + this.options = options; + } + connect(_) { + const { options } = this; + this.connecting = true; + let connectionOptions; + if (isIIpcConnectionOptions(options)) { + connectionOptions = { + path: options.path, + }; + } + else { + connectionOptions = {}; + if (options.port != null) { + connectionOptions.port = options.port; } - }, (cause) => { - if (!cause) { - const newReason = new Error(cause + ''); - Object.assign(newReason, { cause }); - cause = newReason; + if (options.host != null) { + connectionOptions.host = options.host; } - const ret = utils_1.tryCatch(nodeback)(cause); - if (ret === utils_1.errorObj) { - throwLater(ret.e); + if (options.family != null) { + connectionOptions.family = options.family; } + } + if (options.tls) { + Object.assign(connectionOptions, options.tls); + } + // TODO: + // We use native Promise here since other Promise + // implementation may use different schedulers that + // cause issue when the stream is resolved in the + // next tick. + // Should use the provided promise in the next major + // version and do not connect before resolved. + return new Promise((resolve, reject) => { + process.nextTick(() => { + if (!this.connecting) { + reject(new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG)); + return; + } + try { + if (options.tls) { + this.stream = tls_1.connect(connectionOptions); + } + else { + this.stream = net_1.createConnection(connectionOptions); + } + } + catch (err) { + reject(err); + return; + } + resolve(this.stream); + }); }); } - return promise; -} -exports.default = asCallback; - - -/***/ }), -/* 208 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -var baseGetTag = __webpack_require__(51), - isObjectLike = __webpack_require__(458); - -/** `Object#toString` result references. */ -var argsTag = '[object Arguments]'; - -/** - * The base implementation of `_.isArguments`. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - */ -function baseIsArguments(value) { - return isObjectLike(value) && baseGetTag(value) == argsTag; } - -module.exports = baseIsArguments; +exports.default = StandaloneConnector; /***/ }), -/* 209 */ +/* 220 */, +/* 221 */ /***/ (function(module, exports, __webpack_require__) { - /** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. + * This is the web browser implementation of `debug()`. * * Expose `debug()` as the module. */ -exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; -exports.coerce = coerce; -exports.disable = disable; -exports.enable = enable; -exports.enabled = enabled; -exports.humanize = __webpack_require__(848); +exports = module.exports = __webpack_require__(354); +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = 'undefined' != typeof chrome + && 'undefined' != typeof chrome.storage + ? chrome.storage.local + : localstorage(); /** - * The currently active debug mode names, and names to skip. + * Colors. */ -exports.names = []; -exports.skips = []; +exports.colors = [ + 'lightseagreen', + 'forestgreen', + 'goldenrod', + 'dodgerblue', + 'darkorchid', + 'crimson' +]; /** - * Map of special "%n" handling functions, for the debug "format" argument. + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + * TODO: add a `localStorage` variable to explicitly enable/disable colors */ -exports.formatters = {}; - -/** - * Previous log timestamp. - */ +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { + return true; + } -var prevTime; + // is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} /** - * Select a color. - * @param {String} namespace - * @return {Number} - * @api private + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ -function selectColor(namespace) { - var hash = 0, i; - - for (i in namespace) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer +exports.formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (err) { + return '[UnexpectedJSONParseError]: ' + err.message; } +}; - return exports.colors[Math.abs(hash) % exports.colors.length]; -} /** - * Create a debugger with the given `namespace`. + * Colorize log arguments if enabled. * - * @param {String} namespace - * @return {Function} * @api public */ -function createDebug(namespace) { - - function debug() { - // disabled? - if (!debug.enabled) return; - - var self = debug; +function formatArgs(args) { + var useColors = this.useColors; - // set `diff` timestamp - var curr = +new Date(); - var ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; + args[0] = (useColors ? '%c' : '') + + this.namespace + + (useColors ? ' %c' : ' ') + + args[0] + + (useColors ? '%c ' : ' ') + + '+' + exports.humanize(this.diff); - // turn the `arguments` into a proper Array - var args = new Array(arguments.length); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i]; - } + if (!useColors) return; - args[0] = exports.coerce(args[0]); + var c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit') - if ('string' !== typeof args[0]) { - // anything else let's inspect with %O - args.unshift('%O'); + // the final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + var index = 0; + var lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, function(match) { + if ('%%' === match) return; + index++; + if ('%c' === match) { + // we only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; } + }); - // apply any `formatters` transformations - var index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { - // if we encounter an escaped % then don't increase the array index - if (match === '%%') return match; - index++; - var formatter = exports.formatters[format]; - if ('function' === typeof formatter) { - var val = args[index]; - match = formatter.call(self, val); - - // now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); - - // apply env-specific formatting (colors, etc.) - exports.formatArgs.call(self, args); - - var logFn = debug.log || exports.log || console.log.bind(console); - logFn.apply(self, args); - } - - debug.namespace = namespace; - debug.enabled = exports.enabled(namespace); - debug.useColors = exports.useColors(); - debug.color = selectColor(namespace); - - // env-specific initialization logic for debug instances - if ('function' === typeof exports.init) { - exports.init(debug); - } - - return debug; + args.splice(lastC, 0, c); } /** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". * - * @param {String} namespaces * @api public */ -function enable(namespaces) { - exports.save(namespaces); - - exports.names = []; - exports.skips = []; +function log() { + // this hackery is required for IE8/9, where + // the `console.log` function doesn't have 'apply' + return 'object' === typeof console + && console.log + && Function.prototype.apply.call(console.log, console, arguments); +} - var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - var len = split.length; +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ - for (var i = 0; i < len; i++) { - if (!split[i]) continue; // ignore empty strings - namespaces = split[i].replace(/\*/g, '.*?'); - if (namespaces[0] === '-') { - exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); +function save(namespaces) { + try { + if (null == namespaces) { + exports.storage.removeItem('debug'); } else { - exports.names.push(new RegExp('^' + namespaces + '$')); + exports.storage.debug = namespaces; } - } + } catch(e) {} } /** - * Disable debug output. + * Load `namespaces`. * - * @api public + * @return {String} returns the previously persisted debug modes + * @api private */ -function disable() { - exports.enable(''); +function load() { + var r; + try { + r = exports.storage.debug; + } catch(e) {} + + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + + return r; } /** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public + * Enable namespaces listed in `localStorage.debug` initially. */ -function enabled(name) { - var i, len; - for (i = 0, len = exports.skips.length; i < len; i++) { - if (exports.skips[i].test(name)) { - return false; - } - } - for (i = 0, len = exports.names.length; i < len; i++) { - if (exports.names[i].test(name)) { - return true; - } - } - return false; -} +exports.enable(load()); /** - * Coerce `val`. + * Localstorage attempts to return the localstorage. * - * @param {Mixed} val - * @return {Mixed} + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} * @api private */ -function coerce(val) { - if (val instanceof Error) return val.stack || val.message; - return val; +function localstorage() { + try { + return window.localStorage; + } catch (e) {} } /***/ }), -/* 210 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +/* 222 */ +/***/ (function(module) { "use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ +var DLList; +DLList = class DLList { + constructor(incr, decr) { + this.incr = incr; + this.decr = decr; + this._first = null; + this._last = null; + this.length = 0; + } -/** - * Module dependencies. - */ + push(value) { + var node; + this.length++; -var merge = __webpack_require__(707) -var parseUrl = __webpack_require__(981); -var qs = __webpack_require__(386); + if (typeof this.incr === "function") { + this.incr(); + } -/** - * @param {Object} options - * @return {Function} - * @api public - */ + node = { + value, + prev: this._last, + next: null + }; -module.exports = function query(options) { - var opts = merge({}, options) - var queryparse = qs.parse; + if (this._last != null) { + this._last.next = node; + this._last = node; + } else { + this._first = this._last = node; + } - if (typeof options === 'function') { - queryparse = options; - opts = undefined; + return void 0; } - if (opts !== undefined && opts.allowPrototypes === undefined) { - // back-compat for qs module - opts.allowPrototypes = true; - } + shift() { + var value; - return function query(req, res, next){ - if (!req.query) { - var val = parseUrl(req).query; - req.query = queryparse(val, opts); - } + if (this._first == null) { + return; + } else { + this.length--; - next(); - }; -}; + if (typeof this.decr === "function") { + this.decr(); + } + } + value = this._first.value; -/***/ }), -/* 211 */ -/***/ (function(module) { + if ((this._first = this._first.next) != null) { + this._first.prev = null; + } else { + this._last = null; + } -module.exports = require("https"); + return value; + } -/***/ }), -/* 212 */ -/***/ (function(module) { + first() { + if (this._first != null) { + return this._first.value; + } + } -"use strict"; + getArray() { + var node, ref, results; + node = this._first; + results = []; + while (node != null) { + results.push((ref = node, node = node.next, ref.value)); + } -var BottleneckError; -BottleneckError = class BottleneckError extends Error {}; -module.exports = BottleneckError; + return results; + } + + forEachShift(cb) { + var node; + node = this.shift(); + + while (node != null) { + cb(node), node = this.shift(); + } + + return void 0; + } + + debug() { + var node, ref, ref1, ref2, results; + node = this._first; + results = []; + + while (node != null) { + results.push((ref = node, node = node.next, { + value: ref.value, + prev: (ref1 = ref.prev) != null ? ref1.value : void 0, + next: (ref2 = ref.next) != null ? ref2.value : void 0 + })); + } + + return results; + } + +}; +module.exports = DLList; /***/ }), -/* 213 */, -/* 214 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +/* 223 */, +/* 224 */, +/* 225 */, +/* 226 */ +/***/ (function(module, exports, __webpack_require__) { "use strict"; -const SentryStream = __webpack_require__(860); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; -module.exports = defaultSetup; -module.exports.SentryStream = SentryStream; +var _v = _interopRequireDefault(__webpack_require__(806)); -// // // +var _sha = _interopRequireDefault(__webpack_require__(944)); -/** - * Default module function - * @param {Object} client Sentry client - * @param {String} level Bunyan level - * @return {Object} Bunyan stream with embedded Sentry steam - */ -function defaultSetup(client, level) { - return { - stream: new SentryStream(client), - type: 'raw', - level: level || 'warn' - }; -} +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +const v5 = (0, _v.default)('v5', 0x50, _sha.default); +var _default = v5; +exports.default = _default; +module.exports = exports.default; /***/ }), -/* 215 */ +/* 227 */ /***/ (function(module, __unusedexports, __webpack_require__) { "use strict"; -/* eslint-disable node/no-deprecated-api */ +/*! + * accepts + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ -var buffer = __webpack_require__(293) -var Buffer = buffer.Buffer +/** + * Module dependencies. + * @private + */ -var safer = {} +var Negotiator = __webpack_require__(34) +var mime = __webpack_require__(779) -var key +/** + * Module exports. + * @public + */ -for (key in buffer) { - if (!buffer.hasOwnProperty(key)) continue - if (key === 'SlowBuffer' || key === 'Buffer') continue - safer[key] = buffer[key] -} +module.exports = Accepts -var Safer = safer.Buffer = {} -for (key in Buffer) { - if (!Buffer.hasOwnProperty(key)) continue - if (key === 'allocUnsafe' || key === 'allocUnsafeSlow') continue - Safer[key] = Buffer[key] +/** + * Create a new Accepts object for the given req. + * + * @param {object} req + * @public + */ + +function Accepts (req) { + if (!(this instanceof Accepts)) { + return new Accepts(req) + } + + this.headers = req.headers + this.negotiator = new Negotiator(req) } -safer.Buffer.prototype = Buffer.prototype +/** + * Check if the given `type(s)` is acceptable, returning + * the best match when true, otherwise `undefined`, in which + * case you should respond with 406 "Not Acceptable". + * + * The `type` value may be a single mime type string + * such as "application/json", the extension name + * such as "json" or an array `["json", "html", "text/plain"]`. When a list + * or array is given the _best_ match, if any is returned. + * + * Examples: + * + * // Accept: text/html + * this.types('html'); + * // => "html" + * + * // Accept: text/*, application/json + * this.types('html'); + * // => "html" + * this.types('text/html'); + * // => "text/html" + * this.types('json', 'text'); + * // => "json" + * this.types('application/json'); + * // => "application/json" + * + * // Accept: text/*, application/json + * this.types('image/png'); + * this.types('png'); + * // => undefined + * + * // Accept: text/*;q=.5, application/json + * this.types(['html', 'json']); + * this.types('html', 'json'); + * // => "json" + * + * @param {String|Array} types... + * @return {String|Array|Boolean} + * @public + */ -if (!Safer.from || Safer.from === Uint8Array.from) { - Safer.from = function (value, encodingOrOffset, length) { - if (typeof value === 'number') { - throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof value) - } - if (value && typeof value.length === 'undefined') { - throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type ' + typeof value) +Accepts.prototype.type = +Accepts.prototype.types = function (types_) { + var types = types_ + + // support flattened arguments + if (types && !Array.isArray(types)) { + types = new Array(arguments.length) + for (var i = 0; i < types.length; i++) { + types[i] = arguments[i] } - return Buffer(value, encodingOrOffset, length) } + + // no types, return all requested types + if (!types || types.length === 0) { + return this.negotiator.mediaTypes() + } + + // no accept header, return first given type + if (!this.headers.accept) { + return types[0] + } + + var mimes = types.map(extToMime) + var accepts = this.negotiator.mediaTypes(mimes.filter(validMime)) + var first = accepts[0] + + return first + ? types[mimes.indexOf(first)] + : false } -if (!Safer.alloc) { - Safer.alloc = function (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size) - } - if (size < 0 || size >= 2 * (1 << 30)) { - throw new RangeError('The value "' + size + '" is invalid for option "size"') - } - var buf = Buffer(size) - if (!fill || fill.length === 0) { - buf.fill(0) - } else if (typeof encoding === 'string') { - buf.fill(fill, encoding) - } else { - buf.fill(fill) +/** + * Return accepted encodings or best fit based on `encodings`. + * + * Given `Accept-Encoding: gzip, deflate` + * an array sorted by quality is returned: + * + * ['gzip', 'deflate'] + * + * @param {String|Array} encodings... + * @return {String|Array} + * @public + */ + +Accepts.prototype.encoding = +Accepts.prototype.encodings = function (encodings_) { + var encodings = encodings_ + + // support flattened arguments + if (encodings && !Array.isArray(encodings)) { + encodings = new Array(arguments.length) + for (var i = 0; i < encodings.length; i++) { + encodings[i] = arguments[i] } - return buf } + + // no encodings, return all requested encodings + if (!encodings || encodings.length === 0) { + return this.negotiator.encodings() + } + + return this.negotiator.encodings(encodings)[0] || false } -if (!safer.kStringMaxLength) { - try { - safer.kStringMaxLength = process.binding('buffer').kStringMaxLength - } catch (e) { - // we can't determine kStringMaxLength in environments where process.binding - // is unsupported, so let's not set it +/** + * Return accepted charsets or best fit based on `charsets`. + * + * Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5` + * an array sorted by quality is returned: + * + * ['utf-8', 'utf-7', 'iso-8859-1'] + * + * @param {String|Array} charsets... + * @return {String|Array} + * @public + */ + +Accepts.prototype.charset = +Accepts.prototype.charsets = function (charsets_) { + var charsets = charsets_ + + // support flattened arguments + if (charsets && !Array.isArray(charsets)) { + charsets = new Array(arguments.length) + for (var i = 0; i < charsets.length; i++) { + charsets[i] = arguments[i] + } + } + + // no charsets, return all requested charsets + if (!charsets || charsets.length === 0) { + return this.negotiator.charsets() } + + return this.negotiator.charsets(charsets)[0] || false } -if (!safer.constants) { - safer.constants = { - MAX_LENGTH: safer.kMaxLength +/** + * Return accepted languages or best fit based on `langs`. + * + * Given `Accept-Language: en;q=0.8, es, pt` + * an array sorted by quality is returned: + * + * ['es', 'pt', 'en'] + * + * @param {String|Array} langs... + * @return {Array|String} + * @public + */ + +Accepts.prototype.lang = +Accepts.prototype.langs = +Accepts.prototype.language = +Accepts.prototype.languages = function (languages_) { + var languages = languages_ + + // support flattened arguments + if (languages && !Array.isArray(languages)) { + languages = new Array(arguments.length) + for (var i = 0; i < languages.length; i++) { + languages[i] = arguments[i] + } } - if (safer.kStringMaxLength) { - safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength + + // no languages, return all requested languages + if (!languages || languages.length === 0) { + return this.negotiator.languages() } + + return this.negotiator.languages(languages)[0] || false } -module.exports = safer +/** + * Convert extnames to mime. + * + * @param {String} type + * @return {String} + * @private + */ + +function extToMime (type) { + return type.indexOf('/') === -1 + ? mime.lookup(type) + : type +} + +/** + * Check if mime is valid. + * + * @param {String} type + * @return {String} + * @private + */ + +function validMime (type) { + return typeof type === 'string' +} /***/ }), -/* 216 */ +/* 228 */ /***/ (function(module, __unusedexports, __webpack_require__) { -module.exports = sign +"use strict"; -const crypto = __webpack_require__(417) -function sign (secret, payload) { - if (!secret || !payload) { - throw new TypeError('secret & payload required') - } +var Type = __webpack_require__(945); + +function resolveYamlBoolean(data) { + if (data === null) return false; + + var max = data.length; - payload = typeof payload === 'string' ? payload : toNormalizedJsonString(payload) - return 'sha1=' + crypto.createHmac('sha1', secret).update(payload).digest('hex') + return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || + (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')); } -function toNormalizedJsonString (payload) { - return JSON.stringify(payload).replace(/[^\\]\\u[\da-f]{4}/g, s => { - return s.substr(0, 3) + s.substr(3).toUpperCase() - }) +function constructYamlBoolean(data) { + return data === 'true' || + data === 'True' || + data === 'TRUE'; +} + +function isBoolean(object) { + return Object.prototype.toString.call(object) === '[object Boolean]'; } +module.exports = new Type('tag:yaml.org,2002:bool', { + kind: 'scalar', + resolve: resolveYamlBoolean, + construct: constructYamlBoolean, + predicate: isBoolean, + represent: { + lowercase: function (object) { return object ? 'true' : 'false'; }, + uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; }, + camelcase: function (object) { return object ? 'True' : 'False'; } + }, + defaultStyle: 'lowercase' +}); + /***/ }), -/* 217 */, -/* 218 */ +/* 229 */ +/***/ (function(module) { + +module.exports = require("domain"); + +/***/ }), +/* 230 */ /***/ (function(module) { "use strict"; -/** - * Custom implementation of a double ended queue. - */ -function Denque(array) { - this._head = 0; - this._tail = 0; - this._capacityMask = 0x3; - this._list = new Array(4); - if (Array.isArray(array)) { - this._fromArray(array); - } +const setLevelSym = Symbol('pino.setLevel') +const getLevelSym = Symbol('pino.getLevel') +const levelValSym = Symbol('pino.levelVal') +const useLevelLabelsSym = Symbol('pino.useLevelLabels') +const useOnlyCustomLevelsSym = Symbol('pino.useOnlyCustomLevels') +const mixinSym = Symbol('pino.mixin') + +const lsCacheSym = Symbol('pino.lsCache') +const chindingsSym = Symbol('pino.chindings') +const parsedChindingsSym = Symbol('pino.parsedChindings') + +const asJsonSym = Symbol('pino.asJson') +const writeSym = Symbol('pino.write') +const redactFmtSym = Symbol('pino.redactFmt') + +const timeSym = Symbol('pino.time') +const timeSliceIndexSym = Symbol('pino.timeSliceIndex') +const streamSym = Symbol('pino.stream') +const stringifySym = Symbol('pino.stringify') +const stringifiersSym = Symbol('pino.stringifiers') +const endSym = Symbol('pino.end') +const formatOptsSym = Symbol('pino.formatOpts') +const messageKeySym = Symbol('pino.messageKey') +const nestedKeySym = Symbol('pino.nestedKey') + +const wildcardFirstSym = Symbol('pino.wildcardFirst') + +// public symbols, no need to use the same pino +// version for these +const serializersSym = Symbol.for('pino.serializers') +const formattersSym = Symbol.for('pino.formatters') +const hooksSym = Symbol.for('pino.hooks') +const needsMetadataGsym = Symbol.for('pino.metadata') + +module.exports = { + setLevelSym, + getLevelSym, + levelValSym, + useLevelLabelsSym, + mixinSym, + lsCacheSym, + chindingsSym, + parsedChindingsSym, + asJsonSym, + writeSym, + serializersSym, + redactFmtSym, + timeSym, + timeSliceIndexSym, + streamSym, + stringifySym, + stringifiersSym, + endSym, + formatOptsSym, + messageKeySym, + nestedKeySym, + wildcardFirstSym, + needsMetadataGsym, + useOnlyCustomLevelsSym, + formattersSym, + hooksSym } -/** - * ------------- - * PUBLIC API - * ------------- - */ -/** - * Returns the item at the specified index from the list. - * 0 is the first element, 1 is the second, and so on... - * Elements at negative values are that many from the end: -1 is one before the end - * (the last element), -2 is two before the end (one before last), etc. - * @param index - * @returns {*} - */ -Denque.prototype.peekAt = function peekAt(index) { - var i = index; - // expect a number or return undefined - if ((i !== (i | 0))) { - return void 0; - } - var len = this.size(); - if (i >= len || i < -len) return undefined; - if (i < 0) i += len; - i = (this._head + i) & this._capacityMask; - return this._list[i]; -}; +/***/ }), +/* 231 */ +/***/ (function(module, __unusedexports, __webpack_require__) { -/** - * Alias for peakAt() - * @param i - * @returns {*} +"use strict"; +/*! + * depd + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed */ -Denque.prototype.get = function get(i) { - return this.peekAt(i); -}; -/** - * Returns the first item in the list without removing it. - * @returns {*} - */ -Denque.prototype.peek = function peek() { - if (this._head === this._tail) return undefined; - return this._list[this._head]; -}; -/** - * Alias for peek() - * @returns {*} - */ -Denque.prototype.peekFront = function peekFront() { - return this.peek(); -}; /** - * Returns the item that is at the back of the queue without removing it. - * Uses peekAt(-1) + * Module dependencies. + * @private */ -Denque.prototype.peekBack = function peekBack() { - return this.peekAt(-1); -}; + +var EventEmitter = __webpack_require__(614).EventEmitter /** - * Returns the current length of the queue - * @return {Number} + * Module exports. + * @public */ -Object.defineProperty(Denque.prototype, 'length', { - get: function length() { - return this.size(); + +lazyProperty(module.exports, 'callSiteToString', function callSiteToString () { + var limit = Error.stackTraceLimit + var obj = {} + var prep = Error.prepareStackTrace + + function prepareObjectStackTrace (obj, stack) { + return stack } -}); -/** - * Return the number of items on the list, or 0 if empty. - * @returns {number} - */ -Denque.prototype.size = function size() { - if (this._head === this._tail) return 0; - if (this._head < this._tail) return this._tail - this._head; - else return this._capacityMask + 1 - (this._head - this._tail); -}; + Error.prepareStackTrace = prepareObjectStackTrace + Error.stackTraceLimit = 2 + + // capture the stack + Error.captureStackTrace(obj) + + // slice the stack + var stack = obj.stack.slice() + + Error.prepareStackTrace = prep + Error.stackTraceLimit = limit + + return stack[0].toString ? toString : __webpack_require__(265) +}) + +lazyProperty(module.exports, 'eventListenerCount', function eventListenerCount () { + return EventEmitter.listenerCount || __webpack_require__(4) +}) /** - * Add an item at the beginning of the list. - * @param item + * Define a lazy property. */ -Denque.prototype.unshift = function unshift(item) { - if (item === undefined) return this.size(); - var len = this._list.length; - this._head = (this._head - 1 + len) & this._capacityMask; - this._list[this._head] = item; - if (this._tail === this._head) this._growArray(); - if (this._head < this._tail) return this._tail - this._head; - else return this._capacityMask + 1 - (this._head - this._tail); -}; -/** - * Remove and return the first item on the list, - * Returns undefined if the list is empty. - * @returns {*} - */ -Denque.prototype.shift = function shift() { - var head = this._head; - if (head === this._tail) return undefined; - var item = this._list[head]; - this._list[head] = undefined; - this._head = (head + 1) & this._capacityMask; - if (head < 2 && this._tail > 10000 && this._tail <= this._list.length >>> 2) this._shrinkArray(); - return item; -}; +function lazyProperty (obj, prop, getter) { + function get () { + var val = getter() -/** - * Add an item to the bottom of the list. - * @param item - */ -Denque.prototype.push = function push(item) { - if (item === undefined) return this.size(); - var tail = this._tail; - this._list[tail] = item; - this._tail = (tail + 1) & this._capacityMask; - if (this._tail === this._head) { - this._growArray(); + Object.defineProperty(obj, prop, { + configurable: true, + enumerable: true, + value: val + }) + + return val } - if (this._head < this._tail) return this._tail - this._head; - else return this._capacityMask + 1 - (this._head - this._tail); -}; + Object.defineProperty(obj, prop, { + configurable: true, + enumerable: true, + get: get + }) +} /** - * Remove and return the last item on the list. - * Returns undefined if the list is empty. - * @returns {*} + * Call toString() on the obj */ -Denque.prototype.pop = function pop() { - var tail = this._tail; - if (tail === this._head) return undefined; - var len = this._list.length; - this._tail = (tail - 1 + len) & this._capacityMask; - var item = this._list[this._tail]; - this._list[this._tail] = undefined; - if (this._head < 2 && tail > 10000 && tail <= len >>> 2) this._shrinkArray(); - return item; -}; -/** - * Remove and return the item at the specified index from the list. - * Returns undefined if the list is empty. - * @param index - * @returns {*} - */ -Denque.prototype.removeOne = function removeOne(index) { - var i = index; - // expect a number or return undefined - if ((i !== (i | 0))) { - return void 0; +function toString (obj) { + return obj.toString() +} + + +/***/ }), +/* 232 */, +/* 233 */ +/***/ (function(module, exports, __webpack_require__) { + +/* eslint-disable node/no-deprecated-api */ +var buffer = __webpack_require__(293) +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] } - if (this._head === this._tail) return void 0; - var size = this.size(); - var len = this._list.length; - if (i >= size || i < -size) return void 0; - if (i < 0) i += size; - i = (this._head + i) & this._capacityMask; - var item = this._list[i]; - var k; - if (index < size / 2) { - for (k = index; k > 0; k--) { - this._list[i] = this._list[i = (i - 1 + len) & this._capacityMask]; +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) } - this._list[i] = void 0; - this._head = (this._head + 1 + len) & this._capacityMask; } else { - for (k = size - 1 - index; k > 0; k--) { - this._list[i] = this._list[i = ( i + 1 + len) & this._capacityMask]; - } - this._list[i] = void 0; - this._tail = (this._tail - 1 + len) & this._capacityMask; + buf.fill(0) } - return item; -}; + return buf +} -/** - * Remove number of items from the specified index from the list. - * Returns array of removed items. - * Returns undefined if the list is empty. - * @param index - * @param count - * @returns {array} - */ -Denque.prototype.remove = function remove(index, count) { - var i = index; - var removed; - var del_count = count; - // expect a number or return undefined - if ((i !== (i | 0))) { - return void 0; +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') } - if (this._head === this._tail) return void 0; - var size = this.size(); - var len = this._list.length; - if (i >= size || i < -size || count < 1) return void 0; - if (i < 0) i += size; - if (count === 1 || !count) { - removed = new Array(1); - removed[0] = this.removeOne(i); - return removed; + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') } - if (i === 0 && i + count >= size) { - removed = this.toArray(); - this.clear(); - return removed; + return buffer.SlowBuffer(size) +} + + +/***/ }), +/* 234 */, +/* 235 */, +/* 236 */, +/* 237 */, +/* 238 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. + +/**/ + +var objectKeys = Object.keys || function (obj) { + var keys = []; + + for (var key in obj) { + keys.push(key); } - if (i + count > size) count = size - i; - var k; - removed = new Array(count); - for (k = 0; k < count; k++) { - removed[k] = this._list[(this._head + i + k) & this._capacityMask]; + + return keys; +}; +/**/ + + +module.exports = Duplex; + +var Readable = __webpack_require__(786); + +var Writable = __webpack_require__(290); + +__webpack_require__(689)(Duplex, Readable); + +{ + // Allow the keys array to be GC'ed. + var keys = objectKeys(Writable.prototype); + + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; } - i = (this._head + i) & this._capacityMask; - if (index + count === size) { - this._tail = (this._tail - count + len) & this._capacityMask; - for (k = count; k > 0; k--) { - this._list[i = (i + 1 + len) & this._capacityMask] = void 0; +} + +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + Readable.call(this, options); + Writable.call(this, options); + this.allowHalfOpen = true; + + if (options) { + if (options.readable === false) this.readable = false; + if (options.writable === false) this.writable = false; + + if (options.allowHalfOpen === false) { + this.allowHalfOpen = false; + this.once('end', onend); } - return removed; } - if (index === 0) { - this._head = (this._head + count + len) & this._capacityMask; - for (k = count - 1; k > 0; k--) { - this._list[i = (i + 1 + len) & this._capacityMask] = void 0; - } - return removed; +} + +Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; } - if (i < size / 2) { - this._head = (this._head + index + count + len) & this._capacityMask; - for (k = index; k > 0; k--) { - this.unshift(this._list[i = (i - 1 + len) & this._capacityMask]); - } - i = (this._head - 1 + len) & this._capacityMask; - while (del_count > 0) { - this._list[i = (i - 1 + len) & this._capacityMask] = void 0; - del_count--; - } - if (index < 0) this._tail = i; - } else { - this._tail = i; - i = (i + count + len) & this._capacityMask; - for (k = size - (count + index); k > 0; k--) { - this.push(this._list[i++]); +}); +Object.defineProperty(Duplex.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } +}); +Object.defineProperty(Duplex.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } +}); // the no-half-open enforcer + +function onend() { + // If the writable side ended, then we're ok. + if (this._writableState.ended) return; // no more data can be written. + // But allow more writes to happen in this tick. + + process.nextTick(onEndNT, this); +} + +function onEndNT(self) { + self.end(); +} + +Object.defineProperty(Duplex.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined || this._writableState === undefined) { + return false; } - i = this._tail; - while (del_count > 0) { - this._list[i = (i + 1 + len) & this._capacityMask] = void 0; - del_count--; + + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed + + + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } +}); + +/***/ }), +/* 239 */ +/***/ (function(module) { + +"use strict"; + + +module.exports = { + groupRedact, + groupRestore, + nestedRedact, + nestedRestore +} + +function groupRestore ({ keys, values, target }) { + if (target == null) return + const length = keys.length + for (var i = 0; i < length; i++) { + const k = keys[i] + target[k] = values[i] + } +} + +function groupRedact (o, path, censor, isCensorFct) { + const target = get(o, path) + if (target == null) return { keys: null, values: null, target: null, flat: true } + const keys = Object.keys(target) + const length = keys.length + const values = new Array(length) + for (var i = 0; i < length; i++) { + const k = keys[i] + values[i] = target[k] + target[k] = isCensorFct ? censor(target[k]) : censor + } + return { keys, values, target, flat: true } +} + +function nestedRestore (arr) { + const length = arr.length + for (var i = 0; i < length; i++) { + const { key, target, value } = arr[i] + target[key] = value + } +} + +function nestedRedact (store, o, path, ns, censor, isCensorFct) { + const target = get(o, path) + if (target == null) return + const keys = Object.keys(target) + const length = keys.length + for (var i = 0; i < length; i++) { + const key = keys[i] + const { value, parent, exists } = specialSet(target, key, ns, censor, isCensorFct) + + if (exists === true && parent !== null) { + store.push({ key: ns[ns.length - 1], target: parent, value }) } } - if (this._head < 2 && this._tail > 10000 && this._tail <= len >>> 2) this._shrinkArray(); - return removed; -}; + return store +} -/** - * Native splice implementation. - * Remove number of items from the specified index from the list and/or add new elements. - * Returns array of removed items or empty array if count == 0. - * Returns undefined if the list is empty. - * - * @param index - * @param count - * @param {...*} [elements] - * @returns {array} - */ -Denque.prototype.splice = function splice(index, count) { - var i = index; - // expect a number or return undefined - if ((i !== (i | 0))) { - return void 0; +function has (obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop) +} + +function specialSet (o, k, p, v, f) { + var i = -1 + var l = p.length + var li = l - 1 + var n + var nv + var ov + var oov = null + var exists = true + ov = n = o[k] + if (typeof n !== 'object') return { value: null, parent: null, exists } + while (n != null && ++i < l) { + k = p[i] + oov = ov + if (!(k in n)) { + exists = false + break + } + ov = n[k] + nv = f ? v(ov) : v + nv = (i !== li) ? ov : nv + n[k] = (has(n, k) && nv === ov) || (nv === undefined && v !== undefined) ? n[k] : nv + n = n[k] + if (typeof n !== 'object') break } - var size = this.size(); - if (i < 0) i += size; - if (i > size) return void 0; - if (arguments.length > 2) { - var k; - var temp; - var removed; - var arg_len = arguments.length; - var len = this._list.length; - var arguments_index = 2; - if (!size || i < size / 2) { - temp = new Array(i); - for (k = 0; k < i; k++) { - temp[k] = this._list[(this._head + k) & this._capacityMask]; + return { value: ov, parent: oov, exists } +} +function get (o, p) { + var i = -1 + var l = p.length + var n = o + while (n != null && ++i < l) { + n = n[p[i]] + } + return n +} + + +/***/ }), +/* 240 */, +/* 241 */, +/* 242 */ +/***/ (function(module) { + +"use strict"; + // undocumented cb() API, needed for core, not for public API + +function destroy(err, cb) { + var _this = this; + + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err) { + if (!this._writableState) { + process.nextTick(emitErrorNT, this, err); + } else if (!this._writableState.errorEmitted) { + this._writableState.errorEmitted = true; + process.nextTick(emitErrorNT, this, err); } - if (count === 0) { - removed = []; - if (i > 0) { - this._head = (this._head + i + len) & this._capacityMask; - } + } + + return this; + } // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks + + + if (this._readableState) { + this._readableState.destroyed = true; + } // if this is a duplex stream mark the writable part as destroyed as well + + + if (this._writableState) { + this._writableState.destroyed = true; + } + + this._destroy(err || null, function (err) { + if (!cb && err) { + if (!_this._writableState) { + process.nextTick(emitErrorAndCloseNT, _this, err); + } else if (!_this._writableState.errorEmitted) { + _this._writableState.errorEmitted = true; + process.nextTick(emitErrorAndCloseNT, _this, err); } else { - removed = this.remove(i, count); - this._head = (this._head + i + len) & this._capacityMask; - } - while (arg_len > arguments_index) { - this.unshift(arguments[--arg_len]); - } - for (k = i; k > 0; k--) { - this.unshift(temp[k - 1]); + process.nextTick(emitCloseNT, _this); } + } else if (cb) { + process.nextTick(emitCloseNT, _this); + cb(err); } else { - temp = new Array(size - (i + count)); - var leng = temp.length; - for (k = 0; k < leng; k++) { - temp[k] = this._list[(this._head + i + count + k) & this._capacityMask]; - } - if (count === 0) { - removed = []; - if (i != size) { - this._tail = (this._head + i + len) & this._capacityMask; - } - } else { - removed = this.remove(i, count); - this._tail = (this._tail - leng + len) & this._capacityMask; - } - while (arguments_index < arg_len) { - this.push(arguments[arguments_index++]); - } - for (k = 0; k < leng; k++) { - this.push(temp[k]); - } + process.nextTick(emitCloseNT, _this); } - return removed; - } else { - return this.remove(i, count); - } -}; - -/** - * Soft clear - does not reset capacity. - */ -Denque.prototype.clear = function clear() { - this._head = 0; - this._tail = 0; -}; - -/** - * Returns true or false whether the list is empty. - * @returns {boolean} - */ -Denque.prototype.isEmpty = function isEmpty() { - return this._head === this._tail; -}; + }); -/** - * Returns an array of all queue items. - * @returns {Array} - */ -Denque.prototype.toArray = function toArray() { - return this._copyArray(false); -}; + return this; +} -/** - * ------------- - * INTERNALS - * ------------- - */ +function emitErrorAndCloseNT(self, err) { + emitErrorNT(self, err); + emitCloseNT(self); +} -/** - * Fills the queue with items from an array - * For use in the constructor - * @param array - * @private - */ -Denque.prototype._fromArray = function _fromArray(array) { - for (var i = 0; i < array.length; i++) this.push(array[i]); -}; +function emitCloseNT(self) { + if (self._writableState && !self._writableState.emitClose) return; + if (self._readableState && !self._readableState.emitClose) return; + self.emit('close'); +} -/** - * - * @param fullCopy - * @returns {Array} - * @private - */ -Denque.prototype._copyArray = function _copyArray(fullCopy) { - var newArray = []; - var list = this._list; - var len = list.length; - var i; - if (fullCopy || this._head > this._tail) { - for (i = this._head; i < len; i++) newArray.push(list[i]); - for (i = 0; i < this._tail; i++) newArray.push(list[i]); - } else { - for (i = this._head; i < this._tail; i++) newArray.push(list[i]); +function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; } - return newArray; -}; -/** - * Grows the internal list array. - * @private - */ -Denque.prototype._growArray = function _growArray() { - if (this._head) { - // copy existing data, head to end, then beginning to tail. - this._list = this._copyArray(true); - this._head = 0; + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finalCalled = false; + this._writableState.prefinished = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; } +} - // head is at 0 and array is now full, safe to extend - this._tail = this._list.length; +function emitErrorNT(self, err) { + self.emit('error', err); +} - this._list.length *= 2; - this._capacityMask = (this._capacityMask << 1) | 1; +function errorOrDestroy(stream, err) { + // We have tests that rely on errors being emitted + // in the same tick, so changing this is semver major. + // For now when you opt-in to autoDestroy we allow + // the error to be emitted nextTick. In a future + // semver major update we should change the default to this. + var rState = stream._readableState; + var wState = stream._writableState; + if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); +} + +module.exports = { + destroy: destroy, + undestroy: undestroy, + errorOrDestroy: errorOrDestroy }; +/***/ }), +/* 243 */, +/* 244 */, +/* 245 */, +/* 246 */ +/***/ (function(module, exports) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + /** - * Shrinks the internal list array. - * @private + * Convert array of 16 byte values to UUID string format of the form: + * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX */ -Denque.prototype._shrinkArray = function _shrinkArray() { - this._list.length >>>= 1; - this._capacityMask >>>= 1; -}; +var byteToHex = []; +for (var i = 0; i < 256; ++i) { + byteToHex[i] = (i + 0x100).toString(16).substr(1); +} -module.exports = Denque; +function bytesToUuid(buf, offset) { + var i = offset || 0; + var bth = byteToHex; // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4 + + return [bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]]].join(''); +} +var _default = bytesToUuid; +exports.default = _default; +module.exports = exports.default; /***/ }), -/* 219 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { +/* 247 */ +/***/ (function(module, __unusedexports, __webpack_require__) { "use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const net_1 = __webpack_require__(631); -const tls_1 = __webpack_require__(16); -const utils_1 = __webpack_require__(200); -const AbstractConnector_1 = __webpack_require__(888); -function isIIpcConnectionOptions(value) { - return value.path; +const os = __webpack_require__(87); +const tty = __webpack_require__(867); +const hasFlag = __webpack_require__(364); + +const {env} = process; + +let forceColor; +if (hasFlag('no-color') || + hasFlag('no-colors') || + hasFlag('color=false') || + hasFlag('color=never')) { + forceColor = 0; +} else if (hasFlag('color') || + hasFlag('colors') || + hasFlag('color=true') || + hasFlag('color=always')) { + forceColor = 1; } -exports.isIIpcConnectionOptions = isIIpcConnectionOptions; -class StandaloneConnector extends AbstractConnector_1.default { - constructor(options) { - super(); - this.options = options; - } - connect(_) { - const { options } = this; - this.connecting = true; - let connectionOptions; - if (isIIpcConnectionOptions(options)) { - connectionOptions = { - path: options.path, - }; - } - else { - connectionOptions = {}; - if (options.port != null) { - connectionOptions.port = options.port; - } - if (options.host != null) { - connectionOptions.host = options.host; - } - if (options.family != null) { - connectionOptions.family = options.family; - } - } - if (options.tls) { - Object.assign(connectionOptions, options.tls); - } - // TODO: - // We use native Promise here since other Promise - // implementation may use different schedulers that - // cause issue when the stream is resolved in the - // next tick. - // Should use the provided promise in the next major - // version and do not connect before resolved. - return new Promise((resolve, reject) => { - process.nextTick(() => { - if (!this.connecting) { - reject(new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG)); - return; - } - try { - if (options.tls) { - this.stream = tls_1.connect(connectionOptions); - } - else { - this.stream = net_1.createConnection(connectionOptions); - } - } - catch (err) { - reject(err); - return; - } - resolve(this.stream); - }); - }); - } + +if ('FORCE_COLOR' in env) { + if (env.FORCE_COLOR === 'true') { + forceColor = 1; + } else if (env.FORCE_COLOR === 'false') { + forceColor = 0; + } else { + forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3); + } } -exports.default = StandaloneConnector; +function translateLevel(level) { + if (level === 0) { + return false; + } -/***/ }), -/* 220 */, -/* 221 */ -/***/ (function(module, exports, __webpack_require__) { + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; +} -/** - * This is the web browser implementation of `debug()`. - * - * Expose `debug()` as the module. - */ +function supportsColor(haveStream, streamIsTTY) { + if (forceColor === 0) { + return 0; + } -exports = module.exports = __webpack_require__(354); -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = 'undefined' != typeof chrome - && 'undefined' != typeof chrome.storage - ? chrome.storage.local - : localstorage(); + if (hasFlag('color=16m') || + hasFlag('color=full') || + hasFlag('color=truecolor')) { + return 3; + } -/** - * Colors. - */ + if (hasFlag('color=256')) { + return 2; + } -exports.colors = [ - 'lightseagreen', - 'forestgreen', - 'goldenrod', - 'dodgerblue', - 'darkorchid', - 'crimson' -]; + if (haveStream && !streamIsTTY && forceColor === undefined) { + return 0; + } -/** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors - */ + const min = forceColor || 0; -function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { - return true; - } + if (env.TERM === 'dumb') { + return min; + } - // is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || - // double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); -} + if (process.platform === 'win32') { + // Windows 10 build 10586 is the first Windows release that supports 256 colors. + // Windows 10 build 14931 is the first release that supports 16m/TrueColor. + const osRelease = os.release().split('.'); + if ( + Number(osRelease[0]) >= 10 && + Number(osRelease[2]) >= 10586 + ) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ + return 1; + } -exports.formatters.j = function(v) { - try { - return JSON.stringify(v); - } catch (err) { - return '[UnexpectedJSONParseError]: ' + err.message; - } -}; + if ('CI' in env) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') { + return 1; + } + return min; + } -/** - * Colorize log arguments if enabled. - * - * @api public - */ + if ('TEAMCITY_VERSION' in env) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; + } -function formatArgs(args) { - var useColors = this.useColors; + if ('GITHUB_ACTIONS' in env) { + return 1; + } - args[0] = (useColors ? '%c' : '') - + this.namespace - + (useColors ? ' %c' : ' ') - + args[0] - + (useColors ? '%c ' : ' ') - + '+' + exports.humanize(this.diff); + if (env.COLORTERM === 'truecolor') { + return 3; + } - if (!useColors) return; + if ('TERM_PROGRAM' in env) { + const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); - var c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit') + switch (env.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + case 'Apple_Terminal': + return 2; + // No default + } + } - // the final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - var index = 0; - var lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, function(match) { - if ('%%' === match) return; - index++; - if ('%c' === match) { - // we only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } - args.splice(lastC, 0, c); -} + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } -/** - * Invokes `console.log()` when available. - * No-op when `console.log` is not a "function". - * - * @api public - */ + if ('COLORTERM' in env) { + return 1; + } -function log() { - // this hackery is required for IE8/9, where - // the `console.log` function doesn't have 'apply' - return 'object' === typeof console - && console.log - && Function.prototype.apply.call(console.log, console, arguments); + return min; } -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ - -function save(namespaces) { - try { - if (null == namespaces) { - exports.storage.removeItem('debug'); - } else { - exports.storage.debug = namespaces; - } - } catch(e) {} +function getSupportLevel(stream) { + const level = supportsColor(stream, stream && stream.isTTY); + return translateLevel(level); } -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ - -function load() { - var r; - try { - r = exports.storage.debug; - } catch(e) {} +module.exports = { + supportsColor: getSupportLevel, + stdout: translateLevel(supportsColor(true, tty.isatty(1))), + stderr: translateLevel(supportsColor(true, tty.isatty(2))) +}; - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; - } - return r; -} +/***/ }), +/* 248 */, +/* 249 */, +/* 250 */ +/***/ (function(module, __unusedexports, __webpack_require__) { -/** - * Enable namespaces listed in `localStorage.debug` initially. - */ +var constants = __webpack_require__(721) -exports.enable(load()); +var origCwd = process.cwd +var cwd = null -/** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private - */ +var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform -function localstorage() { - try { - return window.localStorage; - } catch (e) {} +process.cwd = function() { + if (!cwd) + cwd = origCwd.call(process) + return cwd } +try { + process.cwd() +} catch (er) {} +var chdir = process.chdir +process.chdir = function(d) { + cwd = null + chdir.call(process, d) +} -/***/ }), -/* 222 */ -/***/ (function(module) { - -"use strict"; +module.exports = patch +function patch (fs) { + // (re-)implement some things that are known busted or missing. -var DLList; -DLList = class DLList { - constructor(incr, decr) { - this.incr = incr; - this.decr = decr; - this._first = null; - this._last = null; - this.length = 0; + // lchmod, broken prior to 0.6.2 + // back-port the fix here. + if (constants.hasOwnProperty('O_SYMLINK') && + process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { + patchLchmod(fs) } - push(value) { - var node; - this.length++; - - if (typeof this.incr === "function") { - this.incr(); - } + // lutimes implementation, or no-op + if (!fs.lutimes) { + patchLutimes(fs) + } - node = { - value, - prev: this._last, - next: null - }; + // https://github.com/isaacs/node-graceful-fs/issues/4 + // Chown should not fail on einval or eperm if non-root. + // It should not fail on enosys ever, as this just indicates + // that a fs doesn't support the intended operation. - if (this._last != null) { - this._last.next = node; - this._last = node; - } else { - this._first = this._last = node; - } + fs.chown = chownFix(fs.chown) + fs.fchown = chownFix(fs.fchown) + fs.lchown = chownFix(fs.lchown) - return void 0; - } + fs.chmod = chmodFix(fs.chmod) + fs.fchmod = chmodFix(fs.fchmod) + fs.lchmod = chmodFix(fs.lchmod) - shift() { - var value; + fs.chownSync = chownFixSync(fs.chownSync) + fs.fchownSync = chownFixSync(fs.fchownSync) + fs.lchownSync = chownFixSync(fs.lchownSync) - if (this._first == null) { - return; - } else { - this.length--; + fs.chmodSync = chmodFixSync(fs.chmodSync) + fs.fchmodSync = chmodFixSync(fs.fchmodSync) + fs.lchmodSync = chmodFixSync(fs.lchmodSync) - if (typeof this.decr === "function") { - this.decr(); - } - } + fs.stat = statFix(fs.stat) + fs.fstat = statFix(fs.fstat) + fs.lstat = statFix(fs.lstat) - value = this._first.value; + fs.statSync = statFixSync(fs.statSync) + fs.fstatSync = statFixSync(fs.fstatSync) + fs.lstatSync = statFixSync(fs.lstatSync) - if ((this._first = this._first.next) != null) { - this._first.prev = null; - } else { - this._last = null; + // if lchmod/lchown do not exist, then make them no-ops + if (!fs.lchmod) { + fs.lchmod = function (path, mode, cb) { + if (cb) process.nextTick(cb) } - - return value; + fs.lchmodSync = function () {} } - - first() { - if (this._first != null) { - return this._first.value; + if (!fs.lchown) { + fs.lchown = function (path, uid, gid, cb) { + if (cb) process.nextTick(cb) } + fs.lchownSync = function () {} } - getArray() { - var node, ref, results; - node = this._first; - results = []; - - while (node != null) { - results.push((ref = node, node = node.next, ref.value)); - } + // on Windows, A/V software can lock the directory, causing this + // to fail with an EACCES or EPERM if the directory contains newly + // created files. Try again on failure, for up to 60 seconds. - return results; + // Set the timeout this long because some Windows Anti-Virus, such as Parity + // bit9, may lock files for up to a minute, causing npm package install + // failures. Also, take care to yield the scheduler. Windows scheduling gives + // CPU to a busy looping process, which can cause the program causing the lock + // contention to be starved of CPU by node, so the contention doesn't resolve. + if (platform === "win32") { + fs.rename = (function (fs$rename) { return function (from, to, cb) { + var start = Date.now() + var backoff = 0; + fs$rename(from, to, function CB (er) { + if (er + && (er.code === "EACCES" || er.code === "EPERM") + && Date.now() - start < 60000) { + setTimeout(function() { + fs.stat(to, function (stater, st) { + if (stater && stater.code === "ENOENT") + fs$rename(from, to, CB); + else + cb(er) + }) + }, backoff) + if (backoff < 100) + backoff += 10; + return; + } + if (cb) cb(er) + }) + }})(fs.rename) } - forEachShift(cb) { - var node; - node = this.shift(); - - while (node != null) { - cb(node), node = this.shift(); + // if read() returns EAGAIN, then just try it again. + fs.read = (function (fs$read) { + function read (fd, buffer, offset, length, position, callback_) { + var callback + if (callback_ && typeof callback_ === 'function') { + var eagCounter = 0 + callback = function (er, _, __) { + if (er && er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + return fs$read.call(fs, fd, buffer, offset, length, position, callback) + } + callback_.apply(this, arguments) + } + } + return fs$read.call(fs, fd, buffer, offset, length, position, callback) } - return void 0; - } - - debug() { - var node, ref, ref1, ref2, results; - node = this._first; - results = []; + // This ensures `util.promisify` works as it does for native `fs.read`. + read.__proto__ = fs$read + return read + })(fs.read) - while (node != null) { - results.push((ref = node, node = node.next, { - value: ref.value, - prev: (ref1 = ref.prev) != null ? ref1.value : void 0, - next: (ref2 = ref.next) != null ? ref2.value : void 0 - })); + fs.readSync = (function (fs$readSync) { return function (fd, buffer, offset, length, position) { + var eagCounter = 0 + while (true) { + try { + return fs$readSync.call(fs, fd, buffer, offset, length, position) + } catch (er) { + if (er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + continue + } + throw er + } } + }})(fs.readSync) - return results; - } - -}; -module.exports = DLList; - -/***/ }), -/* 223 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -var Symbol = __webpack_require__(498); - -/** Used to convert symbols to primitives and strings. */ -var symbolProto = Symbol ? Symbol.prototype : undefined, - symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; - -/** - * Creates a clone of the `symbol` object. - * - * @private - * @param {Object} symbol The symbol object to clone. - * @returns {Object} Returns the cloned symbol object. - */ -function cloneSymbol(symbol) { - return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; -} - -module.exports = cloneSymbol; - + function patchLchmod (fs) { + fs.lchmod = function (path, mode, callback) { + fs.open( path + , constants.O_WRONLY | constants.O_SYMLINK + , mode + , function (err, fd) { + if (err) { + if (callback) callback(err) + return + } + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + fs.fchmod(fd, mode, function (err) { + fs.close(fd, function(err2) { + if (callback) callback(err || err2) + }) + }) + }) + } -/***/ }), -/* 224 */, -/* 225 */, -/* 226 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { + fs.lchmodSync = function (path, mode) { + var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - * - * Based on the Base 64 VLQ implementation in Closure Compiler: - * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java - * - * Copyright 2011 The Closure Compiler Authors. All rights reserved. - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials provided - * with the distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -var base64 = __webpack_require__(947); - -// A single base 64 digit can contain 6 bits of data. For the base 64 variable -// length quantities we use in the source map spec, the first bit is the sign, -// the next four bits are the actual value, and the 6th bit is the -// continuation bit. The continuation bit tells us whether there are more -// digits in this value following this digit. -// -// Continuation -// | Sign -// | | -// V V -// 101011 + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + var threw = true + var ret + try { + ret = fs.fchmodSync(fd, mode) + threw = false + } finally { + if (threw) { + try { + fs.closeSync(fd) + } catch (er) {} + } else { + fs.closeSync(fd) + } + } + return ret + } + } -var VLQ_BASE_SHIFT = 5; + function patchLutimes (fs) { + if (constants.hasOwnProperty("O_SYMLINK")) { + fs.lutimes = function (path, at, mt, cb) { + fs.open(path, constants.O_SYMLINK, function (er, fd) { + if (er) { + if (cb) cb(er) + return + } + fs.futimes(fd, at, mt, function (er) { + fs.close(fd, function (er2) { + if (cb) cb(er || er2) + }) + }) + }) + } -// binary: 100000 -var VLQ_BASE = 1 << VLQ_BASE_SHIFT; + fs.lutimesSync = function (path, at, mt) { + var fd = fs.openSync(path, constants.O_SYMLINK) + var ret + var threw = true + try { + ret = fs.futimesSync(fd, at, mt) + threw = false + } finally { + if (threw) { + try { + fs.closeSync(fd) + } catch (er) {} + } else { + fs.closeSync(fd) + } + } + return ret + } -// binary: 011111 -var VLQ_BASE_MASK = VLQ_BASE - 1; + } else { + fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) } + fs.lutimesSync = function () {} + } + } -// binary: 100000 -var VLQ_CONTINUATION_BIT = VLQ_BASE; + function chmodFix (orig) { + if (!orig) return orig + return function (target, mode, cb) { + return orig.call(fs, target, mode, function (er) { + if (chownErOk(er)) er = null + if (cb) cb.apply(this, arguments) + }) + } + } -/** - * Converts from a two-complement value to a value where the sign bit is - * placed in the least significant bit. For example, as decimals: - * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) - * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) - */ -function toVLQSigned(aValue) { - return aValue < 0 - ? ((-aValue) << 1) + 1 - : (aValue << 1) + 0; -} + function chmodFixSync (orig) { + if (!orig) return orig + return function (target, mode) { + try { + return orig.call(fs, target, mode) + } catch (er) { + if (!chownErOk(er)) throw er + } + } + } -/** - * Converts to a two-complement value from a value where the sign bit is - * placed in the least significant bit. For example, as decimals: - * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 - * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 - */ -function fromVLQSigned(aValue) { - var isNegative = (aValue & 1) === 1; - var shifted = aValue >> 1; - return isNegative - ? -shifted - : shifted; -} -/** - * Returns the base 64 VLQ encoded value. - */ -exports.encode = function base64VLQ_encode(aValue) { - var encoded = ""; - var digit; + function chownFix (orig) { + if (!orig) return orig + return function (target, uid, gid, cb) { + return orig.call(fs, target, uid, gid, function (er) { + if (chownErOk(er)) er = null + if (cb) cb.apply(this, arguments) + }) + } + } - var vlq = toVLQSigned(aValue); + function chownFixSync (orig) { + if (!orig) return orig + return function (target, uid, gid) { + try { + return orig.call(fs, target, uid, gid) + } catch (er) { + if (!chownErOk(er)) throw er + } + } + } - do { - digit = vlq & VLQ_BASE_MASK; - vlq >>>= VLQ_BASE_SHIFT; - if (vlq > 0) { - // There are still more digits in this value, so we must make sure the - // continuation bit is marked. - digit |= VLQ_CONTINUATION_BIT; + function statFix (orig) { + if (!orig) return orig + // Older versions of Node erroneously returned signed integers for + // uid + gid. + return function (target, options, cb) { + if (typeof options === 'function') { + cb = options + options = null + } + function callback (er, stats) { + if (stats) { + if (stats.uid < 0) stats.uid += 0x100000000 + if (stats.gid < 0) stats.gid += 0x100000000 + } + if (cb) cb.apply(this, arguments) + } + return options ? orig.call(fs, target, options, callback) + : orig.call(fs, target, callback) } - encoded += base64.encode(digit); - } while (vlq > 0); + } - return encoded; -}; + function statFixSync (orig) { + if (!orig) return orig + // Older versions of Node erroneously returned signed integers for + // uid + gid. + return function (target, options) { + var stats = options ? orig.call(fs, target, options) + : orig.call(fs, target) + if (stats.uid < 0) stats.uid += 0x100000000 + if (stats.gid < 0) stats.gid += 0x100000000 + return stats; + } + } -/** - * Decodes the next base 64 VLQ value from the given string and returns the - * value and the rest of the string via the out parameter. - */ -exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { - var strLen = aStr.length; - var result = 0; - var shift = 0; - var continuation, digit; + // ENOSYS means that the fs doesn't support the op. Just ignore + // that, because it doesn't matter. + // + // if there's no getuid, or if getuid() is something other + // than 0, and the error is EINVAL or EPERM, then just ignore + // it. + // + // This specific case is a silent failure in cp, install, tar, + // and most other unix tools that manage permissions. + // + // When running as root, or if other types of errors are + // encountered, then it's strict. + function chownErOk (er) { + if (!er) + return true - do { - if (aIndex >= strLen) { - throw new Error("Expected more digits in base 64 VLQ value."); - } + if (er.code === "ENOSYS") + return true - digit = base64.decode(aStr.charCodeAt(aIndex++)); - if (digit === -1) { - throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); + var nonroot = !process.getuid || process.getuid() !== 0 + if (nonroot) { + if (er.code === "EINVAL" || er.code === "EPERM") + return true } - continuation = !!(digit & VLQ_CONTINUATION_BIT); - digit &= VLQ_BASE_MASK; - result = result + (digit << shift); - shift += VLQ_BASE_SHIFT; - } while (continuation); - - aOutParam.value = fromVLQSigned(result); - aOutParam.rest = aIndex; -}; + return false + } +} /***/ }), -/* 227 */ +/* 251 */ /***/ (function(module, __unusedexports, __webpack_require__) { "use strict"; /*! - * accepts - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2015 Douglas Christopher Wilson + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson * MIT Licensed */ @@ -14896,38660 +16005,40506 @@ exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { * @private */ -var Negotiator = __webpack_require__(34) -var mime = __webpack_require__(779) +var debug = __webpack_require__(590)('express:router:route'); +var flatten = __webpack_require__(211); +var Layer = __webpack_require__(322); +var methods = __webpack_require__(203); + +/** + * Module variables. + * @private + */ + +var slice = Array.prototype.slice; +var toString = Object.prototype.toString; /** * Module exports. * @public */ -module.exports = Accepts +module.exports = Route; /** - * Create a new Accepts object for the given req. + * Initialize `Route` with the given `path`, * - * @param {object} req + * @param {String} path * @public */ -function Accepts (req) { - if (!(this instanceof Accepts)) { - return new Accepts(req) - } +function Route(path) { + this.path = path; + this.stack = []; - this.headers = req.headers - this.negotiator = new Negotiator(req) + debug('new %o', path) + + // route handlers for various http methods + this.methods = {}; } /** - * Check if the given `type(s)` is acceptable, returning - * the best match when true, otherwise `undefined`, in which - * case you should respond with 406 "Not Acceptable". - * - * The `type` value may be a single mime type string - * such as "application/json", the extension name - * such as "json" or an array `["json", "html", "text/plain"]`. When a list - * or array is given the _best_ match, if any is returned. - * - * Examples: - * - * // Accept: text/html - * this.types('html'); - * // => "html" - * - * // Accept: text/*, application/json - * this.types('html'); - * // => "html" - * this.types('text/html'); - * // => "text/html" - * this.types('json', 'text'); - * // => "json" - * this.types('application/json'); - * // => "application/json" - * - * // Accept: text/*, application/json - * this.types('image/png'); - * this.types('png'); - * // => undefined - * - * // Accept: text/*;q=.5, application/json - * this.types(['html', 'json']); - * this.types('html', 'json'); - * // => "json" - * - * @param {String|Array} types... - * @return {String|Array|Boolean} - * @public + * Determine if the route handles a given method. + * @private */ -Accepts.prototype.type = -Accepts.prototype.types = function (types_) { - var types = types_ - - // support flattened arguments - if (types && !Array.isArray(types)) { - types = new Array(arguments.length) - for (var i = 0; i < types.length; i++) { - types[i] = arguments[i] - } +Route.prototype._handles_method = function _handles_method(method) { + if (this.methods._all) { + return true; } - // no types, return all requested types - if (!types || types.length === 0) { - return this.negotiator.mediaTypes() - } + var name = method.toLowerCase(); - // no accept header, return first given type - if (!this.headers.accept) { - return types[0] + if (name === 'head' && !this.methods['head']) { + name = 'get'; } - var mimes = types.map(extToMime) - var accepts = this.negotiator.mediaTypes(mimes.filter(validMime)) - var first = accepts[0] - - return first - ? types[mimes.indexOf(first)] - : false -} + return Boolean(this.methods[name]); +}; /** - * Return accepted encodings or best fit based on `encodings`. - * - * Given `Accept-Encoding: gzip, deflate` - * an array sorted by quality is returned: - * - * ['gzip', 'deflate'] - * - * @param {String|Array} encodings... - * @return {String|Array} - * @public + * @return {Array} supported HTTP methods + * @private */ -Accepts.prototype.encoding = -Accepts.prototype.encodings = function (encodings_) { - var encodings = encodings_ +Route.prototype._options = function _options() { + var methods = Object.keys(this.methods); - // support flattened arguments - if (encodings && !Array.isArray(encodings)) { - encodings = new Array(arguments.length) - for (var i = 0; i < encodings.length; i++) { - encodings[i] = arguments[i] - } + // append automatic head + if (this.methods.get && !this.methods.head) { + methods.push('head'); } - // no encodings, return all requested encodings - if (!encodings || encodings.length === 0) { - return this.negotiator.encodings() + for (var i = 0; i < methods.length; i++) { + // make upper case + methods[i] = methods[i].toUpperCase(); } - return this.negotiator.encodings(encodings)[0] || false -} + return methods; +}; /** - * Return accepted charsets or best fit based on `charsets`. - * - * Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5` - * an array sorted by quality is returned: - * - * ['utf-8', 'utf-7', 'iso-8859-1'] - * - * @param {String|Array} charsets... - * @return {String|Array} - * @public + * dispatch req, res into this route + * @private */ -Accepts.prototype.charset = -Accepts.prototype.charsets = function (charsets_) { - var charsets = charsets_ - - // support flattened arguments - if (charsets && !Array.isArray(charsets)) { - charsets = new Array(arguments.length) - for (var i = 0; i < charsets.length; i++) { - charsets[i] = arguments[i] - } +Route.prototype.dispatch = function dispatch(req, res, done) { + var idx = 0; + var stack = this.stack; + if (stack.length === 0) { + return done(); } - // no charsets, return all requested charsets - if (!charsets || charsets.length === 0) { - return this.negotiator.charsets() + var method = req.method.toLowerCase(); + if (method === 'head' && !this.methods['head']) { + method = 'get'; } - return this.negotiator.charsets(charsets)[0] || false -} + req.route = this; -/** - * Return accepted languages or best fit based on `langs`. - * - * Given `Accept-Language: en;q=0.8, es, pt` - * an array sorted by quality is returned: - * - * ['es', 'pt', 'en'] - * - * @param {String|Array} langs... - * @return {Array|String} - * @public - */ + next(); -Accepts.prototype.lang = -Accepts.prototype.langs = -Accepts.prototype.language = -Accepts.prototype.languages = function (languages_) { - var languages = languages_ + function next(err) { + // signal to exit route + if (err && err === 'route') { + return done(); + } - // support flattened arguments - if (languages && !Array.isArray(languages)) { - languages = new Array(arguments.length) - for (var i = 0; i < languages.length; i++) { - languages[i] = arguments[i] + // signal to exit router + if (err && err === 'router') { + return done(err) } - } - // no languages, return all requested languages - if (!languages || languages.length === 0) { - return this.negotiator.languages() - } + var layer = stack[idx++]; + if (!layer) { + return done(err); + } - return this.negotiator.languages(languages)[0] || false -} + if (layer.method && layer.method !== method) { + return next(err); + } + + if (err) { + layer.handle_error(err, req, res, next); + } else { + layer.handle_request(req, res, next); + } + } +}; /** - * Convert extnames to mime. + * Add a handler for all HTTP verbs to this route. * - * @param {String} type - * @return {String} - * @private + * Behaves just like middleware and can respond or call `next` + * to continue processing. + * + * You can use multiple `.all` call to add multiple handlers. + * + * function check_something(req, res, next){ + * next(); + * }; + * + * function validate_user(req, res, next){ + * next(); + * }; + * + * route + * .all(validate_user) + * .all(check_something) + * .get(function(req, res, next){ + * res.send('hello world'); + * }); + * + * @param {function} handler + * @return {Route} for chaining + * @api public */ -function extToMime (type) { - return type.indexOf('/') === -1 - ? mime.lookup(type) - : type -} - -/** - * Check if mime is valid. - * - * @param {String} type - * @return {String} - * @private - */ +Route.prototype.all = function all() { + var handles = flatten(slice.call(arguments)); -function validMime (type) { - return typeof type === 'string' -} + for (var i = 0; i < handles.length; i++) { + var handle = handles[i]; + if (typeof handle !== 'function') { + var type = toString.call(handle); + var msg = 'Route.all() requires a callback function but got a ' + type + throw new TypeError(msg); + } -/***/ }), -/* 228 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + var layer = Layer('/', {}, handle); + layer.method = undefined; -"use strict"; + this.methods._all = true; + this.stack.push(layer); + } + return this; +}; -var Type = __webpack_require__(945); +methods.forEach(function(method){ + Route.prototype[method] = function(){ + var handles = flatten(slice.call(arguments)); -function resolveYamlBoolean(data) { - if (data === null) return false; + for (var i = 0; i < handles.length; i++) { + var handle = handles[i]; - var max = data.length; + if (typeof handle !== 'function') { + var type = toString.call(handle); + var msg = 'Route.' + method + '() requires a callback function but got a ' + type + throw new Error(msg); + } - return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || - (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')); -} + debug('%s %o', method, this.path) -function constructYamlBoolean(data) { - return data === 'true' || - data === 'True' || - data === 'TRUE'; -} + var layer = Layer('/', {}, handle); + layer.method = method; -function isBoolean(object) { - return Object.prototype.toString.call(object) === '[object Boolean]'; -} + this.methods[method] = true; + this.stack.push(layer); + } -module.exports = new Type('tag:yaml.org,2002:bool', { - kind: 'scalar', - resolve: resolveYamlBoolean, - construct: constructYamlBoolean, - predicate: isBoolean, - represent: { - lowercase: function (object) { return object ? 'true' : 'false'; }, - uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; }, - camelcase: function (object) { return object ? 'True' : 'False'; } - }, - defaultStyle: 'lowercase' + return this; + }; }); /***/ }), -/* 229 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -var getTag = __webpack_require__(965), - isObjectLike = __webpack_require__(458); - -/** `Object#toString` result references. */ -var mapTag = '[object Map]'; +/* 252 */, +/* 253 */, +/* 254 */, +/* 255 */, +/* 256 */, +/* 257 */ +/***/ (function(module) { /** - * The base implementation of `_.isMap` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a map, else `false`. - */ -function baseIsMap(value) { - return isObjectLike(value) && getTag(value) == mapTag; -} - -module.exports = baseIsMap; - - -/***/ }), -/* 230 */, -/* 231 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; -/*! - * depd - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed + * Helpers. */ - +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var y = d * 365.25; /** - * Module dependencies. - * @private + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public */ -var EventEmitter = __webpack_require__(614).EventEmitter +module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isNaN(val) === false) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; /** - * Module exports. - * @public + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private */ -lazyProperty(module.exports, 'callSiteToString', function callSiteToString () { - var limit = Error.stackTraceLimit - var obj = {} - var prep = Error.prepareStackTrace - - function prepareObjectStackTrace (obj, stack) { - return stack +function parse(str) { + str = String(str); + if (str.length > 100) { + return; } - - Error.prepareStackTrace = prepareObjectStackTrace - Error.stackTraceLimit = 2 - - // capture the stack - Error.captureStackTrace(obj) - - // slice the stack - var stack = obj.stack.slice() - - Error.prepareStackTrace = prep - Error.stackTraceLimit = limit - - return stack[0].toString ? toString : __webpack_require__(870) -}) - -lazyProperty(module.exports, 'eventListenerCount', function eventListenerCount () { - return EventEmitter.listenerCount || __webpack_require__(4) -}) + var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} /** - * Define a lazy property. + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private */ -function lazyProperty (obj, prop, getter) { - function get () { - var val = getter() - - Object.defineProperty(obj, prop, { - configurable: true, - enumerable: true, - value: val - }) - - return val +function fmtShort(ms) { + if (ms >= d) { + return Math.round(ms / d) + 'd'; } - - Object.defineProperty(obj, prop, { - configurable: true, - enumerable: true, - get: get - }) + if (ms >= h) { + return Math.round(ms / h) + 'h'; + } + if (ms >= m) { + return Math.round(ms / m) + 'm'; + } + if (ms >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; } /** - * Call toString() on the obj + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private */ -function toString (obj) { - return obj.toString() +function fmtLong(ms) { + return plural(ms, d, 'day') || + plural(ms, h, 'hour') || + plural(ms, m, 'minute') || + plural(ms, s, 'second') || + ms + ' ms'; } - -/***/ }), -/* 232 */ -/***/ (function(module) { - -module.exports = [["0","\u0000",128],["a1","。",62],["8140"," 、。,.・:;?!゛゜´`¨^ ̄_ヽヾゝゞ〃仝々〆〇ー―‐/\~∥|…‥‘’“”()〔〕[]{}〈",9,"+-±×"],["8180","÷=≠<>≦≧∞∴♂♀°′″℃¥$¢£%#&*@§☆★○●◎◇◆□■△▲▽▼※〒→←↑↓〓"],["81b8","∈∋⊆⊇⊂⊃∪∩"],["81c8","∧∨¬⇒⇔∀∃"],["81da","∠⊥⌒∂∇≡≒≪≫√∽∝∵∫∬"],["81f0","ʼn♯♭♪†‡¶"],["81fc","◯"],["824f","0",9],["8260","A",25],["8281","a",25],["829f","ぁ",82],["8340","ァ",62],["8380","ム",22],["839f","Α",16,"Σ",6],["83bf","α",16,"σ",6],["8440","А",5,"ЁЖ",25],["8470","а",5,"ёж",7],["8480","о",17],["849f","─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂"],["8740","①",19,"Ⅰ",9],["875f","㍉㌔㌢㍍㌘㌧㌃㌶㍑㍗㌍㌦㌣㌫㍊㌻㎜㎝㎞㎎㎏㏄㎡"],["877e","㍻"],["8780","〝〟№㏍℡㊤",4,"㈱㈲㈹㍾㍽㍼≒≡∫∮∑√⊥∠∟⊿∵∩∪"],["889f","亜唖娃阿哀愛挨姶逢葵茜穐悪握渥旭葦芦鯵梓圧斡扱宛姐虻飴絢綾鮎或粟袷安庵按暗案闇鞍杏以伊位依偉囲夷委威尉惟意慰易椅為畏異移維緯胃萎衣謂違遺医井亥域育郁磯一壱溢逸稲茨芋鰯允印咽員因姻引飲淫胤蔭"],["8940","院陰隠韻吋右宇烏羽迂雨卯鵜窺丑碓臼渦嘘唄欝蔚鰻姥厩浦瓜閏噂云運雲荏餌叡営嬰影映曳栄永泳洩瑛盈穎頴英衛詠鋭液疫益駅悦謁越閲榎厭円"],["8980","園堰奄宴延怨掩援沿演炎焔煙燕猿縁艶苑薗遠鉛鴛塩於汚甥凹央奥往応押旺横欧殴王翁襖鴬鴎黄岡沖荻億屋憶臆桶牡乙俺卸恩温穏音下化仮何伽価佳加可嘉夏嫁家寡科暇果架歌河火珂禍禾稼箇花苛茄荷華菓蝦課嘩貨迦過霞蚊俄峨我牙画臥芽蛾賀雅餓駕介会解回塊壊廻快怪悔恢懐戒拐改"],["8a40","魁晦械海灰界皆絵芥蟹開階貝凱劾外咳害崖慨概涯碍蓋街該鎧骸浬馨蛙垣柿蛎鈎劃嚇各廓拡撹格核殻獲確穫覚角赫較郭閣隔革学岳楽額顎掛笠樫"],["8a80","橿梶鰍潟割喝恰括活渇滑葛褐轄且鰹叶椛樺鞄株兜竃蒲釜鎌噛鴨栢茅萱粥刈苅瓦乾侃冠寒刊勘勧巻喚堪姦完官寛干幹患感慣憾換敢柑桓棺款歓汗漢澗潅環甘監看竿管簡緩缶翰肝艦莞観諌貫還鑑間閑関陥韓館舘丸含岸巌玩癌眼岩翫贋雁頑顔願企伎危喜器基奇嬉寄岐希幾忌揮机旗既期棋棄"],["8b40","機帰毅気汽畿祈季稀紀徽規記貴起軌輝飢騎鬼亀偽儀妓宜戯技擬欺犠疑祇義蟻誼議掬菊鞠吉吃喫桔橘詰砧杵黍却客脚虐逆丘久仇休及吸宮弓急救"],["8b80","朽求汲泣灸球究窮笈級糾給旧牛去居巨拒拠挙渠虚許距鋸漁禦魚亨享京供侠僑兇競共凶協匡卿叫喬境峡強彊怯恐恭挟教橋況狂狭矯胸脅興蕎郷鏡響饗驚仰凝尭暁業局曲極玉桐粁僅勤均巾錦斤欣欽琴禁禽筋緊芹菌衿襟謹近金吟銀九倶句区狗玖矩苦躯駆駈駒具愚虞喰空偶寓遇隅串櫛釧屑屈"],["8c40","掘窟沓靴轡窪熊隈粂栗繰桑鍬勲君薫訓群軍郡卦袈祁係傾刑兄啓圭珪型契形径恵慶慧憩掲携敬景桂渓畦稽系経継繋罫茎荊蛍計詣警軽頚鶏芸迎鯨"],["8c80","劇戟撃激隙桁傑欠決潔穴結血訣月件倹倦健兼券剣喧圏堅嫌建憲懸拳捲検権牽犬献研硯絹県肩見謙賢軒遣鍵険顕験鹸元原厳幻弦減源玄現絃舷言諺限乎個古呼固姑孤己庫弧戸故枯湖狐糊袴股胡菰虎誇跨鈷雇顧鼓五互伍午呉吾娯後御悟梧檎瑚碁語誤護醐乞鯉交佼侯候倖光公功効勾厚口向"],["8d40","后喉坑垢好孔孝宏工巧巷幸広庚康弘恒慌抗拘控攻昂晃更杭校梗構江洪浩港溝甲皇硬稿糠紅紘絞綱耕考肯肱腔膏航荒行衡講貢購郊酵鉱砿鋼閤降"],["8d80","項香高鴻剛劫号合壕拷濠豪轟麹克刻告国穀酷鵠黒獄漉腰甑忽惚骨狛込此頃今困坤墾婚恨懇昏昆根梱混痕紺艮魂些佐叉唆嵯左差査沙瑳砂詐鎖裟坐座挫債催再最哉塞妻宰彩才採栽歳済災采犀砕砦祭斎細菜裁載際剤在材罪財冴坂阪堺榊肴咲崎埼碕鷺作削咋搾昨朔柵窄策索錯桜鮭笹匙冊刷"],["8e40","察拶撮擦札殺薩雑皐鯖捌錆鮫皿晒三傘参山惨撒散桟燦珊産算纂蚕讃賛酸餐斬暫残仕仔伺使刺司史嗣四士始姉姿子屍市師志思指支孜斯施旨枝止"],["8e80","死氏獅祉私糸紙紫肢脂至視詞詩試誌諮資賜雌飼歯事似侍児字寺慈持時次滋治爾璽痔磁示而耳自蒔辞汐鹿式識鴫竺軸宍雫七叱執失嫉室悉湿漆疾質実蔀篠偲柴芝屡蕊縞舎写射捨赦斜煮社紗者謝車遮蛇邪借勺尺杓灼爵酌釈錫若寂弱惹主取守手朱殊狩珠種腫趣酒首儒受呪寿授樹綬需囚収周"],["8f40","宗就州修愁拾洲秀秋終繍習臭舟蒐衆襲讐蹴輯週酋酬集醜什住充十従戎柔汁渋獣縦重銃叔夙宿淑祝縮粛塾熟出術述俊峻春瞬竣舜駿准循旬楯殉淳"],["8f80","準潤盾純巡遵醇順処初所暑曙渚庶緒署書薯藷諸助叙女序徐恕鋤除傷償勝匠升召哨商唱嘗奨妾娼宵将小少尚庄床廠彰承抄招掌捷昇昌昭晶松梢樟樵沼消渉湘焼焦照症省硝礁祥称章笑粧紹肖菖蒋蕉衝裳訟証詔詳象賞醤鉦鍾鐘障鞘上丈丞乗冗剰城場壌嬢常情擾条杖浄状畳穣蒸譲醸錠嘱埴飾"],["9040","拭植殖燭織職色触食蝕辱尻伸信侵唇娠寝審心慎振新晋森榛浸深申疹真神秦紳臣芯薪親診身辛進針震人仁刃塵壬尋甚尽腎訊迅陣靭笥諏須酢図厨"],["9080","逗吹垂帥推水炊睡粋翠衰遂酔錐錘随瑞髄崇嵩数枢趨雛据杉椙菅頗雀裾澄摺寸世瀬畝是凄制勢姓征性成政整星晴棲栖正清牲生盛精聖声製西誠誓請逝醒青静斉税脆隻席惜戚斥昔析石積籍績脊責赤跡蹟碩切拙接摂折設窃節説雪絶舌蝉仙先千占宣専尖川戦扇撰栓栴泉浅洗染潜煎煽旋穿箭線"],["9140","繊羨腺舛船薦詮賎践選遷銭銑閃鮮前善漸然全禅繕膳糎噌塑岨措曾曽楚狙疏疎礎祖租粗素組蘇訴阻遡鼠僧創双叢倉喪壮奏爽宋層匝惣想捜掃挿掻"],["9180","操早曹巣槍槽漕燥争痩相窓糟総綜聡草荘葬蒼藻装走送遭鎗霜騒像増憎臓蔵贈造促側則即息捉束測足速俗属賊族続卒袖其揃存孫尊損村遜他多太汰詑唾堕妥惰打柁舵楕陀駄騨体堆対耐岱帯待怠態戴替泰滞胎腿苔袋貸退逮隊黛鯛代台大第醍題鷹滝瀧卓啄宅托択拓沢濯琢託鐸濁諾茸凧蛸只"],["9240","叩但達辰奪脱巽竪辿棚谷狸鱈樽誰丹単嘆坦担探旦歎淡湛炭短端箪綻耽胆蛋誕鍛団壇弾断暖檀段男談値知地弛恥智池痴稚置致蜘遅馳築畜竹筑蓄"],["9280","逐秩窒茶嫡着中仲宙忠抽昼柱注虫衷註酎鋳駐樗瀦猪苧著貯丁兆凋喋寵帖帳庁弔張彫徴懲挑暢朝潮牒町眺聴脹腸蝶調諜超跳銚長頂鳥勅捗直朕沈珍賃鎮陳津墜椎槌追鎚痛通塚栂掴槻佃漬柘辻蔦綴鍔椿潰坪壷嬬紬爪吊釣鶴亭低停偵剃貞呈堤定帝底庭廷弟悌抵挺提梯汀碇禎程締艇訂諦蹄逓"],["9340","邸鄭釘鼎泥摘擢敵滴的笛適鏑溺哲徹撤轍迭鉄典填天展店添纏甜貼転顛点伝殿澱田電兎吐堵塗妬屠徒斗杜渡登菟賭途都鍍砥砺努度土奴怒倒党冬"],["9380","凍刀唐塔塘套宕島嶋悼投搭東桃梼棟盗淘湯涛灯燈当痘祷等答筒糖統到董蕩藤討謄豆踏逃透鐙陶頭騰闘働動同堂導憧撞洞瞳童胴萄道銅峠鴇匿得徳涜特督禿篤毒独読栃橡凸突椴届鳶苫寅酉瀞噸屯惇敦沌豚遁頓呑曇鈍奈那内乍凪薙謎灘捺鍋楢馴縄畷南楠軟難汝二尼弐迩匂賑肉虹廿日乳入"],["9440","如尿韮任妊忍認濡禰祢寧葱猫熱年念捻撚燃粘乃廼之埜嚢悩濃納能脳膿農覗蚤巴把播覇杷波派琶破婆罵芭馬俳廃拝排敗杯盃牌背肺輩配倍培媒梅"],["9480","楳煤狽買売賠陪這蝿秤矧萩伯剥博拍柏泊白箔粕舶薄迫曝漠爆縛莫駁麦函箱硲箸肇筈櫨幡肌畑畠八鉢溌発醗髪伐罰抜筏閥鳩噺塙蛤隼伴判半反叛帆搬斑板氾汎版犯班畔繁般藩販範釆煩頒飯挽晩番盤磐蕃蛮匪卑否妃庇彼悲扉批披斐比泌疲皮碑秘緋罷肥被誹費避非飛樋簸備尾微枇毘琵眉美"],["9540","鼻柊稗匹疋髭彦膝菱肘弼必畢筆逼桧姫媛紐百謬俵彪標氷漂瓢票表評豹廟描病秒苗錨鋲蒜蛭鰭品彬斌浜瀕貧賓頻敏瓶不付埠夫婦富冨布府怖扶敷"],["9580","斧普浮父符腐膚芙譜負賦赴阜附侮撫武舞葡蕪部封楓風葺蕗伏副復幅服福腹複覆淵弗払沸仏物鮒分吻噴墳憤扮焚奮粉糞紛雰文聞丙併兵塀幣平弊柄並蔽閉陛米頁僻壁癖碧別瞥蔑箆偏変片篇編辺返遍便勉娩弁鞭保舗鋪圃捕歩甫補輔穂募墓慕戊暮母簿菩倣俸包呆報奉宝峰峯崩庖抱捧放方朋"],["9640","法泡烹砲縫胞芳萌蓬蜂褒訪豊邦鋒飽鳳鵬乏亡傍剖坊妨帽忘忙房暴望某棒冒紡肪膨謀貌貿鉾防吠頬北僕卜墨撲朴牧睦穆釦勃没殆堀幌奔本翻凡盆"],["9680","摩磨魔麻埋妹昧枚毎哩槙幕膜枕鮪柾鱒桝亦俣又抹末沫迄侭繭麿万慢満漫蔓味未魅巳箕岬密蜜湊蓑稔脈妙粍民眠務夢無牟矛霧鵡椋婿娘冥名命明盟迷銘鳴姪牝滅免棉綿緬面麺摸模茂妄孟毛猛盲網耗蒙儲木黙目杢勿餅尤戻籾貰問悶紋門匁也冶夜爺耶野弥矢厄役約薬訳躍靖柳薮鑓愉愈油癒"],["9740","諭輸唯佑優勇友宥幽悠憂揖有柚湧涌猶猷由祐裕誘遊邑郵雄融夕予余与誉輿預傭幼妖容庸揚揺擁曜楊様洋溶熔用窯羊耀葉蓉要謡踊遥陽養慾抑欲"],["9780","沃浴翌翼淀羅螺裸来莱頼雷洛絡落酪乱卵嵐欄濫藍蘭覧利吏履李梨理璃痢裏裡里離陸律率立葎掠略劉流溜琉留硫粒隆竜龍侶慮旅虜了亮僚両凌寮料梁涼猟療瞭稜糧良諒遼量陵領力緑倫厘林淋燐琳臨輪隣鱗麟瑠塁涙累類令伶例冷励嶺怜玲礼苓鈴隷零霊麗齢暦歴列劣烈裂廉恋憐漣煉簾練聯"],["9840","蓮連錬呂魯櫓炉賂路露労婁廊弄朗楼榔浪漏牢狼篭老聾蝋郎六麓禄肋録論倭和話歪賄脇惑枠鷲亙亘鰐詫藁蕨椀湾碗腕"],["989f","弌丐丕个丱丶丼丿乂乖乘亂亅豫亊舒弍于亞亟亠亢亰亳亶从仍仄仆仂仗仞仭仟价伉佚估佛佝佗佇佶侈侏侘佻佩佰侑佯來侖儘俔俟俎俘俛俑俚俐俤俥倚倨倔倪倥倅伜俶倡倩倬俾俯們倆偃假會偕偐偈做偖偬偸傀傚傅傴傲"],["9940","僉僊傳僂僖僞僥僭僣僮價僵儉儁儂儖儕儔儚儡儺儷儼儻儿兀兒兌兔兢竸兩兪兮冀冂囘册冉冏冑冓冕冖冤冦冢冩冪冫决冱冲冰况冽凅凉凛几處凩凭"],["9980","凰凵凾刄刋刔刎刧刪刮刳刹剏剄剋剌剞剔剪剴剩剳剿剽劍劔劒剱劈劑辨辧劬劭劼劵勁勍勗勞勣勦飭勠勳勵勸勹匆匈甸匍匐匏匕匚匣匯匱匳匸區卆卅丗卉卍凖卞卩卮夘卻卷厂厖厠厦厥厮厰厶參簒雙叟曼燮叮叨叭叺吁吽呀听吭吼吮吶吩吝呎咏呵咎呟呱呷呰咒呻咀呶咄咐咆哇咢咸咥咬哄哈咨"],["9a40","咫哂咤咾咼哘哥哦唏唔哽哮哭哺哢唹啀啣啌售啜啅啖啗唸唳啝喙喀咯喊喟啻啾喘喞單啼喃喩喇喨嗚嗅嗟嗄嗜嗤嗔嘔嗷嘖嗾嗽嘛嗹噎噐營嘴嘶嘲嘸"],["9a80","噫噤嘯噬噪嚆嚀嚊嚠嚔嚏嚥嚮嚶嚴囂嚼囁囃囀囈囎囑囓囗囮囹圀囿圄圉圈國圍圓團圖嗇圜圦圷圸坎圻址坏坩埀垈坡坿垉垓垠垳垤垪垰埃埆埔埒埓堊埖埣堋堙堝塲堡塢塋塰毀塒堽塹墅墹墟墫墺壞墻墸墮壅壓壑壗壙壘壥壜壤壟壯壺壹壻壼壽夂夊夐夛梦夥夬夭夲夸夾竒奕奐奎奚奘奢奠奧奬奩"],["9b40","奸妁妝佞侫妣妲姆姨姜妍姙姚娥娟娑娜娉娚婀婬婉娵娶婢婪媚媼媾嫋嫂媽嫣嫗嫦嫩嫖嫺嫻嬌嬋嬖嬲嫐嬪嬶嬾孃孅孀孑孕孚孛孥孩孰孳孵學斈孺宀"],["9b80","它宦宸寃寇寉寔寐寤實寢寞寥寫寰寶寳尅將專對尓尠尢尨尸尹屁屆屎屓屐屏孱屬屮乢屶屹岌岑岔妛岫岻岶岼岷峅岾峇峙峩峽峺峭嶌峪崋崕崗嵜崟崛崑崔崢崚崙崘嵌嵒嵎嵋嵬嵳嵶嶇嶄嶂嶢嶝嶬嶮嶽嶐嶷嶼巉巍巓巒巖巛巫已巵帋帚帙帑帛帶帷幄幃幀幎幗幔幟幢幤幇幵并幺麼广庠廁廂廈廐廏"],["9c40","廖廣廝廚廛廢廡廨廩廬廱廳廰廴廸廾弃弉彝彜弋弑弖弩弭弸彁彈彌彎弯彑彖彗彙彡彭彳彷徃徂彿徊很徑徇從徙徘徠徨徭徼忖忻忤忸忱忝悳忿怡恠"],["9c80","怙怐怩怎怱怛怕怫怦怏怺恚恁恪恷恟恊恆恍恣恃恤恂恬恫恙悁悍惧悃悚悄悛悖悗悒悧悋惡悸惠惓悴忰悽惆悵惘慍愕愆惶惷愀惴惺愃愡惻惱愍愎慇愾愨愧慊愿愼愬愴愽慂慄慳慷慘慙慚慫慴慯慥慱慟慝慓慵憙憖憇憬憔憚憊憑憫憮懌懊應懷懈懃懆憺懋罹懍懦懣懶懺懴懿懽懼懾戀戈戉戍戌戔戛"],["9d40","戞戡截戮戰戲戳扁扎扞扣扛扠扨扼抂抉找抒抓抖拔抃抔拗拑抻拏拿拆擔拈拜拌拊拂拇抛拉挌拮拱挧挂挈拯拵捐挾捍搜捏掖掎掀掫捶掣掏掉掟掵捫"],["9d80","捩掾揩揀揆揣揉插揶揄搖搴搆搓搦搶攝搗搨搏摧摯摶摎攪撕撓撥撩撈撼據擒擅擇撻擘擂擱擧舉擠擡抬擣擯攬擶擴擲擺攀擽攘攜攅攤攣攫攴攵攷收攸畋效敖敕敍敘敞敝敲數斂斃變斛斟斫斷旃旆旁旄旌旒旛旙无旡旱杲昊昃旻杳昵昶昴昜晏晄晉晁晞晝晤晧晨晟晢晰暃暈暎暉暄暘暝曁暹曉暾暼"],["9e40","曄暸曖曚曠昿曦曩曰曵曷朏朖朞朦朧霸朮朿朶杁朸朷杆杞杠杙杣杤枉杰枩杼杪枌枋枦枡枅枷柯枴柬枳柩枸柤柞柝柢柮枹柎柆柧檜栞框栩桀桍栲桎"],["9e80","梳栫桙档桷桿梟梏梭梔條梛梃檮梹桴梵梠梺椏梍桾椁棊椈棘椢椦棡椌棍棔棧棕椶椒椄棗棣椥棹棠棯椨椪椚椣椡棆楹楷楜楸楫楔楾楮椹楴椽楙椰楡楞楝榁楪榲榮槐榿槁槓榾槎寨槊槝榻槃榧樮榑榠榜榕榴槞槨樂樛槿權槹槲槧樅榱樞槭樔槫樊樒櫁樣樓橄樌橲樶橸橇橢橙橦橈樸樢檐檍檠檄檢檣"],["9f40","檗蘗檻櫃櫂檸檳檬櫞櫑櫟檪櫚櫪櫻欅蘖櫺欒欖鬱欟欸欷盜欹飮歇歃歉歐歙歔歛歟歡歸歹歿殀殄殃殍殘殕殞殤殪殫殯殲殱殳殷殼毆毋毓毟毬毫毳毯"],["9f80","麾氈氓气氛氤氣汞汕汢汪沂沍沚沁沛汾汨汳沒沐泄泱泓沽泗泅泝沮沱沾沺泛泯泙泪洟衍洶洫洽洸洙洵洳洒洌浣涓浤浚浹浙涎涕濤涅淹渕渊涵淇淦涸淆淬淞淌淨淒淅淺淙淤淕淪淮渭湮渮渙湲湟渾渣湫渫湶湍渟湃渺湎渤滿渝游溂溪溘滉溷滓溽溯滄溲滔滕溏溥滂溟潁漑灌滬滸滾漿滲漱滯漲滌"],["e040","漾漓滷澆潺潸澁澀潯潛濳潭澂潼潘澎澑濂潦澳澣澡澤澹濆澪濟濕濬濔濘濱濮濛瀉瀋濺瀑瀁瀏濾瀛瀚潴瀝瀘瀟瀰瀾瀲灑灣炙炒炯烱炬炸炳炮烟烋烝"],["e080","烙焉烽焜焙煥煕熈煦煢煌煖煬熏燻熄熕熨熬燗熹熾燒燉燔燎燠燬燧燵燼燹燿爍爐爛爨爭爬爰爲爻爼爿牀牆牋牘牴牾犂犁犇犒犖犢犧犹犲狃狆狄狎狒狢狠狡狹狷倏猗猊猜猖猝猴猯猩猥猾獎獏默獗獪獨獰獸獵獻獺珈玳珎玻珀珥珮珞璢琅瑯琥珸琲琺瑕琿瑟瑙瑁瑜瑩瑰瑣瑪瑶瑾璋璞璧瓊瓏瓔珱"],["e140","瓠瓣瓧瓩瓮瓲瓰瓱瓸瓷甄甃甅甌甎甍甕甓甞甦甬甼畄畍畊畉畛畆畚畩畤畧畫畭畸當疆疇畴疊疉疂疔疚疝疥疣痂疳痃疵疽疸疼疱痍痊痒痙痣痞痾痿"],["e180","痼瘁痰痺痲痳瘋瘍瘉瘟瘧瘠瘡瘢瘤瘴瘰瘻癇癈癆癜癘癡癢癨癩癪癧癬癰癲癶癸發皀皃皈皋皎皖皓皙皚皰皴皸皹皺盂盍盖盒盞盡盥盧盪蘯盻眈眇眄眩眤眞眥眦眛眷眸睇睚睨睫睛睥睿睾睹瞎瞋瞑瞠瞞瞰瞶瞹瞿瞼瞽瞻矇矍矗矚矜矣矮矼砌砒礦砠礪硅碎硴碆硼碚碌碣碵碪碯磑磆磋磔碾碼磅磊磬"],["e240","磧磚磽磴礇礒礑礙礬礫祀祠祗祟祚祕祓祺祿禊禝禧齋禪禮禳禹禺秉秕秧秬秡秣稈稍稘稙稠稟禀稱稻稾稷穃穗穉穡穢穩龝穰穹穽窈窗窕窘窖窩竈窰"],["e280","窶竅竄窿邃竇竊竍竏竕竓站竚竝竡竢竦竭竰笂笏笊笆笳笘笙笞笵笨笶筐筺笄筍笋筌筅筵筥筴筧筰筱筬筮箝箘箟箍箜箚箋箒箏筝箙篋篁篌篏箴篆篝篩簑簔篦篥籠簀簇簓篳篷簗簍篶簣簧簪簟簷簫簽籌籃籔籏籀籐籘籟籤籖籥籬籵粃粐粤粭粢粫粡粨粳粲粱粮粹粽糀糅糂糘糒糜糢鬻糯糲糴糶糺紆"],["e340","紂紜紕紊絅絋紮紲紿紵絆絳絖絎絲絨絮絏絣經綉絛綏絽綛綺綮綣綵緇綽綫總綢綯緜綸綟綰緘緝緤緞緻緲緡縅縊縣縡縒縱縟縉縋縢繆繦縻縵縹繃縷"],["e380","縲縺繧繝繖繞繙繚繹繪繩繼繻纃緕繽辮繿纈纉續纒纐纓纔纖纎纛纜缸缺罅罌罍罎罐网罕罔罘罟罠罨罩罧罸羂羆羃羈羇羌羔羞羝羚羣羯羲羹羮羶羸譱翅翆翊翕翔翡翦翩翳翹飜耆耄耋耒耘耙耜耡耨耿耻聊聆聒聘聚聟聢聨聳聲聰聶聹聽聿肄肆肅肛肓肚肭冐肬胛胥胙胝胄胚胖脉胯胱脛脩脣脯腋"],["e440","隋腆脾腓腑胼腱腮腥腦腴膃膈膊膀膂膠膕膤膣腟膓膩膰膵膾膸膽臀臂膺臉臍臑臙臘臈臚臟臠臧臺臻臾舁舂舅與舊舍舐舖舩舫舸舳艀艙艘艝艚艟艤"],["e480","艢艨艪艫舮艱艷艸艾芍芒芫芟芻芬苡苣苟苒苴苳苺莓范苻苹苞茆苜茉苙茵茴茖茲茱荀茹荐荅茯茫茗茘莅莚莪莟莢莖茣莎莇莊荼莵荳荵莠莉莨菴萓菫菎菽萃菘萋菁菷萇菠菲萍萢萠莽萸蔆菻葭萪萼蕚蒄葷葫蒭葮蒂葩葆萬葯葹萵蓊葢蒹蒿蒟蓙蓍蒻蓚蓐蓁蓆蓖蒡蔡蓿蓴蔗蔘蔬蔟蔕蔔蓼蕀蕣蕘蕈"],["e540","蕁蘂蕋蕕薀薤薈薑薊薨蕭薔薛藪薇薜蕷蕾薐藉薺藏薹藐藕藝藥藜藹蘊蘓蘋藾藺蘆蘢蘚蘰蘿虍乕虔號虧虱蚓蚣蚩蚪蚋蚌蚶蚯蛄蛆蚰蛉蠣蚫蛔蛞蛩蛬"],["e580","蛟蛛蛯蜒蜆蜈蜀蜃蛻蜑蜉蜍蛹蜊蜴蜿蜷蜻蜥蜩蜚蝠蝟蝸蝌蝎蝴蝗蝨蝮蝙蝓蝣蝪蠅螢螟螂螯蟋螽蟀蟐雖螫蟄螳蟇蟆螻蟯蟲蟠蠏蠍蟾蟶蟷蠎蟒蠑蠖蠕蠢蠡蠱蠶蠹蠧蠻衄衂衒衙衞衢衫袁衾袞衵衽袵衲袂袗袒袮袙袢袍袤袰袿袱裃裄裔裘裙裝裹褂裼裴裨裲褄褌褊褓襃褞褥褪褫襁襄褻褶褸襌褝襠襞"],["e640","襦襤襭襪襯襴襷襾覃覈覊覓覘覡覩覦覬覯覲覺覽覿觀觚觜觝觧觴觸訃訖訐訌訛訝訥訶詁詛詒詆詈詼詭詬詢誅誂誄誨誡誑誥誦誚誣諄諍諂諚諫諳諧"],["e680","諤諱謔諠諢諷諞諛謌謇謚諡謖謐謗謠謳鞫謦謫謾謨譁譌譏譎證譖譛譚譫譟譬譯譴譽讀讌讎讒讓讖讙讚谺豁谿豈豌豎豐豕豢豬豸豺貂貉貅貊貍貎貔豼貘戝貭貪貽貲貳貮貶賈賁賤賣賚賽賺賻贄贅贊贇贏贍贐齎贓賍贔贖赧赭赱赳趁趙跂趾趺跏跚跖跌跛跋跪跫跟跣跼踈踉跿踝踞踐踟蹂踵踰踴蹊"],["e740","蹇蹉蹌蹐蹈蹙蹤蹠踪蹣蹕蹶蹲蹼躁躇躅躄躋躊躓躑躔躙躪躡躬躰軆躱躾軅軈軋軛軣軼軻軫軾輊輅輕輒輙輓輜輟輛輌輦輳輻輹轅轂輾轌轉轆轎轗轜"],["e780","轢轣轤辜辟辣辭辯辷迚迥迢迪迯邇迴逅迹迺逑逕逡逍逞逖逋逧逶逵逹迸遏遐遑遒逎遉逾遖遘遞遨遯遶隨遲邂遽邁邀邊邉邏邨邯邱邵郢郤扈郛鄂鄒鄙鄲鄰酊酖酘酣酥酩酳酲醋醉醂醢醫醯醪醵醴醺釀釁釉釋釐釖釟釡釛釼釵釶鈞釿鈔鈬鈕鈑鉞鉗鉅鉉鉤鉈銕鈿鉋鉐銜銖銓銛鉚鋏銹銷鋩錏鋺鍄錮"],["e840","錙錢錚錣錺錵錻鍜鍠鍼鍮鍖鎰鎬鎭鎔鎹鏖鏗鏨鏥鏘鏃鏝鏐鏈鏤鐚鐔鐓鐃鐇鐐鐶鐫鐵鐡鐺鑁鑒鑄鑛鑠鑢鑞鑪鈩鑰鑵鑷鑽鑚鑼鑾钁鑿閂閇閊閔閖閘閙"],["e880","閠閨閧閭閼閻閹閾闊濶闃闍闌闕闔闖關闡闥闢阡阨阮阯陂陌陏陋陷陜陞陝陟陦陲陬隍隘隕隗險隧隱隲隰隴隶隸隹雎雋雉雍襍雜霍雕雹霄霆霈霓霎霑霏霖霙霤霪霰霹霽霾靄靆靈靂靉靜靠靤靦靨勒靫靱靹鞅靼鞁靺鞆鞋鞏鞐鞜鞨鞦鞣鞳鞴韃韆韈韋韜韭齏韲竟韶韵頏頌頸頤頡頷頽顆顏顋顫顯顰"],["e940","顱顴顳颪颯颱颶飄飃飆飩飫餃餉餒餔餘餡餝餞餤餠餬餮餽餾饂饉饅饐饋饑饒饌饕馗馘馥馭馮馼駟駛駝駘駑駭駮駱駲駻駸騁騏騅駢騙騫騷驅驂驀驃"],["e980","騾驕驍驛驗驟驢驥驤驩驫驪骭骰骼髀髏髑髓體髞髟髢髣髦髯髫髮髴髱髷髻鬆鬘鬚鬟鬢鬣鬥鬧鬨鬩鬪鬮鬯鬲魄魃魏魍魎魑魘魴鮓鮃鮑鮖鮗鮟鮠鮨鮴鯀鯊鮹鯆鯏鯑鯒鯣鯢鯤鯔鯡鰺鯲鯱鯰鰕鰔鰉鰓鰌鰆鰈鰒鰊鰄鰮鰛鰥鰤鰡鰰鱇鰲鱆鰾鱚鱠鱧鱶鱸鳧鳬鳰鴉鴈鳫鴃鴆鴪鴦鶯鴣鴟鵄鴕鴒鵁鴿鴾鵆鵈"],["ea40","鵝鵞鵤鵑鵐鵙鵲鶉鶇鶫鵯鵺鶚鶤鶩鶲鷄鷁鶻鶸鶺鷆鷏鷂鷙鷓鷸鷦鷭鷯鷽鸚鸛鸞鹵鹹鹽麁麈麋麌麒麕麑麝麥麩麸麪麭靡黌黎黏黐黔黜點黝黠黥黨黯"],["ea80","黴黶黷黹黻黼黽鼇鼈皷鼕鼡鼬鼾齊齒齔齣齟齠齡齦齧齬齪齷齲齶龕龜龠堯槇遙瑤凜熙"],["ed40","纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏"],["ed80","塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱"],["ee40","犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙"],["ee80","蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"],["eeef","ⅰ",9,"¬¦'""],["f040","",62],["f080","",124],["f140","",62],["f180","",124],["f240","",62],["f280","",124],["f340","",62],["f380","",124],["f440","",62],["f480","",124],["f540","",62],["f580","",124],["f640","",62],["f680","",124],["f740","",62],["f780","",124],["f840","",62],["f880","",124],["f940",""],["fa40","ⅰ",9,"Ⅰ",9,"¬¦'"㈱№℡∵纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊"],["fa80","兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯"],["fb40","涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神"],["fb80","祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙"],["fc40","髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"]]; - -/***/ }), -/* 233 */, -/* 234 */, -/* 235 */, -/* 236 */, -/* 237 */, -/* 238 */ -/***/ (function(module) { - -module.exports = require("domain"); - -/***/ }), -/* 239 */ -/***/ (function(module) { - /** - * Copies the values of `source` to `array`. - * - * @private - * @param {Array} source The array to copy values from. - * @param {Array} [array=[]] The array to copy values to. - * @returns {Array} Returns `array`. + * Pluralization helper. */ -function copyArray(source, array) { - var index = -1, - length = source.length; - array || (array = Array(length)); - while (++index < length) { - array[index] = source[index]; +function plural(ms, n, name) { + if (ms < n) { + return; } - return array; + if (ms < n * 1.5) { + return Math.floor(ms / n) + ' ' + name; + } + return Math.ceil(ms / n) + ' ' + name + 's'; } -module.exports = copyArray; - /***/ }), -/* 240 */, -/* 241 */, -/* 242 */, -/* 243 */ -/***/ (function(module) { +/* 258 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; -/*! - * merge-descriptors - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ - - - -/** - * Module exports. - * @public - */ - -module.exports = merge - -/** - * Module variables. - * @private - */ - -var hasOwnProperty = Object.prototype.hasOwnProperty +Object.defineProperty(exports, "__esModule", { value: true }); +const commands = __webpack_require__(508); +const calculateSlot = __webpack_require__(407); +const standard_as_callback_1 = __webpack_require__(207); +const utils_1 = __webpack_require__(200); +const lodash_1 = __webpack_require__(928); +const promiseContainer_1 = __webpack_require__(337); /** - * Merge the property descriptors of `src` into `dest` + * Command instance * - * @param {object} dest Object to add descriptors to - * @param {object} src Object to clone descriptors from - * @param {boolean} [redefine=true] Redefine `dest` properties with `src` properties - * @returns {object} Reference to dest - * @public + * It's rare that you need to create a Command instance yourself. + * + * @export + * @class Command + * + * @example + * ```js + * var infoCommand = new Command('info', null, function (err, result) { + * console.log('result', result); + * }); + * + * redis.sendCommand(infoCommand); + * + * // When no callback provided, Command instance will have a `promise` property, + * // which will resolve/reject with the result of the command. + * var getCommand = new Command('get', ['foo']); + * getCommand.promise.then(function (result) { + * console.log('result', result); + * }); + * ``` + * @see {@link Redis#sendCommand} which can send a Command instance to Redis */ - -function merge(dest, src, redefine) { - if (!dest) { - throw new TypeError('argument dest is required') - } - - if (!src) { - throw new TypeError('argument src is required') - } - - if (redefine === undefined) { - // Default to true - redefine = true - } - - Object.getOwnPropertyNames(src).forEach(function forEachOwnPropertyName(name) { - if (!redefine && hasOwnProperty.call(dest, name)) { - // Skip desriptor - return +class Command { + /** + * Creates an instance of Command. + * @param {string} name Command name + * @param {(Array)} [args=[]] An array of command arguments + * @param {ICommandOptions} [options={}] + * @param {CallbackFunction} [callback] The callback that handles the response. + * If omit, the response will be handled via Promise + * @memberof Command + */ + constructor(name, args = [], options = {}, callback) { + this.name = name; + this.transformed = false; + this.isCustomCommand = false; + this.inTransaction = false; + this.replyEncoding = options.replyEncoding; + this.errorStack = options.errorStack; + this.args = lodash_1.flatten(args); + this.callback = callback; + this.initPromise(); + if (options.keyPrefix) { + this._iterateKeys((key) => options.keyPrefix + key); + } + if (options.readOnly) { + this.isReadOnly = true; + } } - - // Copy descriptor - var descriptor = Object.getOwnPropertyDescriptor(src, name) - Object.defineProperty(dest, name, descriptor) - }) - - return dest -} - - -/***/ }), -/* 244 */, -/* 245 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -module.exports = globSync -globSync.GlobSync = GlobSync - -var fs = __webpack_require__(747) -var minimatch = __webpack_require__(93) -var Minimatch = minimatch.Minimatch -var Glob = __webpack_require__(402).Glob -var util = __webpack_require__(669) -var path = __webpack_require__(622) -var assert = __webpack_require__(357) -var isAbsolute = __webpack_require__(681) -var common = __webpack_require__(856) -var alphasort = common.alphasort -var alphasorti = common.alphasorti -var setopts = common.setopts -var ownProp = common.ownProp -var childrenIgnored = common.childrenIgnored - -function globSync (pattern, options) { - if (typeof options === 'function' || arguments.length === 3) - throw new TypeError('callback provided to sync glob\n'+ - 'See: https://github.com/isaacs/node-glob/issues/167') - - return new GlobSync(pattern, options).found -} - -function GlobSync (pattern, options) { - if (!pattern) - throw new Error('must provide pattern') - - if (typeof options === 'function' || arguments.length === 3) - throw new TypeError('callback provided to sync glob\n'+ - 'See: https://github.com/isaacs/node-glob/issues/167') - - if (!(this instanceof GlobSync)) - return new GlobSync(pattern, options) - - setopts(this, pattern, options) - - if (this.noprocess) - return this - - var n = this.minimatch.set.length - this.matches = new Array(n) - for (var i = 0; i < n; i ++) { - this._process(this.minimatch.set[i], i, false) - } - this._finish() -} - -GlobSync.prototype._finish = function () { - assert(this instanceof GlobSync) - if (this.realpath) { - var self = this - this.matches.forEach(function (matchset, index) { - var set = self.matches[index] = Object.create(null) - for (var p in matchset) { - try { - p = self._makeAbs(p) - var real = fs.realpathSync(p, self.realpathCache) - set[real] = true - } catch (er) { - if (er.syscall === 'stat') - set[self._makeAbs(p)] = true - else - throw er + static getFlagMap() { + if (!this.flagMap) { + this.flagMap = Object.keys(Command.FLAGS).reduce((map, flagName) => { + map[flagName] = {}; + Command.FLAGS[flagName].forEach((commandName) => { + map[flagName][commandName] = true; + }); + return map; + }, {}); } - } - }) - } - common.finish(this) -} - - -GlobSync.prototype._process = function (pattern, index, inGlobStar) { - assert(this instanceof GlobSync) - - // Get the first [n] parts of pattern that are all strings. - var n = 0 - while (typeof pattern[n] === 'string') { - n ++ - } - // now n is the index of the first one that is *not* a string. - - // See if there's anything else - var prefix - switch (n) { - // if not, then this is rather simple - case pattern.length: - this._processSimple(pattern.join('/'), index) - return - - case 0: - // pattern *starts* with some non-trivial item. - // going to readdir(cwd), but not include the prefix in matches. - prefix = null - break - - default: - // pattern has some string bits in the front. - // whatever it starts with, whether that's 'absolute' like /foo/bar, - // or 'relative' like '../baz' - prefix = pattern.slice(0, n).join('/') - break - } - - var remain = pattern.slice(n) - - // get the list of entries. - var read - if (prefix === null) - read = '.' - else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { - if (!prefix || !isAbsolute(prefix)) - prefix = '/' + prefix - read = prefix - } else - read = prefix - - var abs = this._makeAbs(read) - - //if ignored, skip processing - if (childrenIgnored(this, read)) - return - - var isGlobStar = remain[0] === minimatch.GLOBSTAR - if (isGlobStar) - this._processGlobStar(prefix, read, abs, remain, index, inGlobStar) - else - this._processReaddir(prefix, read, abs, remain, index, inGlobStar) -} - - -GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) { - var entries = this._readdir(abs, inGlobStar) - - // if the abs isn't a dir, then nothing can match! - if (!entries) - return - - // It will only match dot entries if it starts with a dot, or if - // dot is set. Stuff like @(.foo|.bar) isn't allowed. - var pn = remain[0] - var negate = !!this.minimatch.negate - var rawGlob = pn._glob - var dotOk = this.dot || rawGlob.charAt(0) === '.' - - var matchedEntries = [] - for (var i = 0; i < entries.length; i++) { - var e = entries[i] - if (e.charAt(0) !== '.' || dotOk) { - var m - if (negate && !prefix) { - m = !e.match(pn) - } else { - m = e.match(pn) - } - if (m) - matchedEntries.push(e) + return this.flagMap; } - } - - var len = matchedEntries.length - // If there are no matched entries, then nothing matches. - if (len === 0) - return - - // if this is the last remaining pattern bit, then no need for - // an additional stat *unless* the user has specified mark or - // stat explicitly. We know they exist, since readdir returned - // them. - - if (remain.length === 1 && !this.mark && !this.stat) { - if (!this.matches[index]) - this.matches[index] = Object.create(null) - - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i] - if (prefix) { - if (prefix.slice(-1) !== '/') - e = prefix + '/' + e - else - e = prefix + e - } - - if (e.charAt(0) === '/' && !this.nomount) { - e = path.join(this.root, e) - } - this.matches[index][e] = true + /** + * Check whether the command has the flag + * + * @param {string} flagName + * @param {string} commandName + * @return {boolean} + */ + static checkFlag(flagName, commandName) { + return !!this.getFlagMap()[flagName][commandName]; } - // This was the last one, and no stats were needed - return - } - - // now test all matched entries as stand-ins for that part - // of the pattern. - remain.shift() - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i] - var newPattern - if (prefix) - newPattern = [prefix, e] - else - newPattern = [e] - this._process(newPattern.concat(remain), index, inGlobStar) - } -} + static setArgumentTransformer(name, func) { + this._transformer.argument[name] = func; + } + static setReplyTransformer(name, func) { + this._transformer.reply[name] = func; + } + initPromise() { + const Promise = promiseContainer_1.get(); + const promise = new Promise((resolve, reject) => { + if (!this.transformed) { + this.transformed = true; + const transformer = Command._transformer.argument[this.name]; + if (transformer) { + this.args = transformer(this.args); + } + this.stringifyArguments(); + } + this.resolve = this._convertValue(resolve); + if (this.errorStack) { + this.reject = (err) => { + reject(utils_1.optimizeErrorStack(err, this.errorStack, __dirname)); + }; + } + else { + this.reject = reject; + } + }); + this.promise = standard_as_callback_1.default(promise, this.callback); + } + getSlot() { + if (typeof this.slot === "undefined") { + const key = this.getKeys()[0]; + this.slot = key == null ? null : calculateSlot(key); + } + return this.slot; + } + getKeys() { + return this._iterateKeys(); + } + /** + * Iterate through the command arguments that are considered keys. + * + * @param {Function} [transform=(key) => key] The transformation that should be applied to + * each key. The transformations will persist. + * @returns {string[]} The keys of the command. + * @memberof Command + */ + _iterateKeys(transform = (key) => key) { + if (typeof this.keys === "undefined") { + this.keys = []; + if (commands.exists(this.name)) { + const keyIndexes = commands.getKeyIndexes(this.name, this.args); + for (const index of keyIndexes) { + this.args[index] = transform(this.args[index]); + this.keys.push(this.args[index]); + } + } + } + return this.keys; + } + /** + * Convert command to writable buffer or string + * + * @return {string|Buffer} + * @see {@link Redis#sendCommand} + * @public + */ + toWritable() { + let bufferMode = false; + for (const arg of this.args) { + if (arg instanceof Buffer) { + bufferMode = true; + break; + } + } + let result; + const commandStr = "*" + + (this.args.length + 1) + + "\r\n$" + + Buffer.byteLength(this.name) + + "\r\n" + + this.name + + "\r\n"; + if (bufferMode) { + const buffers = new MixedBuffers(); + buffers.push(commandStr); + for (const arg of this.args) { + if (arg instanceof Buffer) { + if (arg.length === 0) { + buffers.push("$0\r\n\r\n"); + } + else { + buffers.push("$" + arg.length + "\r\n"); + buffers.push(arg); + buffers.push("\r\n"); + } + } + else { + buffers.push("$" + + Buffer.byteLength(arg) + + "\r\n" + + arg + + "\r\n"); + } + } + result = buffers.toBuffer(); + } + else { + result = commandStr; + for (const arg of this.args) { + result += + "$" + + Buffer.byteLength(arg) + + "\r\n" + + arg + + "\r\n"; + } + } + return result; + } + stringifyArguments() { + for (let i = 0; i < this.args.length; ++i) { + const arg = this.args[i]; + if (!(arg instanceof Buffer) && typeof arg !== "string") { + this.args[i] = utils_1.toArg(arg); + } + } + } + /** + * Convert the value from buffer to the target encoding. + * + * @private + * @param {Function} resolve The resolve function of the Promise + * @returns {Function} A funtion to transform and resolve a value + * @memberof Command + */ + _convertValue(resolve) { + return (value) => { + try { + resolve(this.transformReply(value)); + } + catch (err) { + this.reject(err); + } + return this.promise; + }; + } + /** + * Convert buffer/buffer[] to string/string[], + * and apply reply transformer. + * + * @memberof Command + */ + transformReply(result) { + if (this.replyEncoding) { + result = utils_1.convertBufferToString(result, this.replyEncoding); + } + const transformer = Command._transformer.reply[this.name]; + if (transformer) { + result = transformer(result); + } + return result; + } +} +exports.default = Command; +Command.FLAGS = { + VALID_IN_SUBSCRIBER_MODE: [ + "subscribe", + "psubscribe", + "unsubscribe", + "punsubscribe", + "ping", + "quit", + ], + VALID_IN_MONITOR_MODE: ["monitor", "auth"], + ENTER_SUBSCRIBER_MODE: ["subscribe", "psubscribe"], + EXIT_SUBSCRIBER_MODE: ["unsubscribe", "punsubscribe"], + WILL_DISCONNECT: ["quit"], +}; +Command._transformer = { + argument: {}, + reply: {}, +}; +const msetArgumentTransformer = function (args) { + if (args.length === 1) { + if (typeof Map !== "undefined" && args[0] instanceof Map) { + return utils_1.convertMapToArray(args[0]); + } + if (typeof args[0] === "object" && args[0] !== null) { + return utils_1.convertObjectToArray(args[0]); + } + } + return args; +}; +Command.setArgumentTransformer("mset", msetArgumentTransformer); +Command.setArgumentTransformer("msetnx", msetArgumentTransformer); +Command.setArgumentTransformer("hmset", function (args) { + if (args.length === 2) { + if (typeof Map !== "undefined" && args[1] instanceof Map) { + return [args[0]].concat(utils_1.convertMapToArray(args[1])); + } + if (typeof args[1] === "object" && args[1] !== null) { + return [args[0]].concat(utils_1.convertObjectToArray(args[1])); + } + } + return args; +}); +Command.setReplyTransformer("hgetall", function (result) { + if (Array.isArray(result)) { + const obj = {}; + for (let i = 0; i < result.length; i += 2) { + obj[result[i]] = result[i + 1]; + } + return obj; + } + return result; +}); +Command.setArgumentTransformer("hset", function (args) { + if (args.length === 2) { + if (typeof Map !== "undefined" && args[1] instanceof Map) { + return [args[0]].concat(utils_1.convertMapToArray(args[1])); + } + if (typeof args[1] === "object" && args[1] !== null) { + return [args[0]].concat(utils_1.convertObjectToArray(args[1])); + } + } + return args; +}); +class MixedBuffers { + constructor() { + this.length = 0; + this.items = []; + } + push(x) { + this.length += Buffer.byteLength(x); + this.items.push(x); + } + toBuffer() { + const result = Buffer.allocUnsafe(this.length); + let offset = 0; + for (const item of this.items) { + const length = Buffer.byteLength(item); + Buffer.isBuffer(item) + ? item.copy(result, offset) + : result.write(item, offset, length); + offset += length; + } + return result; + } +} -GlobSync.prototype._emitMatch = function (index, e) { - var abs = this._makeAbs(e) - if (this.mark) - e = this._mark(e) +/***/ }), +/* 259 */, +/* 260 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - if (this.matches[index][e]) - return +const conversions = __webpack_require__(600); - if (this.nodir) { - var c = this.cache[this._makeAbs(e)] - if (c === 'DIR' || Array.isArray(c)) - return - } +/* + This function routes a model to all other models. + + all functions that are routed have a property `.conversion` attached + to the returned synthetic function. This property is an array + of strings, each with the steps in between the 'from' and 'to' + color models (inclusive). + + conversions that are not possible simply are not included. +*/ - this.matches[index][e] = true - if (this.stat) - this._stat(e) +function buildGraph() { + const graph = {}; + // https://jsperf.com/object-keys-vs-for-in-with-closure/3 + const models = Object.keys(conversions); + + for (let len = models.length, i = 0; i < len; i++) { + graph[models[i]] = { + // http://jsperf.com/1-vs-infinity + // micro-opt, but this is simple. + distance: -1, + parent: null + }; + } + + return graph; } +// https://en.wikipedia.org/wiki/Breadth-first_search +function deriveBFS(fromModel) { + const graph = buildGraph(); + const queue = [fromModel]; // Unshift -> queue -> pop -GlobSync.prototype._readdirInGlobStar = function (abs) { - // follow all symlinked directories forever - // just proceed as if this is a non-globstar situation - if (this.follow) - return this._readdir(abs, false) + graph[fromModel].distance = 0; - var entries - var lstat - var stat - try { - lstat = fs.lstatSync(abs) - } catch (er) { - // lstat failed, doesn't exist - return null - } + while (queue.length) { + const current = queue.pop(); + const adjacents = Object.keys(conversions[current]); - var isSym = lstat.isSymbolicLink() - this.symlinks[abs] = isSym + for (let len = adjacents.length, i = 0; i < len; i++) { + const adjacent = adjacents[i]; + const node = graph[adjacent]; - // If it's not a symlink or a dir, then it's definitely a regular file. - // don't bother doing a readdir in that case. - if (!isSym && !lstat.isDirectory()) - this.cache[abs] = 'FILE' - else - entries = this._readdir(abs, false) + if (node.distance === -1) { + node.distance = graph[current].distance + 1; + node.parent = current; + queue.unshift(adjacent); + } + } + } - return entries + return graph; } -GlobSync.prototype._readdir = function (abs, inGlobStar) { - var entries - - if (inGlobStar && !ownProp(this.symlinks, abs)) - return this._readdirInGlobStar(abs) +function link(from, to) { + return function (args) { + return to(from(args)); + }; +} - if (ownProp(this.cache, abs)) { - var c = this.cache[abs] - if (!c || c === 'FILE') - return null +function wrapConversion(toModel, graph) { + const path = [graph[toModel].parent, toModel]; + let fn = conversions[graph[toModel].parent][toModel]; - if (Array.isArray(c)) - return c - } + let cur = graph[toModel].parent; + while (graph[cur].parent) { + path.unshift(graph[cur].parent); + fn = link(conversions[graph[cur].parent][cur], fn); + cur = graph[cur].parent; + } - try { - return this._readdirEntries(abs, fs.readdirSync(abs)) - } catch (er) { - this._readdirError(abs, er) - return null - } + fn.conversion = path; + return fn; } -GlobSync.prototype._readdirEntries = function (abs, entries) { - // if we haven't asked to stat everything, then just - // assume that everything in there exists, so we can avoid - // having to stat it a second time. - if (!this.mark && !this.stat) { - for (var i = 0; i < entries.length; i ++) { - var e = entries[i] - if (abs === '/') - e = abs + e - else - e = abs + '/' + e - this.cache[e] = true - } - } +module.exports = function (fromModel) { + const graph = deriveBFS(fromModel); + const conversion = {}; - this.cache[abs] = entries + const models = Object.keys(graph); + for (let len = models.length, i = 0; i < len; i++) { + const toModel = models[i]; + const node = graph[toModel]; - // mark and cache dir-ness - return entries -} + if (node.parent === null) { + // No possible conversion, or this node is the source model. + continue; + } -GlobSync.prototype._readdirError = function (f, er) { - // handle errors, and cache the information - switch (er.code) { - case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 - case 'ENOTDIR': // totally normal. means it *does* exist. - this.cache[this._makeAbs(f)] = 'FILE' - break + conversion[toModel] = wrapConversion(toModel, graph); + } - case 'ENOENT': // not terribly unusual - case 'ELOOP': - case 'ENAMETOOLONG': - case 'UNKNOWN': - this.cache[this._makeAbs(f)] = false - break + return conversion; +}; - default: // some unusual error. Treat as failure. - this.cache[this._makeAbs(f)] = false - if (this.strict) - throw er - if (!this.silent) - console.error('glob error', er) - break - } -} -GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) { - var entries = this._readdir(abs, inGlobStar) +/***/ }), +/* 261 */, +/* 262 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - // no entries means not a dir, so it can never have matches - // foo.txt/** doesn't match foo.txt - if (!entries) - return +var JsonWebTokenError = __webpack_require__(416); + +var TokenExpiredError = function (message, expiredAt) { + JsonWebTokenError.call(this, message); + this.name = 'TokenExpiredError'; + this.expiredAt = expiredAt; +}; - // test without the globstar, and with every child both below - // and replacing the globstar. - var remainWithoutGlobStar = remain.slice(1) - var gspref = prefix ? [ prefix ] : [] - var noGlobStar = gspref.concat(remainWithoutGlobStar) +TokenExpiredError.prototype = Object.create(JsonWebTokenError.prototype); - // the noGlobStar pattern exits the inGlobStar state - this._process(noGlobStar, index, false) +TokenExpiredError.prototype.constructor = TokenExpiredError; - var len = entries.length - var isSym = this.symlinks[abs] +module.exports = TokenExpiredError; - // If it's a symlink, and we're in a globstar, then stop - if (isSym && inGlobStar) - return +/***/ }), +/* 263 */, +/* 264 */, +/* 265 */ +/***/ (function(module) { - for (var i = 0; i < len; i++) { - var e = entries[i] - if (e.charAt(0) === '.' && !this.dot) - continue +"use strict"; +/*! + * depd + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ - // these two cases enter the inGlobStar state - var instead = gspref.concat(entries[i], remainWithoutGlobStar) - this._process(instead, index, true) - var below = gspref.concat(entries[i], remain) - this._process(below, index, true) - } -} -GlobSync.prototype._processSimple = function (prefix, index) { - // XXX review this. Shouldn't it be doing the mounting etc - // before doing stat? kinda weird? - var exists = this._stat(prefix) +/** + * Module exports. + */ - if (!this.matches[index]) - this.matches[index] = Object.create(null) +module.exports = callSiteToString - // If it doesn't exist, then just mark the lack of results - if (!exists) - return +/** + * Format a CallSite file location to a string. + */ - if (prefix && isAbsolute(prefix) && !this.nomount) { - var trail = /[\/\\]$/.test(prefix) - if (prefix.charAt(0) === '/') { - prefix = path.join(this.root, prefix) - } else { - prefix = path.resolve(this.root, prefix) - if (trail) - prefix += '/' +function callSiteFileLocation (callSite) { + var fileName + var fileLocation = '' + + if (callSite.isNative()) { + fileLocation = 'native' + } else if (callSite.isEval()) { + fileName = callSite.getScriptNameOrSourceURL() + if (!fileName) { + fileLocation = callSite.getEvalOrigin() } + } else { + fileName = callSite.getFileName() } - if (process.platform === 'win32') - prefix = prefix.replace(/\\/g, '/') - - // Mark this as a match - this.matches[index][prefix] = true -} + if (fileName) { + fileLocation += fileName -// Returns either 'DIR', 'FILE', or false -GlobSync.prototype._stat = function (f) { - var abs = this._makeAbs(f) - var needDir = f.slice(-1) === '/' + var lineNumber = callSite.getLineNumber() + if (lineNumber != null) { + fileLocation += ':' + lineNumber - if (f.length > this.maxLength) - return false + var columnNumber = callSite.getColumnNumber() + if (columnNumber) { + fileLocation += ':' + columnNumber + } + } + } - if (!this.stat && ownProp(this.cache, abs)) { - var c = this.cache[abs] + return fileLocation || 'unknown source' +} - if (Array.isArray(c)) - c = 'DIR' +/** + * Format a CallSite to a string. + */ - // It exists, but maybe not how we need it - if (!needDir || c === 'DIR') - return c +function callSiteToString (callSite) { + var addSuffix = true + var fileLocation = callSiteFileLocation(callSite) + var functionName = callSite.getFunctionName() + var isConstructor = callSite.isConstructor() + var isMethodCall = !(callSite.isToplevel() || isConstructor) + var line = '' - if (needDir && c === 'FILE') - return false + if (isMethodCall) { + var methodName = callSite.getMethodName() + var typeName = getConstructorName(callSite) - // otherwise we have to stat, because maybe c=true - // if we know it exists, but not what it is. - } + if (functionName) { + if (typeName && functionName.indexOf(typeName) !== 0) { + line += typeName + '.' + } - var exists - var stat = this.statCache[abs] - if (!stat) { - var lstat - try { - lstat = fs.lstatSync(abs) - } catch (er) { - return false - } + line += functionName - if (lstat.isSymbolicLink()) { - try { - stat = fs.statSync(abs) - } catch (er) { - stat = lstat + if (methodName && functionName.lastIndexOf('.' + methodName) !== functionName.length - methodName.length - 1) { + line += ' [as ' + methodName + ']' } } else { - stat = lstat + line += typeName + '.' + (methodName || '') } + } else if (isConstructor) { + line += 'new ' + (functionName || '') + } else if (functionName) { + line += functionName + } else { + addSuffix = false + line += fileLocation } - this.statCache[abs] = stat - - var c = stat.isDirectory() ? 'DIR' : 'FILE' - this.cache[abs] = this.cache[abs] || c - - if (needDir && c !== 'DIR') - return false + if (addSuffix) { + line += ' (' + fileLocation + ')' + } - return c + return line } -GlobSync.prototype._mark = function (p) { - return common.mark(this, p) -} +/** + * Get constructor name of reviver. + */ -GlobSync.prototype._makeAbs = function (f) { - return common.makeAbs(this, f) +function getConstructorName (obj) { + var receiver = obj.receiver + return (receiver.constructor && receiver.constructor.name) || null } /***/ }), -/* 246 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +/* 266 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; -module.exports = __webpack_require__(429); -module.exports.utils = __webpack_require__(411); +Object.defineProperty(exports, '__esModule', { value: true }); -module.exports.transports = __webpack_require__(485); -module.exports.parsers = __webpack_require__(380); +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } -// To infinity and beyond -Error.stackTraceLimit = Infinity; +var universalUserAgent = __webpack_require__(577); +var request = __webpack_require__(753); +var universalGithubAppJwt = __webpack_require__(292); +var LRU = _interopDefault(__webpack_require__(702)); +var requestError = __webpack_require__(103); +async function getAppAuthentication({ + id, + privateKey, + timeDifference +}) { + const appAuthentication = await universalGithubAppJwt.githubAppJwt({ + id, + privateKey, + now: timeDifference && Math.floor(Date.now() / 1000) + timeDifference + }); + return { + type: "app", + token: appAuthentication.token, + appId: appAuthentication.appId, + expiresAt: new Date(appAuthentication.expiration * 1000).toISOString() + }; +} -/***/ }), -/* 247 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +// https://github.com/isaacs/node-lru-cache#readme +function getCache() { + return new LRU({ + // cache max. 15000 tokens, that will use less than 10mb memory + max: 15000, + // Cache for 1 minute less than GitHub expiry + maxAge: 1000 * 60 * 59 + }); +} +async function get(cache, options) { + const cacheKey = optionsToCacheKey(options); + const result = await cache.get(cacheKey); -"use strict"; + if (!result) { + return; + } -const os = __webpack_require__(87); -const tty = __webpack_require__(867); -const hasFlag = __webpack_require__(364); + const [token, createdAt, expiresAt, repositorySelection, permissionsString, singleFileName] = result.split("|"); + const permissions = options.permissions || permissionsString.split(/,/).reduce((permissions, string) => { + if (/!$/.test(string)) { + permissions[string.slice(0, -1)] = "write"; + } else { + permissions[string] = "read"; + } -const {env} = process; + return permissions; + }, {}); + return { + token, + createdAt, + expiresAt, + permissions, + repositoryIds: options.repositoryIds, + singleFileName, + repositorySelection: repositorySelection + }; +} +async function set(cache, options, data) { + const key = optionsToCacheKey(options); + const permissionsString = options.permissions ? "" : Object.keys(data.permissions).map(name => `${name}${data.permissions[name] === "write" ? "!" : ""}`).join(","); + const value = [data.token, data.createdAt, data.expiresAt, data.repositorySelection, permissionsString, data.singleFileName].join("|"); + await cache.set(key, value); +} -let forceColor; -if (hasFlag('no-color') || - hasFlag('no-colors') || - hasFlag('color=false') || - hasFlag('color=never')) { - forceColor = 0; -} else if (hasFlag('color') || - hasFlag('colors') || - hasFlag('color=true') || - hasFlag('color=always')) { - forceColor = 1; +function optionsToCacheKey({ + installationId, + permissions = {}, + repositoryIds = [] +}) { + const permissionsString = Object.keys(permissions).sort().map(name => permissions[name] === "read" ? name : `${name}!`).join(","); + const repositoryIdsString = repositoryIds.sort().join(","); + return [installationId, repositoryIdsString, permissionsString].filter(Boolean).join("|"); } -if ('FORCE_COLOR' in env) { - if (env.FORCE_COLOR === 'true') { - forceColor = 1; - } else if (env.FORCE_COLOR === 'false') { - forceColor = 0; - } else { - forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3); - } +function toTokenAuthentication({ + installationId, + token, + createdAt, + expiresAt, + repositorySelection, + permissions, + repositoryIds, + singleFileName +}) { + return Object.assign({ + type: "token", + tokenType: "installation", + token, + installationId, + permissions, + createdAt, + expiresAt, + repositorySelection + }, repositoryIds ? { + repositoryIds + } : null, singleFileName ? { + singleFileName + } : null); } -function translateLevel(level) { - if (level === 0) { - return false; - } +async function getInstallationAuthentication(state, options, customRequest) { + const installationId = Number(options.installationId || state.installationId); + + if (!installationId) { + throw new Error("[@octokit/auth-app] installationId option is required for installation authentication."); + } + + const optionsWithInstallationTokenFromState = Object.assign({ + installationId + }, options); + + if (!options.refresh) { + const result = await get(state.cache, optionsWithInstallationTokenFromState); + + if (result) { + const { + token, + createdAt, + expiresAt, + permissions, + repositoryIds, + singleFileName, + repositorySelection + } = result; + return toTokenAuthentication({ + installationId, + token, + createdAt, + expiresAt, + permissions, + repositorySelection, + repositoryIds, + singleFileName + }); + } + } - return { - level, - hasBasic: true, - has256: level >= 2, - has16m: level >= 3 - }; + const appAuthentication = await getAppAuthentication(state); + const request = customRequest || state.request; + const { + data: { + token, + expires_at: expiresAt, + repositories, + permissions, + // @ts-ignore + repository_selection: repositorySelection, + // @ts-ignore + single_file: singleFileName + } + } = await request("POST /app/installations/:installation_id/access_tokens", { + installation_id: installationId, + repository_ids: options.repositoryIds, + permissions: options.permissions, + mediaType: { + previews: ["machine-man"] + }, + headers: { + authorization: `bearer ${appAuthentication.token}` + } + }); + const repositoryIds = repositories ? repositories.map(r => r.id) : void 0; + const createdAt = new Date().toISOString(); + await set(state.cache, optionsWithInstallationTokenFromState, { + token, + createdAt, + expiresAt, + repositorySelection, + permissions, + repositoryIds, + singleFileName + }); + return toTokenAuthentication({ + installationId, + token, + createdAt, + expiresAt, + repositorySelection, + permissions, + repositoryIds, + singleFileName + }); } -function supportsColor(haveStream, streamIsTTY) { - if (forceColor === 0) { - return 0; - } +async function getOAuthAuthentication(state, options, customRequest) { + const request = customRequest || state.request; // The "/login/oauth/access_token" is not part of the REST API hosted on api.github.com, + // instead it’s using the github.com domain. - if (hasFlag('color=16m') || - hasFlag('color=full') || - hasFlag('color=truecolor')) { - return 3; - } + const route = /^https:\/\/(api\.)?github\.com$/.test(state.request.endpoint.DEFAULTS.baseUrl) ? "POST https://github.com/login/oauth/access_token" : `POST ${state.request.endpoint.DEFAULTS.baseUrl.replace("/api/v3", "/login/oauth/access_token")}`; + const parameters = { + headers: { + accept: `application/json` + }, + client_id: state.clientId, + client_secret: state.clientSecret, + code: options.code, + state: options.state, + redirect_uri: options.redirectUrl + }; + const response = await request(route, parameters); - if (hasFlag('color=256')) { - return 2; - } + if (response.data.error !== undefined) { + throw new requestError.RequestError(`${response.data.error_description} (${response.data.error})`, response.status, { + headers: response.headers, + request: request.endpoint(route, parameters) + }); + } - if (haveStream && !streamIsTTY && forceColor === undefined) { - return 0; - } + const { + data: { + access_token: token, + scope + } + } = response; + return { + type: "token", + tokenType: "oauth", + token, + scopes: scope.split(/,\s*/).filter(Boolean) + }; +} - const min = forceColor || 0; +async function auth(state, options) { + if (options.type === "app") { + return getAppAuthentication(state); + } - if (env.TERM === 'dumb') { - return min; - } + if (options.type === "installation") { + return getInstallationAuthentication(state, options); + } - if (process.platform === 'win32') { - // Windows 10 build 10586 is the first Windows release that supports 256 colors. - // Windows 10 build 14931 is the first release that supports 16m/TrueColor. - const osRelease = os.release().split('.'); - if ( - Number(osRelease[0]) >= 10 && - Number(osRelease[2]) >= 10586 - ) { - return Number(osRelease[2]) >= 14931 ? 3 : 2; - } + return getOAuthAuthentication(state, options); +} - return 1; - } +function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } - if ('CI' in env) { - if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') { - return 1; - } + return obj; +} - return min; - } +function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); - if ('TEAMCITY_VERSION' in env) { - return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; - } + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); + if (enumerableOnly) symbols = symbols.filter(function (sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + }); + keys.push.apply(keys, symbols); + } - if ('GITHUB_ACTIONS' in env) { - return 1; - } + return keys; +} - if (env.COLORTERM === 'truecolor') { - return 3; - } +function _objectSpread2(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] != null ? arguments[i] : {}; - if ('TERM_PROGRAM' in env) { - const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + if (i % 2) { + ownKeys(Object(source), true).forEach(function (key) { + _defineProperty(target, key, source[key]); + }); + } else if (Object.getOwnPropertyDescriptors) { + Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); + } else { + ownKeys(Object(source)).forEach(function (key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); + } + } - switch (env.TERM_PROGRAM) { - case 'iTerm.app': - return version >= 3 ? 3 : 2; - case 'Apple_Terminal': - return 2; - // No default - } - } + return target; +} - if (/-256(color)?$/i.test(env.TERM)) { - return 2; - } +const PATHS = ["/app", "/app/installations", "/app/installations/:installation_id", "/app/installations/:installation_id/access_tokens", "/marketplace_listing/accounts/:account_id", "/marketplace_listing/plan", "/marketplace_listing/plans/:plan_id/accounts", "/marketplace_listing/stubbed/accounts/:account_id", "/marketplace_listing/stubbed/plan", "/marketplace_listing/stubbed/plans/:plan_id/accounts", "/orgs/:org/installation", "/repos/:owner/:repo/installation", "/users/:username/installation"]; // CREDIT: Simon Grondin (https://github.com/SGrondin) +// https://github.com/octokit/plugin-throttling.js/blob/45c5d7f13b8af448a9dbca468d9c9150a73b3948/lib/route-matcher.js - if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { - return 1; - } +function routeMatcher(paths) { + // EXAMPLE. For the following paths: - if ('COLORTERM' in env) { - return 1; - } + /* [ + "/orgs/:org/invitations", + "/repos/:owner/:repo/collaborators/:username" + ] */ + const regexes = paths.map(p => p.split("/").map(c => c.startsWith(":") ? "(?:.+?)" : c).join("/")); // 'regexes' would contain: - return min; -} + /* [ + '/orgs/(?:.+?)/invitations', + '/repos/(?:.+?)/(?:.+?)/collaborators/(?:.+?)' + ] */ -function getSupportLevel(stream) { - const level = supportsColor(stream, stream && stream.isTTY); - return translateLevel(level); + const regex = `^(?:${regexes.map(r => `(?:${r})`).join("|")})[^/]*$`; // 'regex' would contain: + + /* + ^(?:(?:\/orgs\/(?:.+?)\/invitations)|(?:\/repos\/(?:.+?)\/(?:.+?)\/collaborators\/(?:.+?)))[^\/]*$ + It may look scary, but paste it into https://www.debuggex.com/ + and it will make a lot more sense! + */ + + return new RegExp(regex, "i"); } -module.exports = { - supportsColor: getSupportLevel, - stdout: translateLevel(supportsColor(true, tty.isatty(1))), - stderr: translateLevel(supportsColor(true, tty.isatty(2))) -}; +const REGEX = routeMatcher(PATHS); +function requiresAppAuth(url) { + return !!url && REGEX.test(url); +} +const FIVE_SECONDS_IN_MS = 5 * 1000; -/***/ }), -/* 248 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +function isNotTimeSkewError(error) { + return !(error.message.match(/'Expiration time' claim \('exp'\) must be a numeric value representing the future time at which the assertion expires/) || error.message.match(/'Issued at' claim \('iat'\) must be an Integer representing the time that the assertion was issued/)); +} -var isFunction = __webpack_require__(10), - isMasked = __webpack_require__(58), - isObject = __webpack_require__(398), - toSource = __webpack_require__(473); +async function hook(state, request, route, parameters) { + let endpoint = request.endpoint.merge(route, parameters); -/** - * Used to match `RegExp` - * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). - */ -var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; + if (requiresAppAuth(endpoint.url.replace(request.endpoint.DEFAULTS.baseUrl, ""))) { + const { + token + } = await getAppAuthentication(state); + endpoint.headers.authorization = `bearer ${token}`; + let response; -/** Used to detect host constructors (Safari). */ -var reIsHostCtor = /^\[object .+?Constructor\]$/; + try { + response = await request(endpoint); + } catch (error) { + // If there's an issue with the expiration, regenerate the token and try again. + // Otherwise rethrow the error for upstream handling. + if (isNotTimeSkewError(error)) { + throw error; + } // If the date header is missing, we can't correct the system time skew. + // Throw the error to be handled upstream. -/** Used for built-in method references. */ -var funcProto = Function.prototype, - objectProto = Object.prototype; -/** Used to resolve the decompiled source of functions. */ -var funcToString = funcProto.toString; + if (typeof error.headers.date === "undefined") { + throw error; + } -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; + const diff = Math.floor((Date.parse(error.headers.date) - Date.parse(new Date().toString())) / 1000); + console.warn(error.message); + console.warn(`[@octokit/auth-app] GitHub API time and system time are different by ${diff} seconds. Retrying request with the difference accounted for.`); + const { + token + } = await getAppAuthentication(_objectSpread2(_objectSpread2({}, state), {}, { + timeDifference: diff + })); + endpoint.headers.authorization = `bearer ${token}`; + return request(endpoint); + } -/** Used to detect if a method is native. */ -var reIsNative = RegExp('^' + - funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') - .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' -); + return response; + } + const { + token, + createdAt + } = await getInstallationAuthentication(state, {}, request); + endpoint.headers.authorization = `token ${token}`; + return sendRequestWithRetries(request, endpoint, createdAt); +} /** - * The base implementation of `_.isNative` without bad shim checks. + * Newly created tokens might not be accessible immediately after creation. + * In case of a 401 response, we retry with an exponential delay until more + * than five seconds pass since the creation of the token. * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a native function, - * else `false`. + * @see https://github.com/octokit/auth-app.js/issues/65 */ -function baseIsNative(value) { - if (!isObject(value) || isMasked(value)) { - return false; + +async function sendRequestWithRetries(request, options, createdAt, retries = 0) { + const timeSinceTokenCreationInMs = +new Date() - +new Date(createdAt); + + try { + return await request(options); + } catch (error) { + if (error.status !== 401) { + throw error; + } + + if (timeSinceTokenCreationInMs >= FIVE_SECONDS_IN_MS) { + if (retries > 0) { + error.message = `After ${retries} retries within ${timeSinceTokenCreationInMs / 1000}s of creating the installation access token, the response remains 401. At this point, the cause may be an authentication problem or a system outage. Please check https://www.githubstatus.com for status information`; + } + + throw error; + } + + ++retries; + const awaitTime = retries * 1000; + console.warn(`[@octokit/auth-app] Retrying after 401 response to account for token replication delay (retry: ${retries}, wait: ${awaitTime / 1000}s)`); + await new Promise(resolve => setTimeout(resolve, awaitTime)); + return sendRequestWithRetries(request, options, createdAt, retries); } - var pattern = isFunction(value) ? reIsNative : reIsHostCtor; - return pattern.test(toSource(value)); } -module.exports = baseIsNative; +const VERSION = "2.6.0"; + +const createAppAuth = function createAppAuth(options) { + const state = Object.assign({ + request: request.request.defaults({ + headers: { + "user-agent": `octokit-auth-app.js/${VERSION} ${universalUserAgent.getUserAgent()}` + } + }), + cache: getCache() + }, options, { + id: Number(options.id) + }, options.installationId ? { + installationId: Number(options.installationId) + } : {}); + return Object.assign(auth.bind(null, state), { + hook: hook.bind(null, state) + }); +}; + +exports.createAppAuth = createAppAuth; +//# sourceMappingURL=index.js.map /***/ }), -/* 249 */ +/* 267 */, +/* 268 */ /***/ (function(__unusedmodule, exports, __webpack_require__) { -"use strict"; - +Object.defineProperty(exports, "__esModule", { value: true }); +var core_1 = __webpack_require__(196); +var utils_1 = __webpack_require__(657); +var NODE_VERSION = utils_1.parseSemver(process.versions.node); +/** http module integration */ +var Http = /** @class */ (function () { + /** + * @inheritDoc + */ + function Http(options) { + if (options === void 0) { options = {}; } + /** + * @inheritDoc + */ + this.name = Http.id; + this._breadcrumbs = typeof options.breadcrumbs === 'undefined' ? true : options.breadcrumbs; + this._tracing = typeof options.tracing === 'undefined' ? false : options.tracing; + } + /** + * @inheritDoc + */ + Http.prototype.setupOnce = function () { + // No need to instrument if we don't want to track anything + if (!this._breadcrumbs && !this._tracing) { + return; + } + var wrappedHandlerMaker = _createWrappedHandlerMaker(this._breadcrumbs, this._tracing); + var httpModule = __webpack_require__(605); + utils_1.fill(httpModule, 'get', wrappedHandlerMaker); + utils_1.fill(httpModule, 'request', wrappedHandlerMaker); + // NOTE: Prior to Node 9, `https` used internals of `http` module, thus we don't patch it. + // If we do, we'd get double breadcrumbs and double spans for `https` calls. + // It has been changed in Node 9, so for all versions equal and above, we patch `https` separately. + if (NODE_VERSION.major && NODE_VERSION.major > 8) { + var httpsModule = __webpack_require__(583); + utils_1.fill(httpsModule, 'get', wrappedHandlerMaker); + utils_1.fill(httpsModule, 'request', wrappedHandlerMaker); + } + }; + /** + * @inheritDoc + */ + Http.id = 'Http'; + return Http; +}()); +exports.Http = Http; /** - * A logger backed by [bunyan](https://github.com/trentm/node-bunyan) - * - * The default log level is `info`, but you can change it by setting the - * `LOG_LEVEL` environment variable to `trace`, `debug`, `info`, `warn`, - * `error`, or `fatal`. - * - * By default, logs are formatted for readability in development. If you intend - * to drain logs to a logging service, set `LOG_FORMAT=json`. + * Function which creates a function which creates wrapped versions of internal `request` and `get` calls within `http` + * and `https` modules. (NB: Not a typo - this is a creator^2!) * - * **Note**: All exceptions reported with `logger.error` will be forwarded to - * [sentry](https://github.com/getsentry/sentry) if the `SENTRY_DSN` environment - * variable is set. + * @param breadcrumbsEnabled Whether or not to record outgoing requests as breadcrumbs + * @param tracingEnabled Whether or not to record outgoing requests as tracing spans * - * ```js - * app.log("This is an info message"); - * app.log.debug("…so is this"); - * app.log.trace("Now we're talking"); - * app.log.info("I thought you should know…"); - * app.log.warn("Woah there"); - * app.log.error("ETOOMANYLOGS"); - * app.log.fatal("Goodbye, cruel world!"); - * ``` + * @returns A function which accepts the exiting handler and returns a wrapped handler */ -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.logger = void 0; -var bunyan_1 = __importDefault(__webpack_require__(891)); -var bunyan_format_1 = __importDefault(__webpack_require__(924)); -var supports_color_1 = __importDefault(__webpack_require__(247)); -var serializers_1 = __webpack_require__(874); -function toBunyanLogLevel(level) { - switch (level) { - case 'info': - case 'trace': - case 'debug': - case 'warn': - case 'error': - case 'fatal': - case undefined: - return level; - default: - throw new Error('Invalid log level'); - } -} -function toBunyanFormat(format) { - switch (format) { - case 'short': - case 'long': - case 'simple': - case 'json': - case 'bunyan': - case undefined: - return format; - default: - throw new Error('Invalid log format'); +function _createWrappedHandlerMaker(breadcrumbsEnabled, tracingEnabled) { + return function wrappedHandlerMaker(originalHandler) { + return function wrappedHandler(options) { + var requestUrl = extractUrl(options); + // we don't want to record requests to Sentry as either breadcrumbs or spans, so just use the original handler + if (isSentryRequest(requestUrl)) { + return originalHandler.apply(this, arguments); + } + var span; + var transaction; + var scope = core_1.getCurrentHub().getScope(); + if (scope && tracingEnabled) { + transaction = scope.getTransaction(); + if (transaction) { + span = transaction.startChild({ + description: (typeof options === 'string' || !options.method ? 'GET' : options.method) + " " + requestUrl, + op: 'request', + }); + } + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + return originalHandler + .apply(this, arguments) + .once('response', function (res) { + if (breadcrumbsEnabled) { + addRequestBreadcrumb('response', requestUrl, this, res); + } + if (tracingEnabled && span) { + span.setHttpStatus(res.statusCode); + cleanDescription(options, this, span); + span.finish(); + } + }) + .once('error', function () { + if (breadcrumbsEnabled) { + addRequestBreadcrumb('error', requestUrl, this); + } + if (tracingEnabled && span) { + span.setHttpStatus(500); + cleanDescription(options, this, span); + span.finish(); + } + }); + }; + }; +} +/** + * Captures Breadcrumb based on provided request/response pair + */ +function addRequestBreadcrumb(event, url, req, res) { + if (!core_1.getCurrentHub().getIntegration(Http)) { + return; } + core_1.getCurrentHub().addBreadcrumb({ + category: 'http', + data: { + method: req.method, + status_code: res && res.statusCode, + url: url, + }, + type: 'http', + }, { + event: event, + request: req, + response: res, + }); } -exports.logger = new bunyan_1.default({ - level: toBunyanLogLevel(process.env.LOG_LEVEL || 'info'), - name: 'probot', - serializers: serializers_1.serializers, - stream: new bunyan_format_1.default({ - color: supports_color_1.default.stdout, - levelInString: !!process.env.LOG_LEVEL_IN_STRING, - outputMode: toBunyanFormat(process.env.LOG_FORMAT || 'short') - }) -}); -//# sourceMappingURL=logger.js.map - -/***/ }), -/* 250 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -var constants = __webpack_require__(721) - -var origCwd = process.cwd -var cwd = null - -var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform - -process.cwd = function() { - if (!cwd) - cwd = origCwd.call(process) - return cwd +/** + * Assemble a URL to be used for breadcrumbs and spans. + * + * @param url URL string or object containing the component parts + * @returns Fully-formed URL + */ +function extractUrl(url) { + if (typeof url === 'string') { + return url; + } + var protocol = url.protocol || ''; + var hostname = url.hostname || url.host || ''; + // Don't log standard :80 (http) and :443 (https) ports to reduce the noise + var port = !url.port || url.port === 80 || url.port === 443 ? '' : ":" + url.port; + var path = url.path ? url.path : '/'; + // internal routes end up with too many slashes + return (protocol + "//" + hostname + port + path).replace('///', '/'); } -try { - process.cwd() -} catch (er) {} - -var chdir = process.chdir -process.chdir = function(d) { - cwd = null - chdir.call(process, d) +exports.extractUrl = extractUrl; +/** + * Handle an edge case with urls in the span description. Runs just before the span closes because it relies on + * data from the response object. + * + * @param requestOptions Configuration data for the request + * @param response Response object + * @param span Span representing the request + */ +function cleanDescription(requestOptions, response, span) { + // There are some libraries which don't pass the request protocol in the options object, so attempt to retrieve it + // from the response and run the URL processing again. We only do this in the presence of a (non-empty) host value, + // because if we're missing both, it's likely we're dealing with an internal route, in which case we don't want to be + // jamming a random `http:` on the front of it. + if (typeof requestOptions !== 'string' && !Object.keys(requestOptions).includes('protocol') && requestOptions.host) { + // Neither http.IncomingMessage nor any of its ancestors have an `agent` property in their type definitions, and + // http.Agent doesn't have a `protocol` property in its type definition. Nonetheless, at least one request library + // (superagent) arranges things that way, so might as well give it a shot. + try { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any + requestOptions.protocol = response.agent.protocol; + span.description = (requestOptions.method || 'GET') + " " + extractUrl(requestOptions); + } + catch (error) { + // well, we tried + } + } } - -module.exports = patch - -function patch (fs) { - // (re-)implement some things that are known busted or missing. - - // lchmod, broken prior to 0.6.2 - // back-port the fix here. - if (constants.hasOwnProperty('O_SYMLINK') && - process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { - patchLchmod(fs) - } - - // lutimes implementation, or no-op - if (!fs.lutimes) { - patchLutimes(fs) - } - - // https://github.com/isaacs/node-graceful-fs/issues/4 - // Chown should not fail on einval or eperm if non-root. - // It should not fail on enosys ever, as this just indicates - // that a fs doesn't support the intended operation. - - fs.chown = chownFix(fs.chown) - fs.fchown = chownFix(fs.fchown) - fs.lchown = chownFix(fs.lchown) - - fs.chmod = chmodFix(fs.chmod) - fs.fchmod = chmodFix(fs.fchmod) - fs.lchmod = chmodFix(fs.lchmod) - - fs.chownSync = chownFixSync(fs.chownSync) - fs.fchownSync = chownFixSync(fs.fchownSync) - fs.lchownSync = chownFixSync(fs.lchownSync) - - fs.chmodSync = chmodFixSync(fs.chmodSync) - fs.fchmodSync = chmodFixSync(fs.fchmodSync) - fs.lchmodSync = chmodFixSync(fs.lchmodSync) - - fs.stat = statFix(fs.stat) - fs.fstat = statFix(fs.fstat) - fs.lstat = statFix(fs.lstat) - - fs.statSync = statFixSync(fs.statSync) - fs.fstatSync = statFixSync(fs.fstatSync) - fs.lstatSync = statFixSync(fs.lstatSync) - - // if lchmod/lchown do not exist, then make them no-ops - if (!fs.lchmod) { - fs.lchmod = function (path, mode, cb) { - if (cb) process.nextTick(cb) +/** + * Checks whether given url points to Sentry server + * @param url url to verify + */ +function isSentryRequest(url) { + var client = core_1.getCurrentHub().getClient(); + if (!url || !client) { + return false; } - fs.lchmodSync = function () {} - } - if (!fs.lchown) { - fs.lchown = function (path, uid, gid, cb) { - if (cb) process.nextTick(cb) + var dsn = client.getDsn(); + if (!dsn) { + return false; } - fs.lchownSync = function () {} - } - - // on Windows, A/V software can lock the directory, causing this - // to fail with an EACCES or EPERM if the directory contains newly - // created files. Try again on failure, for up to 60 seconds. + return url.indexOf(dsn.host) !== -1; +} +//# sourceMappingURL=http.js.map - // Set the timeout this long because some Windows Anti-Virus, such as Parity - // bit9, may lock files for up to a minute, causing npm package install - // failures. Also, take care to yield the scheduler. Windows scheduling gives - // CPU to a busy looping process, which can cause the program causing the lock - // contention to be starved of CPU by node, so the contention doesn't resolve. - if (platform === "win32") { - fs.rename = (function (fs$rename) { return function (from, to, cb) { - var start = Date.now() - var backoff = 0; - fs$rename(from, to, function CB (er) { - if (er - && (er.code === "EACCES" || er.code === "EPERM") - && Date.now() - start < 60000) { - setTimeout(function() { - fs.stat(to, function (stater, st) { - if (stater && stater.code === "ENOENT") - fs$rename(from, to, CB); - else - cb(er) - }) - }, backoff) - if (backoff < 100) - backoff += 10; - return; - } - if (cb) cb(er) - }) - }})(fs.rename) - } +/***/ }), +/* 269 */, +/* 270 */, +/* 271 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { - // if read() returns EAGAIN, then just try it again. - fs.read = (function (fs$read) { - function read (fd, buffer, offset, length, position, callback_) { - var callback - if (callback_ && typeof callback_ === 'function') { - var eagCounter = 0 - callback = function (er, _, __) { - if (er && er.code === 'EAGAIN' && eagCounter < 10) { - eagCounter ++ - return fs$read.call(fs, fd, buffer, offset, length, position, callback) - } - callback_.apply(this, arguments) - } - } - return fs$read.call(fs, fd, buffer, offset, length, position, callback) +Object.defineProperty(exports, "__esModule", { value: true }); +var core_1 = __webpack_require__(196); +var utils_1 = __webpack_require__(657); +var handlers_1 = __webpack_require__(807); +/** Global Promise Rejection handler */ +var OnUnhandledRejection = /** @class */ (function () { + /** + * @inheritDoc + */ + function OnUnhandledRejection(_options) { + if (_options === void 0) { _options = { mode: 'warn' }; } + this._options = _options; + /** + * @inheritDoc + */ + this.name = OnUnhandledRejection.id; } - - // This ensures `util.promisify` works as it does for native `fs.read`. - read.__proto__ = fs$read - return read - })(fs.read) - - fs.readSync = (function (fs$readSync) { return function (fd, buffer, offset, length, position) { - var eagCounter = 0 - while (true) { - try { - return fs$readSync.call(fs, fd, buffer, offset, length, position) - } catch (er) { - if (er.code === 'EAGAIN' && eagCounter < 10) { - eagCounter ++ - continue + /** + * @inheritDoc + */ + OnUnhandledRejection.prototype.setupOnce = function () { + global.process.on('unhandledRejection', this.sendUnhandledPromise.bind(this)); + }; + /** + * Send an exception with reason + * @param reason string + * @param promise promise + */ + // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any + OnUnhandledRejection.prototype.sendUnhandledPromise = function (reason, promise) { + var hub = core_1.getCurrentHub(); + if (!hub.getIntegration(OnUnhandledRejection)) { + this._handleRejection(reason); + return; } - throw er - } - } - }})(fs.readSync) - - function patchLchmod (fs) { - fs.lchmod = function (path, mode, callback) { - fs.open( path - , constants.O_WRONLY | constants.O_SYMLINK - , mode - , function (err, fd) { - if (err) { - if (callback) callback(err) - return + /* eslint-disable @typescript-eslint/no-unsafe-member-access */ + var context = (promise.domain && promise.domain.sentryContext) || {}; + hub.withScope(function (scope) { + scope.setExtra('unhandledPromiseRejection', true); + // Preserve backwards compatibility with raven-node for now + if (context.user) { + scope.setUser(context.user); + } + if (context.tags) { + scope.setTags(context.tags); + } + if (context.extra) { + scope.setExtras(context.extra); + } + hub.captureException(reason, { originalException: promise }); + }); + /* eslint-disable @typescript-eslint/no-unsafe-member-access */ + this._handleRejection(reason); + }; + /** + * Handler for `mode` option + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + OnUnhandledRejection.prototype._handleRejection = function (reason) { + // https://github.com/nodejs/node/blob/7cf6f9e964aa00772965391c23acda6d71972a9a/lib/internal/process/promises.js#L234-L240 + var rejectionWarning = 'This error originated either by ' + + 'throwing inside of an async function without a catch block, ' + + 'or by rejecting a promise which was not handled with .catch().' + + ' The promise rejected with the reason:'; + /* eslint-disable no-console */ + if (this._options.mode === 'warn') { + utils_1.consoleSandbox(function () { + console.warn(rejectionWarning); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + console.error(reason && reason.stack ? reason.stack : reason); + }); } - // prefer to return the chmod error, if one occurs, - // but still try to close, and report closing errors if they occur. - fs.fchmod(fd, mode, function (err) { - fs.close(fd, function(err2) { - if (callback) callback(err || err2) - }) - }) - }) - } - - fs.lchmodSync = function (path, mode) { - var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) - - // prefer to return the chmod error, if one occurs, - // but still try to close, and report closing errors if they occur. - var threw = true - var ret - try { - ret = fs.fchmodSync(fd, mode) - threw = false - } finally { - if (threw) { - try { - fs.closeSync(fd) - } catch (er) {} - } else { - fs.closeSync(fd) + else if (this._options.mode === 'strict') { + utils_1.consoleSandbox(function () { + console.warn(rejectionWarning); + }); + handlers_1.logAndExitProcess(reason); } - } - return ret - } - } + /* eslint-enable no-console */ + }; + /** + * @inheritDoc + */ + OnUnhandledRejection.id = 'OnUnhandledRejection'; + return OnUnhandledRejection; +}()); +exports.OnUnhandledRejection = OnUnhandledRejection; +//# sourceMappingURL=onunhandledrejection.js.map - function patchLutimes (fs) { - if (constants.hasOwnProperty("O_SYMLINK")) { - fs.lutimes = function (path, at, mt, cb) { - fs.open(path, constants.O_SYMLINK, function (er, fd) { - if (er) { - if (cb) cb(er) - return - } - fs.futimes(fd, at, mt, function (er) { - fs.close(fd, function (er2) { - if (cb) cb(er || er2) - }) - }) - }) - } +/***/ }), +/* 272 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { - fs.lutimesSync = function (path, at, mt) { - var fd = fs.openSync(path, constants.O_SYMLINK) - var ret - var threw = true - try { - ret = fs.futimesSync(fd, at, mt) - threw = false - } finally { - if (threw) { - try { - fs.closeSync(fd) - } catch (er) {} - } else { - fs.closeSync(fd) - } - } - return ret - } +"use strict"; - } else { - fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) } - fs.lutimesSync = function () {} +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __generator = (this && this.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } - } +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +var node_fetch_1 = __importDefault(__webpack_require__(724)); +var escape_1 = __importDefault(__webpack_require__(644)); +function convertProject(raw) { + return { + id: raw.id, + slug: raw.slug, + language: raw.language.code + }; +} +var RTD = /** @class */ (function () { + function RTD(token) { + this.token = token; + } + RTD.prototype.getProject = function (slug) { + return __awaiter(this, void 0, void 0, function () { + return __generator(this, function (_a) { + return [2 /*return*/, node_fetch_1.default("https://readthedocs.org/api/v3/projects/" + escape_1.default(slug) + "/", { + method: 'get', + headers: { + 'Content-Type': 'application/json', + 'Authorization': "Token " + this.token + } + }) + .then(function (res) { return Promise.all([res.status, res.json()]); }) + .then(function (_a) { + var status = _a[0], json = _a[1]; + if (status != 200) { + throw new Error("Unexpected status code " + status + " with body: " + JSON.stringify(json)); + } + return convertProject(json); + })]; + }); + }); + }; + RTD.prototype.getTranslates = function (project) { + return __awaiter(this, void 0, void 0, function () { + var projectInfo, _a; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + if (!(typeof project === "string")) return [3 /*break*/, 2]; + return [4 /*yield*/, this.getProject(project)]; + case 1: + _a = _b.sent(); + return [3 /*break*/, 3]; + case 2: + _a = project; + _b.label = 3; + case 3: + projectInfo = _a; + return [2 /*return*/, node_fetch_1.default("https://readthedocs.org/api/v3/projects/" + escape_1.default(projectInfo.slug) + "/translations/", { + method: 'get', + headers: { + 'Content-Type': 'application/json', + 'Authorization': "Token " + this.token + } + }) + .then(function (res) { + return Promise.all([res.status, res.json()]); + }) + .then(function (_a) { + var status = _a[0], json = _a[1]; + if (status !== 200) { + throw new Error("Unexpected status code " + status + " with body: " + JSON.stringify(json)); + } + return json['results']; + }) + .then(function (translations) { + return translations.reduce(function (accumulator, currentValue) { + accumulator.push(convertProject(currentValue)); + return accumulator; + }, [projectInfo]); + })]; + } + }); + }); + }; + /** + * @see https://docs.readthedocs.io/en/stable/api/v3.html#version-detail + */ + RTD.prototype.getBuildActiveness = function (project, branch) { + return __awaiter(this, void 0, void 0, function () { + return __generator(this, function (_a) { + return [2 /*return*/, node_fetch_1.default("https://readthedocs.org/api/v3/projects/" + project + "/versions/" + escape_1.default(branch) + "/", { + method: 'get', + headers: { + 'Content-Type': 'application/json', + 'Authorization': "Token " + this.token + } + }) + .then(function (res) { + return Promise.all([res.status, res.json()]); + }) + .then(function (_a) { + var status = _a[0], json = _a[1]; + if (status != 200) { + throw new Error("Unexpected status code " + status + " with body: " + JSON.stringify(json)); + } + return json; + }) + .then(function (ver) { return ver.active; })]; + }); + }); + }; + /** + * @see https://docs.readthedocs.io/en/stable/api/v3.html#version-update + */ + RTD.prototype.configureBuild = function (project, branch, flag) { + return __awaiter(this, void 0, void 0, function () { + var currentFlag; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, this.getBuildActiveness(project, branch)]; + case 1: + currentFlag = _a.sent(); + if (currentFlag === flag) { + // no need to ask for update + return [2 /*return*/, false]; + } + // this implementation doesn't care the transaction, so + // the returned value could be different with expected one + // if we run two procedures at the same time + return [2 /*return*/, node_fetch_1.default("https://readthedocs.org/api/v3/projects/" + project + "/versions/" + escape_1.default(branch) + "/", { + method: 'patch', + headers: { + 'Content-Type': 'application/json', + 'Authorization': "Token " + this.token + }, + body: "{\"active\": " + flag + "}" + }) + .then(function (res) { + if (res.status != 204) { + return Promise.all([res.status, res.json()]); + } + else { + // 204 responses empty text, so json() doesn't work + return Promise.all([res.status, res.text()]); + } + }) + .then(function (_a) { + var status = _a[0], json = _a[1]; + if (status != 204) { + throw new Error("Unexpected status code " + status + " with body: " + JSON.stringify(json)); + } + return true; + })]; + } + }); + }); + }; + RTD.prototype.enableBuild = function (project, branch) { + return __awaiter(this, void 0, void 0, function () { + return __generator(this, function (_a) { + return [2 /*return*/, this.configureBuild(project, branch, true)]; + }); + }); + }; + RTD.prototype.disableBuild = function (project, branch) { + return __awaiter(this, void 0, void 0, function () { + return __generator(this, function (_a) { + return [2 /*return*/, this.configureBuild(project, branch, false)]; + }); + }); + }; + return RTD; +}()); +exports.default = RTD; - function chmodFix (orig) { - if (!orig) return orig - return function (target, mode, cb) { - return orig.call(fs, target, mode, function (er) { - if (chownErOk(er)) er = null - if (cb) cb.apply(this, arguments) - }) + +/***/ }), +/* 273 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +Object.defineProperty(exports, "__esModule", { value: true }); +var utils_1 = __webpack_require__(657); +var fs_1 = __webpack_require__(747); +var lru_map_1 = __webpack_require__(604); +var stacktrace = __webpack_require__(459); +var DEFAULT_LINES_OF_CONTEXT = 7; +var FILE_CONTENT_CACHE = new lru_map_1.LRUMap(100); +/** + * Resets the file cache. Exists for testing purposes. + * @hidden + */ +function resetFileContentCache() { + FILE_CONTENT_CACHE.clear(); +} +exports.resetFileContentCache = resetFileContentCache; +/** JSDoc */ +function getFunction(frame) { + try { + return frame.functionName || frame.typeName + "." + (frame.methodName || ''); } - } + catch (e) { + // This seems to happen sometimes when using 'use strict', + // stemming from `getTypeName`. + // [TypeError: Cannot read property 'constructor' of undefined] + return ''; + } +} +var mainModule = ((require.main && require.main.filename && utils_1.dirname(require.main.filename)) || + global.process.cwd()) + "/"; +/** JSDoc */ +function getModule(filename, base) { + if (!base) { + // eslint-disable-next-line no-param-reassign + base = mainModule; + } + // It's specifically a module + var file = utils_1.basename(filename, '.js'); + // eslint-disable-next-line no-param-reassign + filename = utils_1.dirname(filename); + var n = filename.lastIndexOf('/node_modules/'); + if (n > -1) { + // /node_modules/ is 14 chars + return filename.substr(n + 14).replace(/\//g, '.') + ":" + file; + } + // Let's see if it's a part of the main module + // To be a part of main module, it has to share the same base + n = (filename + "/").lastIndexOf(base, 0); + if (n === 0) { + var moduleName = filename.substr(base.length).replace(/\//g, '.'); + if (moduleName) { + moduleName += ':'; + } + moduleName += file; + return moduleName; + } + return file; +} +/** + * This function reads file contents and caches them in a global LRU cache. + * Returns a Promise filepath => content array for all files that we were able to read. + * + * @param filenames Array of filepaths to read content from. + */ +function readSourceFiles(filenames) { + // we're relying on filenames being de-duped already + if (filenames.length === 0) { + return utils_1.SyncPromise.resolve({}); + } + return new utils_1.SyncPromise(function (resolve) { + var sourceFiles = {}; + var count = 0; + var _loop_1 = function (i) { + var filename = filenames[i]; + var cache = FILE_CONTENT_CACHE.get(filename); + // We have a cache hit + if (cache !== undefined) { + // If it's not null (which means we found a file and have a content) + // we set the content and return it later. + if (cache !== null) { + sourceFiles[filename] = cache; + } + // eslint-disable-next-line no-plusplus + count++; + // In any case we want to skip here then since we have a content already or we couldn't + // read the file and don't want to try again. + if (count === filenames.length) { + resolve(sourceFiles); + } + return "continue"; + } + fs_1.readFile(filename, function (err, data) { + var content = err ? null : data.toString(); + sourceFiles[filename] = content; + // We always want to set the cache, even to null which means there was an error reading the file. + // We do not want to try to read the file again. + FILE_CONTENT_CACHE.set(filename, content); + // eslint-disable-next-line no-plusplus + count++; + if (count === filenames.length) { + resolve(sourceFiles); + } + }); + }; + // eslint-disable-next-line @typescript-eslint/prefer-for-of + for (var i = 0; i < filenames.length; i++) { + _loop_1(i); + } + }); +} +/** + * @hidden + */ +function extractStackFromError(error) { + var stack = stacktrace.parse(error); + if (!stack) { + return []; + } + return stack; +} +exports.extractStackFromError = extractStackFromError; +/** + * @hidden + */ +function parseStack(stack, options) { + var filesToRead = []; + var linesOfContext = options && options.frameContextLines !== undefined ? options.frameContextLines : DEFAULT_LINES_OF_CONTEXT; + var frames = stack.map(function (frame) { + var parsedFrame = { + colno: frame.columnNumber, + filename: frame.fileName || '', + function: getFunction(frame), + lineno: frame.lineNumber, + }; + var isInternal = frame.native || + (parsedFrame.filename && + !parsedFrame.filename.startsWith('/') && + !parsedFrame.filename.startsWith('.') && + parsedFrame.filename.indexOf(':\\') !== 1); + // in_app is all that's not an internal Node function or a module within node_modules + // note that isNative appears to return true even for node core libraries + // see https://github.com/getsentry/raven-node/issues/176 + parsedFrame.in_app = + !isInternal && parsedFrame.filename !== undefined && parsedFrame.filename.indexOf('node_modules/') === -1; + // Extract a module name based on the filename + if (parsedFrame.filename) { + parsedFrame.module = getModule(parsedFrame.filename); + if (!isInternal && linesOfContext > 0 && filesToRead.indexOf(parsedFrame.filename) === -1) { + filesToRead.push(parsedFrame.filename); + } + } + return parsedFrame; + }); + // We do an early return if we do not want to fetch context liens + if (linesOfContext <= 0) { + return utils_1.SyncPromise.resolve(frames); + } + try { + return addPrePostContext(filesToRead, frames, linesOfContext); + } + catch (_) { + // This happens in electron for example where we are not able to read files from asar. + // So it's fine, we recover be just returning all frames without pre/post context. + return utils_1.SyncPromise.resolve(frames); + } +} +exports.parseStack = parseStack; +/** + * This function tries to read the source files + adding pre and post context (source code) + * to a frame. + * @param filesToRead string[] of filepaths + * @param frames StackFrame[] containg all frames + */ +function addPrePostContext(filesToRead, frames, linesOfContext) { + return new utils_1.SyncPromise(function (resolve) { + return readSourceFiles(filesToRead).then(function (sourceFiles) { + var result = frames.map(function (frame) { + if (frame.filename && sourceFiles[frame.filename]) { + try { + var lines = sourceFiles[frame.filename].split('\n'); + utils_1.addContextToFrame(lines, frame, linesOfContext); + } + catch (e) { + // anomaly, being defensive in case + // unlikely to ever happen in practice but can definitely happen in theory + } + } + return frame; + }); + resolve(result); + }); + }); +} +/** + * @hidden + */ +function getExceptionFromError(error, options) { + var name = error.name || error.constructor.name; + var stack = extractStackFromError(error); + return new utils_1.SyncPromise(function (resolve) { + return parseStack(stack, options).then(function (frames) { + var result = { + stacktrace: { + frames: prepareFramesForEvent(frames), + }, + type: name, + value: error.message, + }; + resolve(result); + }); + }); +} +exports.getExceptionFromError = getExceptionFromError; +/** + * @hidden + */ +function parseError(error, options) { + return new utils_1.SyncPromise(function (resolve) { + return getExceptionFromError(error, options).then(function (exception) { + resolve({ + exception: { + values: [exception], + }, + }); + }); + }); +} +exports.parseError = parseError; +/** + * @hidden + */ +function prepareFramesForEvent(stack) { + if (!stack || !stack.length) { + return []; + } + var localStack = stack; + var firstFrameFunction = localStack[0].function || ''; + if (firstFrameFunction.indexOf('captureMessage') !== -1 || firstFrameFunction.indexOf('captureException') !== -1) { + localStack = localStack.slice(1); + } + // The frame where the crash happened, should be the last entry in the array + return localStack.reverse(); +} +exports.prepareFramesForEvent = prepareFramesForEvent; +//# sourceMappingURL=parsers.js.map - function chmodFixSync (orig) { - if (!orig) return orig - return function (target, mode) { - try { - return orig.call(fs, target, mode) - } catch (er) { - if (!chownErOk(er)) throw er - } +/***/ }), +/* 274 */ +/***/ (function(__unusedmodule, exports) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * Tiny class to simplify dealing with subscription set + * + * @export + * @class SubscriptionSet + */ +class SubscriptionSet { + constructor() { + this.set = { + subscribe: {}, + psubscribe: {}, + }; } - } + add(set, channel) { + this.set[mapSet(set)][channel] = true; + } + del(set, channel) { + delete this.set[mapSet(set)][channel]; + } + channels(set) { + return Object.keys(this.set[mapSet(set)]); + } + isEmpty() { + return (this.channels("subscribe").length === 0 && + this.channels("psubscribe").length === 0); + } +} +exports.default = SubscriptionSet; +function mapSet(set) { + if (set === "unsubscribe") { + return "subscribe"; + } + if (set === "punsubscribe") { + return "psubscribe"; + } + return set; +} - function chownFix (orig) { - if (!orig) return orig - return function (target, uid, gid, cb) { - return orig.call(fs, target, uid, gid, function (er) { - if (chownErOk(er)) er = null - if (cb) cb.apply(this, arguments) - }) +/***/ }), +/* 275 */, +/* 276 */, +/* 277 */ +/***/ (function(__unusedmodule, exports) { + +Object.defineProperty(exports, "__esModule", { value: true }); +var defaultFunctionName = ''; +/** + * Safely extract function name from itself + */ +function getFunctionName(fn) { + try { + if (!fn || typeof fn !== 'function') { + return defaultFunctionName; + } + return fn.name || defaultFunctionName; } - } + catch (e) { + // Just accessing custom props in some Selenium environments + // can cause a "Permission denied" exception (see raven-js#495). + return defaultFunctionName; + } +} +exports.getFunctionName = getFunctionName; +//# sourceMappingURL=stacktrace.js.map - function chownFixSync (orig) { - if (!orig) return orig - return function (target, uid, gid) { - try { - return orig.call(fs, target, uid, gid) - } catch (er) { - if (!chownErOk(er)) throw er - } +/***/ }), +/* 278 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +"use strict"; + + +const fastRedact = __webpack_require__(468) +const { redactFmtSym, wildcardFirstSym } = __webpack_require__(230) +const { rx, validator } = fastRedact + +const validate = validator({ + ERR_PATHS_MUST_BE_STRINGS: () => 'pino – redacted paths must be strings', + ERR_INVALID_PATH: (s) => `pino – redact paths array contains an invalid path (${s})` +}) + +const CENSOR = '[Redacted]' +const strict = false // TODO should this be configurable? + +function redaction (opts, serialize) { + const { paths, censor } = handle(opts) + + const shape = paths.reduce((o, str) => { + rx.lastIndex = 0 + const first = rx.exec(str) + const next = rx.exec(str) + + // ns is the top-level path segment, brackets + quoting removed. + let ns = first[1] !== undefined + ? first[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/, '$1') + : first[0] + + if (ns === '*') { + ns = wildcardFirstSym } - } - function statFix (orig) { - if (!orig) return orig - // Older versions of Node erroneously returned signed integers for - // uid + gid. - return function (target, options, cb) { - if (typeof options === 'function') { - cb = options - options = null - } - function callback (er, stats) { - if (stats) { - if (stats.uid < 0) stats.uid += 0x100000000 - if (stats.gid < 0) stats.gid += 0x100000000 - } - if (cb) cb.apply(this, arguments) - } - return options ? orig.call(fs, target, options, callback) - : orig.call(fs, target, callback) + // top level key: + if (next === null) { + o[ns] = null + return o } - } - function statFixSync (orig) { - if (!orig) return orig - // Older versions of Node erroneously returned signed integers for - // uid + gid. - return function (target, options) { - var stats = options ? orig.call(fs, target, options) - : orig.call(fs, target) - if (stats.uid < 0) stats.uid += 0x100000000 - if (stats.gid < 0) stats.gid += 0x100000000 - return stats; + // path with at least two segments: + // if ns is already redacted at the top level, ignore lower level redactions + if (o[ns] === null) { + return o } - } - // ENOSYS means that the fs doesn't support the op. Just ignore - // that, because it doesn't matter. - // - // if there's no getuid, or if getuid() is something other - // than 0, and the error is EINVAL or EPERM, then just ignore - // it. - // - // This specific case is a silent failure in cp, install, tar, - // and most other unix tools that manage permissions. - // - // When running as root, or if other types of errors are - // encountered, then it's strict. - function chownErOk (er) { - if (!er) - return true + const { index } = next + const nextPath = `${str.substr(index, str.length - 1)}` - if (er.code === "ENOSYS") - return true + o[ns] = o[ns] || [] - var nonroot = !process.getuid || process.getuid() !== 0 - if (nonroot) { - if (er.code === "EINVAL" || er.code === "EPERM") - return true + // shape is a mix of paths beginning with literal values and wildcard + // paths [ "a.b.c", "*.b.z" ] should reduce to a shape of + // { "a": [ "b.c", "b.z" ], *: [ "b.z" ] } + // note: "b.z" is in both "a" and * arrays because "a" matches the wildcard. + // (* entry has wildcardFirstSym as key) + if (ns !== wildcardFirstSym && o[ns].length === 0) { + // first time ns's get all '*' redactions so far + o[ns].push(...(o[wildcardFirstSym] || [])) } - return false + if (ns === wildcardFirstSym) { + // new * path gets added to all previously registered literal ns's. + Object.keys(o).forEach(function (k) { + if (o[k]) { + o[k].push(nextPath) + } + }) + } + + o[ns].push(nextPath) + return o + }, {}) + + // the redactor assigned to the format symbol key + // provides top level redaction for instances where + // an object is interpolated into the msg string + const result = { + [redactFmtSym]: fastRedact({ paths, censor, serialize, strict }) + } + + const topCensor = (...args) => + typeof censor === 'function' ? serialize(censor(...args)) : serialize(censor) + + return [...Object.keys(shape), ...Object.getOwnPropertySymbols(shape)].reduce((o, k) => { + // top level key: + if (shape[k] === null) o[k] = topCensor + else o[k] = fastRedact({ paths: shape[k], censor, serialize, strict }) + return o + }, result) +} + +function handle (opts) { + if (Array.isArray(opts)) { + opts = { paths: opts, censor: CENSOR } + validate(opts) + return opts } + var { paths, censor = CENSOR, remove } = opts + if (Array.isArray(paths) === false) { throw Error('pino – redact must contain an array of strings') } + if (remove === true) censor = undefined + validate({ paths, censor }) + + return { paths, censor } } +module.exports = redaction + /***/ }), -/* 251 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +/* 279 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +Object.defineProperty(exports, "__esModule", { value: true }); +var loglevel_1 = __webpack_require__(50); +exports.LogLevel = loglevel_1.LogLevel; +var severity_1 = __webpack_require__(640); +exports.Severity = severity_1.Severity; +var status_1 = __webpack_require__(373); +exports.Status = status_1.Status; +//# sourceMappingURL=index.js.map + +/***/ }), +/* 280 */ +/***/ (function(module) { "use strict"; /*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson + * escape-html + * Copyright(c) 2012-2013 TJ Holowaychuk + * Copyright(c) 2015 Andreas Lubbe + * Copyright(c) 2015 Tiancheng "Timothy" Gu * MIT Licensed */ -/** - * Module dependencies. - * @private - */ - -var debug = __webpack_require__(590)('express:router:route'); -var flatten = __webpack_require__(31); -var Layer = __webpack_require__(805); -var methods = __webpack_require__(203); - /** * Module variables. * @private */ -var slice = Array.prototype.slice; -var toString = Object.prototype.toString; +var matchHtmlRegExp = /["'&<>]/; /** * Module exports. * @public */ -module.exports = Route; +module.exports = escapeHtml; /** - * Initialize `Route` with the given `path`, + * Escape special characters in the given string of html. * - * @param {String} path + * @param {string} string The string to escape for inserting into HTML + * @return {string} * @public */ -function Route(path) { - this.path = path; - this.stack = []; - - debug('new %o', path) - - // route handlers for various http methods - this.methods = {}; -} - -/** - * Determine if the route handles a given method. - * @private - */ +function escapeHtml(string) { + var str = '' + string; + var match = matchHtmlRegExp.exec(str); -Route.prototype._handles_method = function _handles_method(method) { - if (this.methods._all) { - return true; + if (!match) { + return str; } - var name = method.toLowerCase(); - - if (name === 'head' && !this.methods['head']) { - name = 'get'; - } - - return Boolean(this.methods[name]); -}; + var escape; + var html = ''; + var index = 0; + var lastIndex = 0; -/** - * @return {Array} supported HTTP methods - * @private - */ + for (index = match.index; index < str.length; index++) { + switch (str.charCodeAt(index)) { + case 34: // " + escape = '"'; + break; + case 38: // & + escape = '&'; + break; + case 39: // ' + escape = '''; + break; + case 60: // < + escape = '<'; + break; + case 62: // > + escape = '>'; + break; + default: + continue; + } -Route.prototype._options = function _options() { - var methods = Object.keys(this.methods); + if (lastIndex !== index) { + html += str.substring(lastIndex, index); + } - // append automatic head - if (this.methods.get && !this.methods.head) { - methods.push('head'); + lastIndex = index + 1; + html += escape; } - for (var i = 0; i < methods.length; i++) { - // make upper case - methods[i] = methods[i].toUpperCase(); - } + return lastIndex !== index + ? html + str.substring(lastIndex, index) + : html; +} - return methods; -}; -/** - * dispatch req, res into this route - * @private - */ +/***/ }), +/* 281 */ +/***/ (function(module) { -Route.prototype.dispatch = function dispatch(req, res, done) { - var idx = 0; - var stack = this.stack; - if (stack.length === 0) { - return done(); - } +"use strict"; - var method = req.method.toLowerCase(); - if (method === 'head' && !this.methods['head']) { - method = 'get'; - } - req.route = this; +const processFn = (fn, options) => function (...args) { + const P = options.promiseModule; - next(); + return new P((resolve, reject) => { + if (options.multiArgs) { + args.push((...result) => { + if (options.errorFirst) { + if (result[0]) { + reject(result); + } else { + result.shift(); + resolve(result); + } + } else { + resolve(result); + } + }); + } else if (options.errorFirst) { + args.push((error, result) => { + if (error) { + reject(error); + } else { + resolve(result); + } + }); + } else { + args.push(resolve); + } - function next(err) { - // signal to exit route - if (err && err === 'route') { - return done(); - } + fn.apply(this, args); + }); +}; - // signal to exit router - if (err && err === 'router') { - return done(err) - } +module.exports = (input, options) => { + options = Object.assign({ + exclude: [/.+(Sync|Stream)$/], + errorFirst: true, + promiseModule: Promise + }, options); - var layer = stack[idx++]; - if (!layer) { - return done(err); - } + const objType = typeof input; + if (!(input !== null && (objType === 'object' || objType === 'function'))) { + throw new TypeError(`Expected \`input\` to be a \`Function\` or \`Object\`, got \`${input === null ? 'null' : objType}\``); + } - if (layer.method && layer.method !== method) { - return next(err); - } + const filter = key => { + const match = pattern => typeof pattern === 'string' ? key === pattern : pattern.test(key); + return options.include ? options.include.some(match) : !options.exclude.some(match); + }; - if (err) { - layer.handle_error(err, req, res, next); - } else { - layer.handle_request(req, res, next); - } - } -}; + let ret; + if (objType === 'function') { + ret = function (...args) { + return options.excludeMain ? input(...args) : processFn(input, options).apply(this, args); + }; + } else { + ret = Object.create(Object.getPrototypeOf(input)); + } -/** - * Add a handler for all HTTP verbs to this route. - * - * Behaves just like middleware and can respond or call `next` - * to continue processing. - * - * You can use multiple `.all` call to add multiple handlers. - * - * function check_something(req, res, next){ - * next(); - * }; - * - * function validate_user(req, res, next){ - * next(); - * }; - * - * route - * .all(validate_user) - * .all(check_something) - * .get(function(req, res, next){ - * res.send('hello world'); - * }); - * - * @param {function} handler - * @return {Route} for chaining - * @api public - */ + for (const key in input) { // eslint-disable-line guard-for-in + const property = input[key]; + ret[key] = typeof property === 'function' && filter(key) ? processFn(property, options) : property; + } -Route.prototype.all = function all() { - var handles = flatten(slice.call(arguments)); + return ret; +}; - for (var i = 0; i < handles.length; i++) { - var handle = handles[i]; - if (typeof handle !== 'function') { - var type = toString.call(handle); - var msg = 'Route.all() requires a callback function but got a ' + type - throw new TypeError(msg); - } +/***/ }), +/* 282 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - var layer = Layer('/', {}, handle); - layer.method = undefined; +var timespan = __webpack_require__(530); +var PS_SUPPORTED = __webpack_require__(487); +var jws = __webpack_require__(170); +var includes = __webpack_require__(531); +var isBoolean = __webpack_require__(969); +var isInteger = __webpack_require__(565); +var isNumber = __webpack_require__(611); +var isPlainObject = __webpack_require__(720); +var isString = __webpack_require__(96); +var once = __webpack_require__(937); - this.methods._all = true; - this.stack.push(layer); - } +var SUPPORTED_ALGS = ['RS256', 'RS384', 'RS512', 'ES256', 'ES384', 'ES512', 'HS256', 'HS384', 'HS512', 'none'] +if (PS_SUPPORTED) { + SUPPORTED_ALGS.splice(3, 0, 'PS256', 'PS384', 'PS512'); +} - return this; +var sign_options_schema = { + expiresIn: { isValid: function(value) { return isInteger(value) || (isString(value) && value); }, message: '"expiresIn" should be a number of seconds or string representing a timespan' }, + notBefore: { isValid: function(value) { return isInteger(value) || (isString(value) && value); }, message: '"notBefore" should be a number of seconds or string representing a timespan' }, + audience: { isValid: function(value) { return isString(value) || Array.isArray(value); }, message: '"audience" must be a string or array' }, + algorithm: { isValid: includes.bind(null, SUPPORTED_ALGS), message: '"algorithm" must be a valid string enum value' }, + header: { isValid: isPlainObject, message: '"header" must be an object' }, + encoding: { isValid: isString, message: '"encoding" must be a string' }, + issuer: { isValid: isString, message: '"issuer" must be a string' }, + subject: { isValid: isString, message: '"subject" must be a string' }, + jwtid: { isValid: isString, message: '"jwtid" must be a string' }, + noTimestamp: { isValid: isBoolean, message: '"noTimestamp" must be a boolean' }, + keyid: { isValid: isString, message: '"keyid" must be a string' }, + mutatePayload: { isValid: isBoolean, message: '"mutatePayload" must be a boolean' } }; -methods.forEach(function(method){ - Route.prototype[method] = function(){ - var handles = flatten(slice.call(arguments)); - - for (var i = 0; i < handles.length; i++) { - var handle = handles[i]; +var registered_claims_schema = { + iat: { isValid: isNumber, message: '"iat" should be a number of seconds' }, + exp: { isValid: isNumber, message: '"exp" should be a number of seconds' }, + nbf: { isValid: isNumber, message: '"nbf" should be a number of seconds' } +}; - if (typeof handle !== 'function') { - var type = toString.call(handle); - var msg = 'Route.' + method + '() requires a callback function but got a ' + type - throw new Error(msg); +function validate(schema, allowUnknown, object, parameterName) { + if (!isPlainObject(object)) { + throw new Error('Expected "' + parameterName + '" to be a plain object.'); + } + Object.keys(object) + .forEach(function(key) { + var validator = schema[key]; + if (!validator) { + if (!allowUnknown) { + throw new Error('"' + key + '" is not allowed in "' + parameterName + '"'); + } + return; + } + if (!validator.isValid(object[key])) { + throw new Error(validator.message); } + }); +} - debug('%s %o', method, this.path) +function validateOptions(options) { + return validate(sign_options_schema, false, options, 'options'); +} - var layer = Layer('/', {}, handle); - layer.method = method; +function validatePayload(payload) { + return validate(registered_claims_schema, true, payload, 'payload'); +} - this.methods[method] = true; - this.stack.push(layer); - } +var options_to_payload = { + 'audience': 'aud', + 'issuer': 'iss', + 'subject': 'sub', + 'jwtid': 'jti' +}; - return this; - }; -}); +var options_for_objects = [ + 'expiresIn', + 'notBefore', + 'noTimestamp', + 'audience', + 'issuer', + 'subject', + 'jwtid', +]; +module.exports = function (payload, secretOrPrivateKey, options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } else { + options = options || {}; + } -/***/ }), -/* 252 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + var isObjectPayload = typeof payload === 'object' && + !Buffer.isBuffer(payload); -var isCore = __webpack_require__(353); -var fs = __webpack_require__(747); -var path = __webpack_require__(622); -var caller = __webpack_require__(465); -var nodeModulesPaths = __webpack_require__(455); -var normalizeOptions = __webpack_require__(899); + var header = Object.assign({ + alg: options.algorithm || 'HS256', + typ: isObjectPayload ? 'JWT' : undefined, + kid: options.keyid + }, options.header); -var defaultIsFile = function isFile(file) { - try { - var stat = fs.statSync(file); - } catch (e) { - if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false; - throw e; + function failure(err) { + if (callback) { + return callback(err); } - return stat.isFile() || stat.isFIFO(); -}; + throw err; + } -var defaultIsDir = function isDirectory(dir) { + if (!secretOrPrivateKey && options.algorithm !== 'none') { + return failure(new Error('secretOrPrivateKey must have a value')); + } + + if (typeof payload === 'undefined') { + return failure(new Error('payload is required')); + } else if (isObjectPayload) { try { - var stat = fs.statSync(dir); - } catch (e) { - if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false; - throw e; + validatePayload(payload); } - return stat.isDirectory(); -}; - -var maybeUnwrapSymlink = function maybeUnwrapSymlink(x, opts) { - if (opts && opts.preserveSymlinks === false) { - try { - return fs.realpathSync(x); - } catch (realPathErr) { - if (realPathErr.code !== 'ENOENT') { - throw realPathErr; - } - } + catch (error) { + return failure(error); } - return x; -}; - -var getPackageCandidates = function getPackageCandidates(x, start, opts) { - var dirs = nodeModulesPaths(start, opts, x); - for (var i = 0; i < dirs.length; i++) { - dirs[i] = path.join(dirs[i], x); + if (!options.mutatePayload) { + payload = Object.assign({},payload); } - return dirs; -}; + } else { + var invalid_options = options_for_objects.filter(function (opt) { + return typeof options[opt] !== 'undefined'; + }); -module.exports = function resolveSync(x, options) { - if (typeof x !== 'string') { - throw new TypeError('Path must be a string.'); + if (invalid_options.length > 0) { + return failure(new Error('invalid ' + invalid_options.join(',') + ' option for ' + (typeof payload ) + ' payload')); } - var opts = normalizeOptions(x, options); - - var isFile = opts.isFile || defaultIsFile; - var readFileSync = opts.readFileSync || fs.readFileSync; - var isDirectory = opts.isDirectory || defaultIsDir; - var packageIterator = opts.packageIterator; - - var extensions = opts.extensions || ['.js']; - var basedir = opts.basedir || path.dirname(caller()); - var parent = opts.filename || basedir; + } - opts.paths = opts.paths || []; + if (typeof payload.exp !== 'undefined' && typeof options.expiresIn !== 'undefined') { + return failure(new Error('Bad "options.expiresIn" option the payload already has an "exp" property.')); + } - // ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory - var absoluteStart = maybeUnwrapSymlink(path.resolve(basedir), opts); + if (typeof payload.nbf !== 'undefined' && typeof options.notBefore !== 'undefined') { + return failure(new Error('Bad "options.notBefore" option the payload already has an "nbf" property.')); + } - if ((/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/).test(x)) { - var res = path.resolve(absoluteStart, x); - if (x === '.' || x === '..' || x.slice(-1) === '/') res += '/'; - var m = loadAsFileSync(res) || loadAsDirectorySync(res); - if (m) return maybeUnwrapSymlink(m, opts); - } else if (isCore(x)) { - return x; - } else { - var n = loadNodeModulesSync(x, absoluteStart); - if (n) return maybeUnwrapSymlink(n, opts); - } + try { + validateOptions(options); + } + catch (error) { + return failure(error); + } - var err = new Error("Cannot find module '" + x + "' from '" + parent + "'"); - err.code = 'MODULE_NOT_FOUND'; - throw err; + var timestamp = payload.iat || Math.floor(Date.now() / 1000); - function loadAsFileSync(x) { - var pkg = loadpkg(path.dirname(x)); + if (options.noTimestamp) { + delete payload.iat; + } else if (isObjectPayload) { + payload.iat = timestamp; + } - if (pkg && pkg.dir && pkg.pkg && opts.pathFilter) { - var rfile = path.relative(pkg.dir, x); - var r = opts.pathFilter(pkg.pkg, x, rfile); - if (r) { - x = path.resolve(pkg.dir, r); // eslint-disable-line no-param-reassign - } - } + if (typeof options.notBefore !== 'undefined') { + try { + payload.nbf = timespan(options.notBefore, timestamp); + } + catch (err) { + return failure(err); + } + if (typeof payload.nbf === 'undefined') { + return failure(new Error('"notBefore" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60')); + } + } - if (isFile(x)) { - return x; - } + if (typeof options.expiresIn !== 'undefined' && typeof payload === 'object') { + try { + payload.exp = timespan(options.expiresIn, timestamp); + } + catch (err) { + return failure(err); + } + if (typeof payload.exp === 'undefined') { + return failure(new Error('"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60')); + } + } - for (var i = 0; i < extensions.length; i++) { - var file = x + extensions[i]; - if (isFile(file)) { - return file; - } - } + Object.keys(options_to_payload).forEach(function (key) { + var claim = options_to_payload[key]; + if (typeof options[key] !== 'undefined') { + if (typeof payload[claim] !== 'undefined') { + return failure(new Error('Bad "options.' + key + '" option. The payload already has an "' + claim + '" property.')); + } + payload[claim] = options[key]; } + }); - function loadpkg(dir) { - if (dir === '' || dir === '/') return; - if (process.platform === 'win32' && (/^\w:[/\\]*$/).test(dir)) { - return; - } - if ((/[/\\]node_modules[/\\]*$/).test(dir)) return; + var encoding = options.encoding || 'utf8'; - var pkgfile = path.join(maybeUnwrapSymlink(dir, opts), 'package.json'); + if (typeof callback === 'function') { + callback = callback && once(callback); - if (!isFile(pkgfile)) { - return loadpkg(path.dirname(dir)); - } + jws.createSign({ + header: header, + privateKey: secretOrPrivateKey, + payload: payload, + encoding: encoding + }).once('error', callback) + .once('done', function (signature) { + callback(null, signature); + }); + } else { + return jws.sign({header: header, payload: payload, secret: secretOrPrivateKey, encoding: encoding}); + } +}; - var body = readFileSync(pkgfile); - try { - var pkg = JSON.parse(body); - } catch (jsonErr) {} +/***/ }), +/* 283 */, +/* 284 */ +/***/ (function(__unusedmodule, __unusedexports, __webpack_require__) { - if (pkg && opts.packageFilter) { - // v2 will pass pkgfile - pkg = opts.packageFilter(pkg, /*pkgfile,*/ dir); // eslint-disable-line spaced-comment - } +const Layer = __webpack_require__(322); +const Router = __webpack_require__(987); - return { pkg: pkg, dir: dir }; - } +const last = (arr = []) => arr[arr.length - 1]; +const noop = Function.prototype; - function loadAsDirectorySync(x) { - var pkgfile = path.join(maybeUnwrapSymlink(x, opts), '/package.json'); - if (isFile(pkgfile)) { - try { - var body = readFileSync(pkgfile, 'UTF8'); - var pkg = JSON.parse(body); - } catch (e) {} +function copyFnProps(oldFn, newFn) { + Object.keys(oldFn).forEach((key) => { + newFn[key] = oldFn[key]; + }); + return newFn; +} - if (pkg && opts.packageFilter) { - // v2 will pass pkgfile - pkg = opts.packageFilter(pkg, /*pkgfile,*/ x); // eslint-disable-line spaced-comment - } +function wrap(fn) { + const newFn = function newFn(...args) { + const ret = fn.apply(this, args); + const next = (args.length === 5 ? args[2] : last(args)) || noop; + if (ret && ret.catch) ret.catch(err => next(err)); + return ret; + }; + Object.defineProperty(newFn, 'length', { + value: fn.length, + writable: false, + }); + return copyFnProps(fn, newFn); +} - if (pkg && pkg.main) { - if (typeof pkg.main !== 'string') { - var mainError = new TypeError('package “' + pkg.name + '” `main` must be a string'); - mainError.code = 'INVALID_PACKAGE_MAIN'; - throw mainError; - } - if (pkg.main === '.' || pkg.main === './') { - pkg.main = 'index'; - } - try { - var m = loadAsFileSync(path.resolve(x, pkg.main)); - if (m) return m; - var n = loadAsDirectorySync(path.resolve(x, pkg.main)); - if (n) return n; - } catch (e) {} - } - } +function patchRouterParam() { + const originalParam = Router.prototype.constructor.param; + Router.prototype.constructor.param = function param(name, fn) { + fn = wrap(fn); + return originalParam.call(this, name, fn); + }; +} - return loadAsFileSync(path.join(x, '/index')); - } +Object.defineProperty(Layer.prototype, 'handle', { + enumerable: true, + get() { + return this.__handle; + }, + set(fn) { + fn = wrap(fn); + this.__handle = fn; + }, +}); - function loadNodeModulesSync(x, start) { - var thunk = function () { return getPackageCandidates(x, start, opts); }; - var dirs = packageIterator ? packageIterator(x, start, thunk, opts) : thunk(); +patchRouterParam(); - for (var i = 0; i < dirs.length; i++) { - var dir = dirs[i]; - if (isDirectory(path.dirname(dir))) { - var m = loadAsFileSync(dir); - if (m) return m; - var n = loadAsDirectorySync(dir); - if (n) return n; - } + +/***/ }), +/* 285 */, +/* 286 */, +/* 287 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +const stream_1 = __webpack_require__(413); +/** + * Convenient class to convert the process of scaning keys to a readable stream. + * + * @export + * @class ScanStream + * @extends {Readable} + */ +class ScanStream extends stream_1.Readable { + constructor(opt) { + super(opt); + this.opt = opt; + this._redisCursor = "0"; + this._redisDrained = false; + } + _read() { + if (this._redisDrained) { + this.push(null); + return; + } + const args = [this._redisCursor]; + if (this.opt.key) { + args.unshift(this.opt.key); + } + if (this.opt.match) { + args.push("MATCH", this.opt.match); + } + if (this.opt.count) { + args.push("COUNT", String(this.opt.count)); } + this.opt.redis[this.opt.command](args, (err, res) => { + if (err) { + this.emit("error", err); + return; + } + this._redisCursor = res[0] instanceof Buffer ? res[0].toString() : res[0]; + if (this._redisCursor === "0") { + this._redisDrained = true; + } + this.push(res[1]); + }); } -}; + close() { + this._redisDrained = true; + } +} +exports.default = ScanStream; + + +/***/ }), +/* 288 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + + +// Update this array if you add/rename/remove files in this directory. +// We support Browserify by skipping automatic module discovery and requiring modules directly. +var modules = [ + __webpack_require__(162), + __webpack_require__(797), + __webpack_require__(645), + __webpack_require__(877), + __webpack_require__(762), + __webpack_require__(28), + __webpack_require__(1), + __webpack_require__(92), +]; + +// Put all encoding/alias/codec definitions to single object and export it. +for (var i = 0; i < modules.length; i++) { + var module = modules[i]; + for (var enc in module) + if (Object.prototype.hasOwnProperty.call(module, enc)) + exports[enc] = module[enc]; +} /***/ }), -/* 253 */ +/* 289 */, +/* 290 */ /***/ (function(module, __unusedexports, __webpack_require__) { -module.exports = authenticate; +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. + + +module.exports = Writable; +/* */ + +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} // It seems a linked list but it is not +// there will be only 2 of these for each stream + + +function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + + this.finish = function () { + onCorkedFinish(_this, state); + }; +} +/* */ + +/**/ -const { Deprecation } = __webpack_require__(692); -const once = __webpack_require__(969); -const deprecateAuthenticate = once((log, deprecation) => log.warn(deprecation)); +var Duplex; +/**/ -function authenticate(state, options) { - deprecateAuthenticate( - state.octokit.log, - new Deprecation( - '[@octokit/rest] octokit.authenticate() is deprecated. Use "auth" constructor option instead.' - ) - ); +Writable.WritableState = WritableState; +/**/ - if (!options) { - state.auth = false; - return; +var internalUtil = { + deprecate: __webpack_require__(22) +}; +/**/ + +/**/ + +var Stream = __webpack_require__(343); +/**/ + + +var Buffer = __webpack_require__(293).Buffer; + +var OurUint8Array = global.Uint8Array || function () {}; + +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} + +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} + +var destroyImpl = __webpack_require__(242); + +var _require = __webpack_require__(528), + getHighWaterMark = _require.getHighWaterMark; + +var _require$codes = __webpack_require__(954).codes, + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, + ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, + ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, + ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; + +var errorOrDestroy = destroyImpl.errorOrDestroy; + +__webpack_require__(689)(Writable, Stream); + +function nop() {} + +function WritableState(options, stream, isDuplex) { + Duplex = Duplex || __webpack_require__(238); + options = options || {}; // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream, + // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. + + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream + // contains buffers or objects. + + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + + this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called + + this.finalCalled = false; // drain event flag. + + this.needDrain = false; // at the start of calling end() + + this.ending = false; // when end() has been called, and returned + + this.ended = false; // when 'finish' is emitted + + this.finished = false; // has it been destroyed + + this.destroyed = false; // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + + this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + + this.length = 0; // a flag to see when we're in the middle of a write. + + this.writing = false; // when true all writes will be buffered until .uncork() call + + this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + + this.sync = true; // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + + this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) + + this.onwrite = function (er) { + onwrite(stream, er); + }; // the callback that the user supplies to write(chunk,encoding,cb) + + + this.writecb = null; // the amount that is being written when _write is called. + + this.writelen = 0; + this.bufferedRequest = null; + this.lastBufferedRequest = null; // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + + this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + + this.prefinished = false; // True if the error was already emitted and should not be thrown again + + this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. + + this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') + + this.autoDestroy = !!options.autoDestroy; // count buffered requests + + this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + + this.corkedRequestsFree = new CorkedRequest(this); +} + +WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + + while (current) { + out.push(current); + current = current.next; } - switch (options.type) { - case "basic": - if (!options.username || !options.password) { - throw new Error( - "Basic authentication requires both a username and password to be set" - ); - } - break; + return out; +}; - case "oauth": - if (!options.token && !(options.key && options.secret)) { - throw new Error( - "OAuth2 authentication requires a token or key & secret to be set" - ); - } - break; +(function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function writableStateBufferGetter() { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} +})(); // Test _writableState for inheritance to account for Duplex streams, +// whose prototype chain only points to Readable. - case "token": - case "app": - if (!options.token) { - throw new Error("Token authentication requires a token to be set"); - } - break; - default: - throw new Error( - "Invalid authentication type, must be 'basic', 'oauth', 'token' or 'app'" - ); +var realHasInstance; + +if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function value(object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; + return object && object._writableState instanceof WritableState; + } + }); +} else { + realHasInstance = function realHasInstance(object) { + return object instanceof this; + }; +} + +function Writable(options) { + Duplex = Duplex || __webpack_require__(238); // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + // Checking for a Stream.Duplex instance is faster here instead of inside + // the WritableState constructor, at least with V8 6.5 + + var isDuplex = this instanceof Duplex; + if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); + this._writableState = new WritableState(options, this, isDuplex); // legacy. + + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + if (typeof options.writev === 'function') this._writev = options.writev; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + if (typeof options.final === 'function') this._final = options.final; + } + + Stream.call(this); +} // Otherwise people can pipe Writable streams, which is just wrong. + + +Writable.prototype.pipe = function () { + errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); +}; + +function writeAfterEnd(stream, cb) { + var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb + + errorOrDestroy(stream, er); + process.nextTick(cb, er); +} // Checks that a user-supplied chunk is valid, especially for the particular +// mode the stream is in. Currently this means that `null` is never accepted +// and undefined/non-string values are only allowed in object mode. + + +function validChunk(stream, state, chunk, cb) { + var er; + + if (chunk === null) { + er = new ERR_STREAM_NULL_VALUES(); + } else if (typeof chunk !== 'string' && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); } - state.auth = options; + if (er) { + errorOrDestroy(stream, er); + process.nextTick(cb, er); + return false; + } + + return true; } +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; -/***/ }), -/* 254 */, -/* 255 */, -/* 256 */, -/* 257 */ -/***/ (function(module) { + var isBuf = !state.objectMode && _isUint8Array(chunk); -var JsonWebTokenError = function (message, error) { - Error.call(this, message); - if(Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); + if (isBuf && !Buffer.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); } - this.name = 'JsonWebTokenError'; - this.message = message; - if (error) this.inner = error; + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + if (typeof cb !== 'function') cb = nop; + if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } + return ret; }; -JsonWebTokenError.prototype = Object.create(Error.prototype); -JsonWebTokenError.prototype.constructor = JsonWebTokenError; +Writable.prototype.cork = function () { + this._writableState.corked++; +}; -module.exports = JsonWebTokenError; +Writable.prototype.uncork = function () { + var state = this._writableState; + if (state.corked) { + state.corked--; + if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; -/***/ }), -/* 258 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; -"use strict"; +Object.defineProperty(Writable.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } +}); -Object.defineProperty(exports, "__esModule", { value: true }); -const commands = __webpack_require__(281); -const calculateSlot = __webpack_require__(407); -const standard_as_callback_1 = __webpack_require__(207); -const utils_1 = __webpack_require__(200); -const lodash_1 = __webpack_require__(961); -const promiseContainer_1 = __webpack_require__(337); -/** - * Command instance - * - * It's rare that you need to create a Command instance yourself. - * - * @export - * @class Command - * - * @example - * ```js - * var infoCommand = new Command('info', null, function (err, result) { - * console.log('result', result); - * }); - * - * redis.sendCommand(infoCommand); - * - * // When no callback provided, Command instance will have a `promise` property, - * // which will resolve/reject with the result of the command. - * var getCommand = new Command('get', ['foo']); - * getCommand.promise.then(function (result) { - * console.log('result', result); - * }); - * ``` - * @see {@link Redis#sendCommand} which can send a Command instance to Redis - */ -class Command { - /** - * Creates an instance of Command. - * @param {string} name Command name - * @param {(Array)} [args=[]] An array of command arguments - * @param {ICommandOptions} [options={}] - * @param {CallbackFunction} [callback] The callback that handles the response. - * If omit, the response will be handled via Promise - * @memberof Command - */ - constructor(name, args = [], options = {}, callback) { - this.name = name; - this.transformed = false; - this.isCustomCommand = false; - this.inTransaction = false; - this.replyEncoding = options.replyEncoding; - this.errorStack = options.errorStack; - this.args = lodash_1.flatten(args); - this.callback = callback; - this.initPromise(); - if (options.keyPrefix) { - this._iterateKeys((key) => options.keyPrefix + key); - } - if (options.readOnly) { - this.isReadOnly = true; - } +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + + return chunk; +} + +Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } +}); // if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. + +function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; } - static getFlagMap() { - if (!this.flagMap) { - this.flagMap = Object.keys(Command.FLAGS).reduce((map, flagName) => { - map[flagName] = {}; - Command.FLAGS[flagName].forEach((commandName) => { - map[flagName][commandName] = true; - }); - return map; - }, {}); - } - return this.flagMap; + } + + var len = state.objectMode ? 1 : chunk.length; + state.length += len; + var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. + + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; + + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; } - /** - * Check whether the command has the flag - * - * @param {string} flagName - * @param {string} commandName - * @return {boolean} - */ - static checkFlag(flagName, commandName) { - return !!this.getFlagMap()[flagName][commandName]; + + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; +} + +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} + +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + process.nextTick(cb, er); // this can emit finish, and it will always happen + // after error + + process.nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); // this can emit finish, but finish must + // always follow error + + finishMaybe(stream, state); + } +} + +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} + +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); + onwriteStateUpdate(state); + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state) || stream.destroyed; + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); } - static setArgumentTransformer(name, func) { - this._transformer.argument[name] = func; + + if (sync) { + process.nextTick(afterWrite, stream, state, finished, cb); + } else { + afterWrite(stream, state, finished, cb); } - static setReplyTransformer(name, func) { - this._transformer.reply[name] = func; + } +} + +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} // Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. + + +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} // if there's something in the buffer waiting, then process it + + +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + var count = 0; + var allBuffers = true; + + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; } - initPromise() { - const Promise = promiseContainer_1.get(); - const promise = new Promise((resolve, reject) => { - if (!this.transformed) { - this.transformed = true; - const transformer = Command._transformer.argument[this.name]; - if (transformer) { - this.args = transformer(this.args); - } - this.stringifyArguments(); - } - this.resolve = this._convertValue(resolve); - if (this.errorStack) { - this.reject = (err) => { - reject(utils_1.optimizeErrorStack(err, this.errorStack, __dirname)); - }; - } - else { - this.reject = reject; - } - }); - this.promise = standard_as_callback_1.default(promise, this.callback); + + buffer.allBuffers = allBuffers; + doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + + state.pendingcb++; + state.lastBufferedRequest = null; + + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); } - getSlot() { - if (typeof this.slot === "undefined") { - const key = this.getKeys()[0]; - this.slot = key == null ? null : calculateSlot(key); - } - return this.slot; + + state.bufferedRequestCount = 0; + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + + if (state.writing) { + break; + } } - getKeys() { - return this._iterateKeys(); + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequest = entry; + state.bufferProcessing = false; +} + +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); +}; + +Writable.prototype._writev = null; + +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks + + if (state.corked) { + state.corked = 1; + this.uncork(); + } // ignore unnecessary end() calls. + + + if (!state.ending) endWritable(this, state, cb); + return this; +}; + +Object.defineProperty(Writable.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } +}); + +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} + +function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + + if (err) { + errorOrDestroy(stream, err); } - /** - * Iterate through the command arguments that are considered keys. - * - * @param {Function} [transform=(key) => key] The transformation that should be applied to - * each key. The transformations will persist. - * @returns {string[]} The keys of the command. - * @memberof Command - */ - _iterateKeys(transform = (key) => key) { - if (typeof this.keys === "undefined") { - this.keys = []; - if (commands.exists(this.name)) { - const keyIndexes = commands.getKeyIndexes(this.name, this.args); - for (const index of keyIndexes) { - this.args[index] = transform(this.args[index]); - this.keys.push(this.args[index]); - } - } + + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); + }); +} + +function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function' && !state.destroyed) { + state.pendingcb++; + state.finalCalled = true; + process.nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } + } +} + +function finishMaybe(stream, state) { + var need = needFinish(state); + + if (need) { + prefinish(stream, state); + + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); + + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the readable side is ready for autoDestroy as well + var rState = stream._readableState; + + if (!rState || rState.autoDestroy && rState.endEmitted) { + stream.destroy(); } - return this.keys; - } - /** - * Convert command to writable buffer or string - * - * @return {string|Buffer} - * @see {@link Redis#sendCommand} - * @public - */ - toWritable() { - let bufferMode = false; - for (const arg of this.args) { - if (arg instanceof Buffer) { - bufferMode = true; - break; - } - } - let result; - const commandStr = "*" + - (this.args.length + 1) + - "\r\n$" + - Buffer.byteLength(this.name) + - "\r\n" + - this.name + - "\r\n"; - if (bufferMode) { - const buffers = new MixedBuffers(); - buffers.push(commandStr); - for (const arg of this.args) { - if (arg instanceof Buffer) { - if (arg.length === 0) { - buffers.push("$0\r\n\r\n"); - } - else { - buffers.push("$" + arg.length + "\r\n"); - buffers.push(arg); - buffers.push("\r\n"); - } - } - else { - buffers.push("$" + - Buffer.byteLength(arg) + - "\r\n" + - arg + - "\r\n"); - } - } - result = buffers.toBuffer(); - } - else { - result = commandStr; - for (const arg of this.args) { - result += - "$" + - Buffer.byteLength(arg) + - "\r\n" + - arg + - "\r\n"; - } - } - return result; - } - stringifyArguments() { - for (let i = 0; i < this.args.length; ++i) { - const arg = this.args[i]; - if (!(arg instanceof Buffer) && typeof arg !== "string") { - this.args[i] = utils_1.toArg(arg); - } - } - } - /** - * Convert the value from buffer to the target encoding. - * - * @private - * @param {Function} resolve The resolve function of the Promise - * @returns {Function} A funtion to transform and resolve a value - * @memberof Command - */ - _convertValue(resolve) { - return (value) => { - try { - resolve(this.transformReply(value)); - } - catch (err) { - this.reject(err); - } - return this.promise; - }; - } - /** - * Convert buffer/buffer[] to string/string[], - * and apply reply transformer. - * - * @memberof Command - */ - transformReply(result) { - if (this.replyEncoding) { - result = utils_1.convertBufferToString(result, this.replyEncoding); - } - const transformer = Command._transformer.reply[this.name]; - if (transformer) { - result = transformer(result); - } - return result; - } -} -exports.default = Command; -Command.FLAGS = { - VALID_IN_SUBSCRIBER_MODE: [ - "subscribe", - "psubscribe", - "unsubscribe", - "punsubscribe", - "ping", - "quit", - ], - VALID_IN_MONITOR_MODE: ["monitor", "auth"], - ENTER_SUBSCRIBER_MODE: ["subscribe", "psubscribe"], - EXIT_SUBSCRIBER_MODE: ["unsubscribe", "punsubscribe"], - WILL_DISCONNECT: ["quit"], -}; -Command._transformer = { - argument: {}, - reply: {}, -}; -const msetArgumentTransformer = function (args) { - if (args.length === 1) { - if (typeof Map !== "undefined" && args[0] instanceof Map) { - return utils_1.convertMapToArray(args[0]); - } - if (typeof args[0] === "object" && args[0] !== null) { - return utils_1.convertObjectToArray(args[0]); - } - } - return args; -}; -Command.setArgumentTransformer("mset", msetArgumentTransformer); -Command.setArgumentTransformer("msetnx", msetArgumentTransformer); -Command.setArgumentTransformer("hmset", function (args) { - if (args.length === 2) { - if (typeof Map !== "undefined" && args[1] instanceof Map) { - return [args[0]].concat(utils_1.convertMapToArray(args[1])); - } - if (typeof args[1] === "object" && args[1] !== null) { - return [args[0]].concat(utils_1.convertObjectToArray(args[1])); - } - } - return args; -}); -Command.setReplyTransformer("hgetall", function (result) { - if (Array.isArray(result)) { - const obj = {}; - for (let i = 0; i < result.length; i += 2) { - obj[result[i]] = result[i + 1]; - } - return obj; - } - return result; -}); -Command.setArgumentTransformer("hset", function (args) { - if (args.length === 2) { - if (typeof Map !== "undefined" && args[1] instanceof Map) { - return [args[0]].concat(utils_1.convertMapToArray(args[1])); - } - if (typeof args[1] === "object" && args[1] !== null) { - return [args[0]].concat(utils_1.convertObjectToArray(args[1])); - } - } - return args; -}); -class MixedBuffers { - constructor() { - this.length = 0; - this.items = []; - } - push(x) { - this.length += Buffer.byteLength(x); - this.items.push(x); - } - toBuffer() { - const result = Buffer.allocUnsafe(this.length); - let offset = 0; - for (const item of this.items) { - const length = Buffer.byteLength(item); - Buffer.isBuffer(item) - ? item.copy(result, offset) - : result.write(item, offset, length); - offset += length; - } - return result; + } } + } + + return need; } +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); -/***/ }), -/* 259 */ -/***/ (function(module) { + if (cb) { + if (state.finished) process.nextTick(cb);else stream.once('finish', cb); + } -/** - * Gets the stack value for `key`. - * - * @private - * @name get - * @memberOf Stack - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ -function stackGet(key) { - return this.__data__.get(key); + state.ended = true; + stream.writable = false; } -module.exports = stackGet; - +function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; -/***/ }), -/* 260 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } // reuse the free corkReq. -// Note: since nyc uses this module to output coverage, any lines -// that are in the direct sync flow of nyc's outputCoverage are -// ignored, since we can never get coverage for them. -var assert = __webpack_require__(357) -var signals = __webpack_require__(654) -var EE = __webpack_require__(614) -/* istanbul ignore if */ -if (typeof EE !== 'function') { - EE = EE.EventEmitter + state.corkedRequestsFree.next = corkReq; } -var emitter -if (process.__signal_exit_emitter__) { - emitter = process.__signal_exit_emitter__ -} else { - emitter = process.__signal_exit_emitter__ = new EE() - emitter.count = 0 - emitter.emitted = {} -} +Object.defineProperty(Writable.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._writableState === undefined) { + return false; + } -// Because this emitter is a global, we have to check to see if a -// previous version of this library failed to enable infinite listeners. -// I know what you're about to say. But literally everything about -// signal-exit is a compromise with evil. Get used to it. -if (!emitter.infinite) { - emitter.setMaxListeners(Infinity) - emitter.infinite = true -} + return this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed -module.exports = function (cb, opts) { - assert.equal(typeof cb, 'function', 'a callback must be provided for exit handler') - if (loaded === false) { - load() + this._writableState.destroyed = value; } +}); +Writable.prototype.destroy = destroyImpl.destroy; +Writable.prototype._undestroy = destroyImpl.undestroy; - var ev = 'exit' - if (opts && opts.alwaysLast) { - ev = 'afterexit' - } +Writable.prototype._destroy = function (err, cb) { + cb(err); +}; - var remove = function () { - emitter.removeListener(ev, cb) - if (emitter.listeners('exit').length === 0 && - emitter.listeners('afterexit').length === 0) { - unload() - } - } - emitter.on(ev, cb) +/***/ }), +/* 291 */, +/* 292 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { - return remove -} +"use strict"; -module.exports.unload = unload -function unload () { - if (!loaded) { - return - } - loaded = false - signals.forEach(function (sig) { - try { - process.removeListener(sig, sigListeners[sig]) - } catch (er) {} - }) - process.emit = originalProcessEmit - process.reallyExit = originalProcessReallyExit - emitter.count -= 1 -} +Object.defineProperty(exports, '__esModule', { value: true }); -function emit (event, code, signal) { - if (emitter.emitted[event]) { - return - } - emitter.emitted[event] = true - emitter.emit(event, code, signal) -} +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } -// { : , ... } -var sigListeners = {} -signals.forEach(function (sig) { - sigListeners[sig] = function listener () { - // If there are no other listeners, an exit is coming! - // Simplest way: remove us and then re-send the signal. - // We know that this will kill the process, so we can - // safely emit now. - var listeners = process.listeners(sig) - if (listeners.length === emitter.count) { - unload() - emit('exit', null, sig) - /* istanbul ignore next */ - emit('afterexit', null, sig) - /* istanbul ignore next */ - process.kill(process.pid, sig) - } - } -}) +var jsonwebtoken = _interopDefault(__webpack_require__(439)); -module.exports.signals = function () { - return signals +async function getToken({ + privateKey, + payload +}) { + return jsonwebtoken.sign(payload, privateKey, { + algorithm: "RS256" + }); } -module.exports.load = load - -var loaded = false - -function load () { - if (loaded) { - return - } - loaded = true - - // This is the number of onSignalExit's that are in play. - // It's important so that we can count the correct number of - // listeners on signals, and don't wait for the other one to - // handle it instead of us. - emitter.count += 1 - - signals = signals.filter(function (sig) { - try { - process.on(sig, sigListeners[sig]) - return true - } catch (er) { - return false - } - }) +async function githubAppJwt({ + id, + privateKey, + now = Math.floor(Date.now() / 1000) +}) { + // When creating a JSON Web Token, it sets the "issued at time" (iat) to 30s + // in the past as we have seen people running situations where the GitHub API + // claimed the iat would be in future. It turned out the clocks on the + // different machine were not in sync. + const nowWithSafetyMargin = now - 30; + const expiration = nowWithSafetyMargin + 60 * 10; // JWT expiration time (10 minute maximum) - process.emit = processEmit - process.reallyExit = processReallyExit + const payload = { + iat: nowWithSafetyMargin, + exp: expiration, + iss: id + }; + const token = await getToken({ + privateKey, + payload + }); + return { + appId: id, + expiration, + token + }; } -var originalProcessReallyExit = process.reallyExit -function processReallyExit (code) { - process.exitCode = code || 0 - emit('exit', process.exitCode, null) - /* istanbul ignore next */ - emit('afterexit', process.exitCode, null) - /* istanbul ignore next */ - originalProcessReallyExit.call(process, process.exitCode) -} +exports.githubAppJwt = githubAppJwt; +//# sourceMappingURL=index.js.map -var originalProcessEmit = process.emit -function processEmit (ev, arg) { - if (ev === 'exit') { - if (arg !== undefined) { - process.exitCode = arg - } - var ret = originalProcessEmit.apply(this, arguments) - emit('exit', process.exitCode, null) - /* istanbul ignore next */ - emit('afterexit', process.exitCode, null) - return ret - } else { - return originalProcessEmit.apply(this, arguments) - } -} +/***/ }), +/* 293 */ +/***/ (function(module) { + +module.exports = require("buffer"); /***/ }), -/* 261 */ +/* 294 */ /***/ (function(module, __unusedexports, __webpack_require__) { -var nativeCreate = __webpack_require__(878); +"use strict"; -/** Used to stand-in for `undefined` hash values. */ -var HASH_UNDEFINED = '__lodash_hash_undefined__'; +const fs = __webpack_require__(747); -/** - * Sets the hash `key` to `value`. - * - * @private - * @name set - * @memberOf Hash - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the hash instance. - */ -function hashSet(key, value) { - var data = this.__data__; - this.size += this.has(key) ? 0 : 1; - data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; - return this; -} +module.exports = fp => new Promise(resolve => { + fs.access(fp, err => { + resolve(!err); + }); +}); -module.exports = hashSet; +module.exports.sync = fp => { + try { + fs.accessSync(fp); + return true; + } catch (err) { + return false; + } +}; /***/ }), -/* 262 */ +/* 295 */, +/* 296 */, +/* 297 */, +/* 298 */ /***/ (function(module, __unusedexports, __webpack_require__) { -var JsonWebTokenError = __webpack_require__(257); - -var TokenExpiredError = function (message, expiredAt) { - JsonWebTokenError.call(this, message); - this.name = 'TokenExpiredError'; - this.expiredAt = expiredAt; -}; +"use strict"; +/*! + * destroy + * Copyright(c) 2014 Jonathan Ong + * MIT Licensed + */ -TokenExpiredError.prototype = Object.create(JsonWebTokenError.prototype); -TokenExpiredError.prototype.constructor = TokenExpiredError; -module.exports = TokenExpiredError; +/** + * Module dependencies. + * @private + */ -/***/ }), -/* 263 */, -/* 264 */, -/* 265 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +var ReadStream = __webpack_require__(747).ReadStream +var Stream = __webpack_require__(413) -module.exports = getPage +/** + * Module exports. + * @public + */ -const deprecate = __webpack_require__(370) -const getPageLinks = __webpack_require__(577) -const HttpError = __webpack_require__(297) +module.exports = destroy -function getPage (octokit, link, which, headers) { - deprecate(`octokit.get${which.charAt(0).toUpperCase() + which.slice(1)}Page() – You can use octokit.paginate or async iterators instead: https://github.com/octokit/rest.js#pagination.`) - const url = getPageLinks(link)[which] +/** + * Destroy a stream. + * + * @param {object} stream + * @public + */ - if (!url) { - const urlError = new HttpError(`No ${which} page found`, 404) - return Promise.reject(urlError) +function destroy(stream) { + if (stream instanceof ReadStream) { + return destroyReadStream(stream) } - const requestOptions = { - url, - headers: applyAcceptHeader(link, headers) + if (!(stream instanceof Stream)) { + return stream } - const promise = octokit.request(requestOptions) + if (typeof stream.destroy === 'function') { + stream.destroy() + } - return promise + return stream } -function applyAcceptHeader (res, headers) { - const previous = res.headers && res.headers['x-github-media-type'] +/** + * Destroy a ReadStream. + * + * @param {object} stream + * @private + */ + +function destroyReadStream(stream) { + stream.destroy() - if (!previous || (headers && headers.accept)) { - return headers + if (typeof stream.close === 'function') { + // node.js core bug work-around + stream.on('open', onOpenClose) } - headers = headers || {} - headers.accept = 'application/vnd.' + previous - .replace('; param=', '.') - .replace('; format=', '+') - return headers + return stream +} + +/** + * On open handler to close stream. + * @private + */ + +function onOpenClose() { + if (typeof this.fd === 'number') { + // actually close down the fd + this.close() + } } /***/ }), -/* 266 */ +/* 299 */, +/* 300 */, +/* 301 */ /***/ (function(module) { -module.exports = Yallist +module.exports = {"name":"probot","version":"10.7.0","description":"🤖 A framework for building GitHub Apps to automate and improve your workflow","repository":"https://github.com/probot/probot","main":"lib/index.js","types":"./lib/index.d.ts","bin":{"probot":"./bin/probot.js"},"scripts":{"build":"rimraf lib && tsc -p tsconfig.json","lint":"prettier --check 'src/**/*.ts' 'test/**/*.ts' 'docs/*.md' *.md package.json tsconfig.json","lint:fix":"prettier --write 'src/**/*.ts' 'test/**/*.ts' 'docs/*.md' *.md package.json tsconfig.json","pretest":"tsc --noEmit -p test","test":"jest","posttest":"npm run lint","doc":"typedoc --options .typedoc.json"},"files":["lib","bin","static","views"],"keywords":["probot","github-apps","github","automation","robots","workflow"],"bugs":"https://github.com/probot/probot/issues","homepage":"https://probot.github.io","author":"Brandon Keepers","license":"ISC","dependencies":{"@octokit/auth-app":"^2.4.14","@octokit/auth-unauthenticated":"^1.0.0","@octokit/core":"^3.1.0","@octokit/graphql":"^4.2.0","@octokit/plugin-enterprise-compatibility":"^1.2.1","@octokit/plugin-paginate-rest":"^2.2.3","@octokit/plugin-rest-endpoint-methods":"^3.17.0","@octokit/plugin-retry":"^3.0.1","@octokit/plugin-throttling":"^3.3.0","@octokit/request":"^5.1.0","@octokit/types":"^5.0.1","@octokit/webhooks":"^7.11.0","@probot/pino":"^1.1.2","@types/express":"^4.17.2","@types/ioredis":"^4.0.6","@types/pino":"^6.3.0","@types/pino-http":"^5.0.4","@types/supports-color":"^5.3.0","bottleneck":"^2.15.3","commander":"^5.0.0","deepmerge":"^4.1.0","deprecation":"^2.3.1","dotenv":"~8.2.0","eventsource":"^1.0.7","express":"^4.16.2","express-async-errors":"^3.0.0","hbs":"^4.1.1","ioredis":"^4.5.1","is-base64":"^1.1.0","js-yaml":"^3.13.1","jsonwebtoken":"^8.1.0","lru-cache":"^6.0.0","octokit-pagination-methods":"1.1.0","pino":"^6.5.0","pino-http":"^5.2.0","pino-pretty":"^4.1.0","pkg-conf":"^3.0.0","raven":"^2.4.2","resolve":"^1.4.0","semver":"^7.0.0","supports-color":"^7.0.0","update-dotenv":"^1.1.0","update-notifier":"^4.0.0","uuid":"^7.0.0"},"devDependencies":{"@sinonjs/fake-timers":"^6.0.1","@tsconfig/node10":"^1.0.3","@types/eventsource":"^1.1.0","@types/jest":"^25.1.3","@types/js-yaml":"^3.10.1","@types/jsonwebtoken":"^8.3.0","@types/node":"^14.0.6","@types/raven":"^2.1.5","@types/resolve":"^1.14.0","@types/semver":"^7.1.0","@types/supertest":"^2.0.4","@types/uuid":"^7.0.0","body-parser":"^1.19.0","connect-sse":"^1.2.0","execa":"^4.0.3","get-port":"^5.1.1","got":"^11.5.1","jest":"^26.1.0","json-server":"^0.16.1","nock":"^13.0.3","prettier":"^2.0.5","rimraf":"^3.0.2","semantic-release":"^17.0.0","semantic-release-plugin-update-version-in-files":"^1.1.0","smee-client":"^1.2.2","supertest":"^4.0.2","ts-jest":"^26.1.1","typedoc":"^0.17.0","typescript":"^3.9.3"},"engines":{"node":">=10.21"},"jest":{"testEnvironment":"node","setupFiles":["/test/setup.ts"],"coveragePathIgnorePatterns":["/lib/"],"moduleFileExtensions":["ts","js","json","node"],"preset":"ts-jest"},"release":{"plugins":["@semantic-release/commit-analyzer","@semantic-release/release-notes-generator","@semantic-release/github","@semantic-release/npm",["semantic-release-plugin-update-version-in-files",{"files":["lib/version.*"]}]]},"_resolved":"https://registry.npmjs.org/probot/-/probot-10.7.0.tgz","_integrity":"sha512-4Ats45Ua/TmoNfOJbvbd78M76fKiyD1QLdpoYdqXzSigItq3Qwrgzk/nbavnaNi4aa8WWMfLyQbctuXHN7+rGw==","_from":"probot@10.7.0"}; -Yallist.Node = Node -Yallist.create = Yallist +/***/ }), +/* 302 */, +/* 303 */ +/***/ (function(module) { -function Yallist (list) { - var self = this - if (!(self instanceof Yallist)) { - self = new Yallist() - } +"use strict"; - self.tail = null - self.head = null - self.length = 0 +module.exports = function (x) { + var lf = typeof x === 'string' ? '\n' : '\n'.charCodeAt(); + var cr = typeof x === 'string' ? '\r' : '\r'.charCodeAt(); - if (list && typeof list.forEach === 'function') { - list.forEach(function (item) { - self.push(item) - }) - } else if (arguments.length > 0) { - for (var i = 0, l = arguments.length; i < l; i++) { - self.push(arguments[i]) - } - } + if (x[x.length - 1] === lf) { + x = x.slice(0, x.length - 1); + } - return self -} + if (x[x.length - 1] === cr) { + x = x.slice(0, x.length - 1); + } -Yallist.prototype.removeNode = function (node) { - if (node.list !== this) { - throw new Error('removing node which does not belong to this list') - } + return x; +}; - var next = node.next - var prev = node.prev - if (next) { - next.prev = prev - } +/***/ }), +/* 304 */ +/***/ (function(module) { - if (prev) { - prev.next = next - } +module.exports = require("string_decoder"); - if (node === this.head) { - this.head = next - } - if (node === this.tail) { - this.tail = prev - } +/***/ }), +/* 305 */, +/* 306 */, +/* 307 */ +/***/ (function(module) { - node.list.length-- - node.next = null - node.prev = null - node.list = null -} +"use strict"; -Yallist.prototype.unshiftNode = function (node) { - if (node === this.head) { - return - } - if (node.list) { - node.list.removeNode(node) - } +module.exports = { + mapHttpRequest, + reqSerializer +} - var head = this.head - node.list = this - node.next = head - if (head) { - head.prev = node +var rawSymbol = Symbol('pino-raw-req-ref') +var pinoReqProto = Object.create({}, { + id: { + enumerable: true, + writable: true, + value: '' + }, + method: { + enumerable: true, + writable: true, + value: '' + }, + url: { + enumerable: true, + writable: true, + value: '' + }, + headers: { + enumerable: true, + writable: true, + value: {} + }, + remoteAddress: { + enumerable: true, + writable: true, + value: '' + }, + remotePort: { + enumerable: true, + writable: true, + value: '' + }, + raw: { + enumerable: false, + get: function () { + return this[rawSymbol] + }, + set: function (val) { + this[rawSymbol] = val + } } +}) +Object.defineProperty(pinoReqProto, rawSymbol, { + writable: true, + value: {} +}) - this.head = node - if (!this.tail) { - this.tail = node +function reqSerializer (req) { + // req.info is for hapi compat. + var connection = req.info || req.connection + const _req = Object.create(pinoReqProto) + _req.id = (typeof req.id === 'function' ? req.id() : (req.id || (req.info ? req.info.id : undefined))) + _req.method = req.method + // req.originalUrl is for expressjs compat. + if (req.originalUrl) { + _req.url = req.originalUrl + } else { + // req.url.path is for hapi compat. + _req.url = req.path || (req.url ? (req.url.path || req.url) : undefined) } - this.length++ + _req.headers = req.headers + _req.remoteAddress = connection && connection.remoteAddress + _req.remotePort = connection && connection.remotePort + // req.raw is for hapi compat/equivalence + _req.raw = req.raw || req + return _req } -Yallist.prototype.pushNode = function (node) { - if (node === this.tail) { - return +function mapHttpRequest (req) { + return { + req: reqSerializer(req) } +} - if (node.list) { - node.list.removeNode(node) - } - var tail = this.tail - node.list = this - node.prev = tail - if (tail) { - tail.next = node - } +/***/ }), +/* 308 */, +/* 309 */ +/***/ (function(module, exports, __webpack_require__) { - this.tail = node - if (!this.head) { - this.head = node - } - this.length++ -} +/* eslint-disable node/no-deprecated-api */ +var buffer = __webpack_require__(293) +var Buffer = buffer.Buffer -Yallist.prototype.push = function () { - for (var i = 0, l = arguments.length; i < l; i++) { - push(this, arguments[i]) +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] } - return this.length +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer } -Yallist.prototype.unshift = function () { - for (var i = 0, l = arguments.length; i < l; i++) { - unshift(this, arguments[i]) - } - return this.length +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) } -Yallist.prototype.pop = function () { - if (!this.tail) { - return undefined - } +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) - var res = this.tail.value - this.tail = this.tail.prev - if (this.tail) { - this.tail.next = null - } else { - this.head = null +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') } - this.length-- - return res + return Buffer(arg, encodingOrOffset, length) } -Yallist.prototype.shift = function () { - if (!this.head) { - return undefined +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') } - - var res = this.head.value - this.head = this.head.next - if (this.head) { - this.head.prev = null + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } } else { - this.tail = null + buf.fill(0) } - this.length-- - return res + return buf } -Yallist.prototype.forEach = function (fn, thisp) { - thisp = thisp || this - for (var walker = this.head, i = 0; walker !== null; i++) { - fn.call(thisp, walker.value, i, this) - walker = walker.next +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') } + return Buffer(size) } -Yallist.prototype.forEachReverse = function (fn, thisp) { - thisp = thisp || this - for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { - fn.call(thisp, walker.value, i, this) - walker = walker.prev +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') } + return buffer.SlowBuffer(size) } -Yallist.prototype.get = function (n) { - for (var i = 0, walker = this.head; walker !== null && i < n; i++) { - // abort out of the list early if we hit a cycle - walker = walker.next - } - if (i === n && walker !== null) { - return walker.value - } -} -Yallist.prototype.getReverse = function (n) { - for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { - // abort out of the list early if we hit a cycle - walker = walker.prev - } - if (i === n && walker !== null) { - return walker.value - } -} +/***/ }), +/* 310 */, +/* 311 */, +/* 312 */ +/***/ (function(module, __unusedexports, __webpack_require__) { -Yallist.prototype.map = function (fn, thisp) { - thisp = thisp || this - var res = new Yallist() - for (var walker = this.head; walker !== null;) { - res.push(fn.call(thisp, walker.value, this)) - walker = walker.next - } - return res -} +"use strict"; -Yallist.prototype.mapReverse = function (fn, thisp) { - thisp = thisp || this - var res = new Yallist() - for (var walker = this.tail; walker !== null;) { - res.push(fn.call(thisp, walker.value, this)) - walker = walker.prev - } - return res -} -Yallist.prototype.reduce = function (fn, initial) { - var acc - var walker = this.head - if (arguments.length > 1) { - acc = initial - } else if (this.head) { - walker = this.head.next - acc = this.head.value - } else { - throw new TypeError('Reduce of empty list with no initial value') - } +var common = __webpack_require__(740); +var Type = __webpack_require__(945); - for (var i = 0; walker !== null; i++) { - acc = fn(acc, walker.value, i) - walker = walker.next +var YAML_FLOAT_PATTERN = new RegExp( + // 2.5e4, 2.5 and integers + '^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' + + // .2e4, .2 + // special case, seems not from spec + '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' + + // 20:59 + '|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*' + + // .inf + '|[-+]?\\.(?:inf|Inf|INF)' + + // .nan + '|\\.(?:nan|NaN|NAN))$'); + +function resolveYamlFloat(data) { + if (data === null) return false; + + if (!YAML_FLOAT_PATTERN.test(data) || + // Quick hack to not allow integers end with `_` + // Probably should update regexp & check speed + data[data.length - 1] === '_') { + return false; } - return acc + return true; } -Yallist.prototype.reduceReverse = function (fn, initial) { - var acc - var walker = this.tail - if (arguments.length > 1) { - acc = initial - } else if (this.tail) { - walker = this.tail.prev - acc = this.tail.value - } else { - throw new TypeError('Reduce of empty list with no initial value') - } +function constructYamlFloat(data) { + var value, sign, base, digits; - for (var i = this.length - 1; walker !== null; i--) { - acc = fn(acc, walker.value, i) - walker = walker.prev + value = data.replace(/_/g, '').toLowerCase(); + sign = value[0] === '-' ? -1 : 1; + digits = []; + + if ('+-'.indexOf(value[0]) >= 0) { + value = value.slice(1); } - return acc -} + if (value === '.inf') { + return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; -Yallist.prototype.toArray = function () { - var arr = new Array(this.length) - for (var i = 0, walker = this.head; walker !== null; i++) { - arr[i] = walker.value - walker = walker.next - } - return arr -} + } else if (value === '.nan') { + return NaN; -Yallist.prototype.toArrayReverse = function () { - var arr = new Array(this.length) - for (var i = 0, walker = this.tail; walker !== null; i++) { - arr[i] = walker.value - walker = walker.prev - } - return arr -} + } else if (value.indexOf(':') >= 0) { + value.split(':').forEach(function (v) { + digits.unshift(parseFloat(v, 10)); + }); -Yallist.prototype.slice = function (from, to) { - to = to || this.length - if (to < 0) { - to += this.length - } - from = from || 0 - if (from < 0) { - from += this.length - } - var ret = new Yallist() - if (to < from || to < 0) { - return ret - } - if (from < 0) { - from = 0 - } - if (to > this.length) { - to = this.length - } - for (var i = 0, walker = this.head; walker !== null && i < from; i++) { - walker = walker.next - } - for (; walker !== null && i < to; i++, walker = walker.next) { - ret.push(walker.value) - } - return ret -} + value = 0.0; + base = 1; -Yallist.prototype.sliceReverse = function (from, to) { - to = to || this.length - if (to < 0) { - to += this.length - } - from = from || 0 - if (from < 0) { - from += this.length - } - var ret = new Yallist() - if (to < from || to < 0) { - return ret - } - if (from < 0) { - from = 0 - } - if (to > this.length) { - to = this.length - } - for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { - walker = walker.prev - } - for (; walker !== null && i > from; i--, walker = walker.prev) { - ret.push(walker.value) - } - return ret -} + digits.forEach(function (d) { + value += d * base; + base *= 60; + }); -Yallist.prototype.reverse = function () { - var head = this.head - var tail = this.tail - for (var walker = head; walker !== null; walker = walker.prev) { - var p = walker.prev - walker.prev = walker.next - walker.next = p - } - this.head = tail - this.tail = head - return this -} + return sign * value; -function push (self, item) { - self.tail = new Node(item, self.tail, null, self) - if (!self.head) { - self.head = self.tail } - self.length++ + return sign * parseFloat(value, 10); } -function unshift (self, item) { - self.head = new Node(item, null, self.head, self) - if (!self.tail) { - self.tail = self.head - } - self.length++ -} -function Node (value, prev, next, list) { - if (!(this instanceof Node)) { - return new Node(value, prev, next, list) - } +var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; - this.list = list - this.value = value +function representYamlFloat(object, style) { + var res; - if (prev) { - prev.next = this - this.prev = prev - } else { - this.prev = null + if (isNaN(object)) { + switch (style) { + case 'lowercase': return '.nan'; + case 'uppercase': return '.NAN'; + case 'camelcase': return '.NaN'; + } + } else if (Number.POSITIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '.inf'; + case 'uppercase': return '.INF'; + case 'camelcase': return '.Inf'; + } + } else if (Number.NEGATIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '-.inf'; + case 'uppercase': return '-.INF'; + case 'camelcase': return '-.Inf'; + } + } else if (common.isNegativeZero(object)) { + return '-0.0'; } - if (next) { - next.prev = this - this.next = next - } else { - this.next = null - } + res = object.toString(10); + + // JS stringifier can build scientific format without dots: 5e-100, + // while YAML requres dot: 5.e-100. Fix it with simple hack + + return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res; } +function isFloat(object) { + return (Object.prototype.toString.call(object) === '[object Number]') && + (object % 1 !== 0 || common.isNegativeZero(object)); +} -/***/ }), -/* 267 */, -/* 268 */ -/***/ (function(module) { +module.exports = new Type('tag:yaml.org,2002:float', { + kind: 'scalar', + resolve: resolveYamlFloat, + construct: constructYamlFloat, + predicate: isFloat, + represent: representYamlFloat, + defaultStyle: 'lowercase' +}); -module.exports = {"100":"Continue","101":"Switching Protocols","102":"Processing","103":"Early Hints","200":"OK","201":"Created","202":"Accepted","203":"Non-Authoritative Information","204":"No Content","205":"Reset Content","206":"Partial Content","207":"Multi-Status","208":"Already Reported","226":"IM Used","300":"Multiple Choices","301":"Moved Permanently","302":"Found","303":"See Other","304":"Not Modified","305":"Use Proxy","306":"(Unused)","307":"Temporary Redirect","308":"Permanent Redirect","400":"Bad Request","401":"Unauthorized","402":"Payment Required","403":"Forbidden","404":"Not Found","405":"Method Not Allowed","406":"Not Acceptable","407":"Proxy Authentication Required","408":"Request Timeout","409":"Conflict","410":"Gone","411":"Length Required","412":"Precondition Failed","413":"Payload Too Large","414":"URI Too Long","415":"Unsupported Media Type","416":"Range Not Satisfiable","417":"Expectation Failed","418":"I'm a teapot","421":"Misdirected Request","422":"Unprocessable Entity","423":"Locked","424":"Failed Dependency","425":"Unordered Collection","426":"Upgrade Required","428":"Precondition Required","429":"Too Many Requests","431":"Request Header Fields Too Large","451":"Unavailable For Legal Reasons","500":"Internal Server Error","501":"Not Implemented","502":"Bad Gateway","503":"Service Unavailable","504":"Gateway Timeout","505":"HTTP Version Not Supported","506":"Variant Also Negotiates","507":"Insufficient Storage","508":"Loop Detected","509":"Bandwidth Limit Exceeded","510":"Not Extended","511":"Network Authentication Required"}; /***/ }), -/* 269 */ -/***/ (function(module) { +/* 313 */ +/***/ (function(module, __unusedexports, __webpack_require__) { -/** Used to match `RegExp` flags from their coerced string values. */ -var reFlags = /\w*$/; +"use strict"; -/** - * Creates a clone of `regexp`. - * - * @private - * @param {Object} regexp The regexp to clone. - * @returns {Object} Returns the cloned regexp. - */ -function cloneRegExp(regexp) { - var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); - result.lastIndex = regexp.lastIndex; - return result; -} -module.exports = cloneRegExp; +var Buffer = __webpack_require__(293).Buffer, + Transform = __webpack_require__(413).Transform; -/***/ }), -/* 270 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +// == Exports ================================================================== +module.exports = function(iconv) { + + // Additional Public API. + iconv.encodeStream = function encodeStream(encoding, options) { + return new IconvLiteEncoderStream(iconv.getEncoder(encoding, options), options); + } -var copyObject = __webpack_require__(765), - getSymbolsIn = __webpack_require__(778); + iconv.decodeStream = function decodeStream(encoding, options) { + return new IconvLiteDecoderStream(iconv.getDecoder(encoding, options), options); + } -/** - * Copies own and inherited symbols of `source` to `object`. - * - * @private - * @param {Object} source The object to copy symbols from. - * @param {Object} [object={}] The object to copy symbols to. - * @returns {Object} Returns `object`. - */ -function copySymbolsIn(source, object) { - return copyObject(source, getSymbolsIn(source), object); -} + iconv.supportsStreams = true; -module.exports = copySymbolsIn; + // Not published yet. + iconv.IconvLiteEncoderStream = IconvLiteEncoderStream; + iconv.IconvLiteDecoderStream = IconvLiteDecoderStream; + iconv._collect = IconvLiteDecoderStream.prototype.collect; +}; -/***/ }), -/* 271 */, -/* 272 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { -"use strict"; +// == Encoder stream ======================================================= +function IconvLiteEncoderStream(conv, options) { + this.conv = conv; + options = options || {}; + options.decodeStrings = false; // We accept only strings, so we don't need to decode them. + Transform.call(this, options); +} -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; +IconvLiteEncoderStream.prototype = Object.create(Transform.prototype, { + constructor: { value: IconvLiteEncoderStream } +}); + +IconvLiteEncoderStream.prototype._transform = function(chunk, encoding, done) { + if (typeof chunk != 'string') + return done(new Error("Iconv encoding stream needs strings as its input.")); + try { + var res = this.conv.write(chunk); + if (res && res.length) this.push(res); + done(); + } + catch (e) { + done(e); } -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -var node_fetch_1 = __importDefault(__webpack_require__(454)); -var escape_1 = __importDefault(__webpack_require__(885)); -function convertProject(raw) { - return { - id: raw.id, - slug: raw.slug, - language: raw.language.code - }; } -var RTD = /** @class */ (function () { - function RTD(token) { - this.token = token; + +IconvLiteEncoderStream.prototype._flush = function(done) { + try { + var res = this.conv.end(); + if (res && res.length) this.push(res); + done(); } - RTD.prototype.getProject = function (slug) { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - return [2 /*return*/, node_fetch_1.default("https://readthedocs.org/api/v3/projects/" + escape_1.default(slug) + "/", { - method: 'get', - headers: { - 'Content-Type': 'application/json', - 'Authorization': "Token " + this.token - } - }) - .then(function (res) { return Promise.all([res.status, res.json()]); }) - .then(function (_a) { - var status = _a[0], json = _a[1]; - if (status != 200) { - throw new Error("Unexpected status code " + status + " with body: " + JSON.stringify(json)); - } - return convertProject(json); - })]; - }); - }); - }; - RTD.prototype.getTranslates = function (project) { - return __awaiter(this, void 0, void 0, function () { - var projectInfo, _a; - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - if (!(typeof project === "string")) return [3 /*break*/, 2]; - return [4 /*yield*/, this.getProject(project)]; - case 1: - _a = _b.sent(); - return [3 /*break*/, 3]; - case 2: - _a = project; - _b.label = 3; - case 3: - projectInfo = _a; - return [2 /*return*/, node_fetch_1.default("https://readthedocs.org/api/v3/projects/" + escape_1.default(projectInfo.slug) + "/translations/", { - method: 'get', - headers: { - 'Content-Type': 'application/json', - 'Authorization': "Token " + this.token - } - }) - .then(function (res) { - return Promise.all([res.status, res.json()]); - }) - .then(function (_a) { - var status = _a[0], json = _a[1]; - if (status !== 200) { - throw new Error("Unexpected status code " + status + " with body: " + JSON.stringify(json)); - } - return json['results']; - }) - .then(function (translations) { - return translations.reduce(function (accumulator, currentValue) { - accumulator.push(convertProject(currentValue)); - return accumulator; - }, [projectInfo]); - })]; - } - }); - }); - }; - /** - * @see https://docs.readthedocs.io/en/stable/api/v3.html#version-detail - */ - RTD.prototype.getBuildActiveness = function (project, branch) { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - return [2 /*return*/, node_fetch_1.default("https://readthedocs.org/api/v3/projects/" + project + "/versions/" + escape_1.default(branch) + "/", { - method: 'get', - headers: { - 'Content-Type': 'application/json', - 'Authorization': "Token " + this.token - } - }) - .then(function (res) { - return Promise.all([res.status, res.json()]); - }) - .then(function (_a) { - var status = _a[0], json = _a[1]; - if (status != 200) { - throw new Error("Unexpected status code " + status + " with body: " + JSON.stringify(json)); - } - return json; - }) - .then(function (ver) { return ver.active; })]; - }); - }); - }; - /** - * @see https://docs.readthedocs.io/en/stable/api/v3.html#version-update - */ - RTD.prototype.configureBuild = function (project, branch, flag) { - return __awaiter(this, void 0, void 0, function () { - var currentFlag; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.getBuildActiveness(project, branch)]; - case 1: - currentFlag = _a.sent(); - if (currentFlag === flag) { - // no need to ask for update - return [2 /*return*/, false]; - } - // this implementation doesn't care the transaction, so - // the returned value could be different with expected one - // if we run two procedures at the same time - return [2 /*return*/, node_fetch_1.default("https://readthedocs.org/api/v3/projects/" + project + "/versions/" + escape_1.default(branch) + "/", { - method: 'patch', - headers: { - 'Content-Type': 'application/json', - 'Authorization': "Token " + this.token - }, - body: "{\"active\": " + flag + "}" - }) - .then(function (res) { - if (res.status != 204) { - return Promise.all([res.status, res.json()]); - } - else { - // 204 responses empty text, so json() doesn't work - return Promise.all([res.status, res.text()]); - } - }) - .then(function (_a) { - var status = _a[0], json = _a[1]; - if (status != 204) { - throw new Error("Unexpected status code " + status + " with body: " + JSON.stringify(json)); - } - return true; - })]; - } - }); - }); - }; - RTD.prototype.enableBuild = function (project, branch) { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - return [2 /*return*/, this.configureBuild(project, branch, true)]; - }); - }); - }; - RTD.prototype.disableBuild = function (project, branch) { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - return [2 /*return*/, this.configureBuild(project, branch, false)]; - }); - }); - }; - return RTD; -}()); -exports.default = RTD; + catch (e) { + done(e); + } +} +IconvLiteEncoderStream.prototype.collect = function(cb) { + var chunks = []; + this.on('error', cb); + this.on('data', function(chunk) { chunks.push(chunk); }); + this.on('end', function() { + cb(null, Buffer.concat(chunks)); + }); + return this; +} -/***/ }), -/* 273 */, -/* 274 */ -/***/ (function(__unusedmodule, exports) { -"use strict"; +// == Decoder stream ======================================================= +function IconvLiteDecoderStream(conv, options) { + this.conv = conv; + options = options || {}; + options.encoding = this.encoding = 'utf8'; // We output strings. + Transform.call(this, options); +} -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * Tiny class to simplify dealing with subscription set - * - * @export - * @class SubscriptionSet - */ -class SubscriptionSet { - constructor() { - this.set = { - subscribe: {}, - psubscribe: {}, - }; - } - add(set, channel) { - this.set[mapSet(set)][channel] = true; - } - del(set, channel) { - delete this.set[mapSet(set)][channel]; - } - channels(set) { - return Object.keys(this.set[mapSet(set)]); +IconvLiteDecoderStream.prototype = Object.create(Transform.prototype, { + constructor: { value: IconvLiteDecoderStream } +}); + +IconvLiteDecoderStream.prototype._transform = function(chunk, encoding, done) { + if (!Buffer.isBuffer(chunk)) + return done(new Error("Iconv decoding stream needs buffers as its input.")); + try { + var res = this.conv.write(chunk); + if (res && res.length) this.push(res, this.encoding); + done(); } - isEmpty() { - return (this.channels("subscribe").length === 0 && - this.channels("psubscribe").length === 0); + catch (e) { + done(e); } } -exports.default = SubscriptionSet; -function mapSet(set) { - if (set === "unsubscribe") { - return "subscribe"; + +IconvLiteDecoderStream.prototype._flush = function(done) { + try { + var res = this.conv.end(); + if (res && res.length) this.push(res, this.encoding); + done(); } - if (set === "punsubscribe") { - return "psubscribe"; + catch (e) { + done(e); } - return set; } +IconvLiteDecoderStream.prototype.collect = function(cb) { + var res = ''; + this.on('error', cb); + this.on('data', function(chunk) { res += chunk; }); + this.on('end', function() { + cb(null, res); + }); + return this; +} -/***/ }), -/* 275 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -module.exports = receiverOn - -const webhookNames = __webpack_require__(782) -function receiverOn (state, webhookNameOrNames, handler) { - if (Array.isArray(webhookNameOrNames)) { - webhookNameOrNames.forEach(webhookName => receiverOn(state, webhookName, handler)) - return - } - if (webhookNames.indexOf(webhookNameOrNames) === -1) { - console.warn(`"${webhookNameOrNames}" is not a known webhook name (https://developer.github.com/v3/activity/events/types/)`) - } +/***/ }), +/* 314 */, +/* 315 */ +/***/ (function(module) { - if (!state.hooks[webhookNameOrNames]) { - state.hooks[webhookNameOrNames] = [] +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }) + } + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } } - - state.hooks[webhookNameOrNames].push(handler) } /***/ }), -/* 276 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -var util = __webpack_require__(338); -var binarySearch = __webpack_require__(972); -var ArraySet = __webpack_require__(66).ArraySet; -var base64VLQ = __webpack_require__(226); -var quickSort = __webpack_require__(930).quickSort; +/* 316 */ +/***/ (function(module, __unusedexports, __webpack_require__) { -function SourceMapConsumer(aSourceMap, aSourceMapURL) { - var sourceMap = aSourceMap; - if (typeof aSourceMap === 'string') { - sourceMap = util.parseSourceMapInput(aSourceMap); - } +var path = __webpack_require__(622); +var fs = __webpack_require__(747); - return sourceMap.sections != null - ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) - : new BasicSourceMapConsumer(sourceMap, aSourceMapURL); -} +function Mime() { + // Map of extension -> mime type + this.types = Object.create(null); -SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) { - return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL); + // Map of mime type -> extension + this.extensions = Object.create(null); } /** - * The version of the source mapping spec that we are consuming. + * Define mimetype -> extension mappings. Each key is a mime-type that maps + * to an array of extensions associated with the type. The first extension is + * used as the default extension for the type. + * + * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']}); + * + * @param map (Object) type definitions */ -SourceMapConsumer.prototype._version = 3; - -// `__generatedMappings` and `__originalMappings` are arrays that hold the -// parsed mapping coordinates from the source map's "mappings" attribute. They -// are lazily instantiated, accessed via the `_generatedMappings` and -// `_originalMappings` getters respectively, and we only parse the mappings -// and create these arrays once queried for a source location. We jump through -// these hoops because there can be many thousands of mappings, and parsing -// them is expensive, so we only want to do it if we must. -// -// Each object in the arrays is of the form: -// -// { -// generatedLine: The line number in the generated code, -// generatedColumn: The column number in the generated code, -// source: The path to the original source file that generated this -// chunk of code, -// originalLine: The line number in the original source that -// corresponds to this chunk of generated code, -// originalColumn: The column number in the original source that -// corresponds to this chunk of generated code, -// name: The name of the original symbol which generated this chunk of -// code. -// } -// -// All properties except for `generatedLine` and `generatedColumn` can be -// `null`. -// -// `_generatedMappings` is ordered by the generated positions. -// -// `_originalMappings` is ordered by the original positions. +Mime.prototype.define = function (map) { + for (var type in map) { + var exts = map[type]; + for (var i = 0; i < exts.length; i++) { + if (process.env.DEBUG_MIME && this.types[exts[i]]) { + console.warn((this._loading || "define()").replace(/.*\//, ''), 'changes "' + exts[i] + '" extension type from ' + + this.types[exts[i]] + ' to ' + type); + } -SourceMapConsumer.prototype.__generatedMappings = null; -Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { - configurable: true, - enumerable: true, - get: function () { - if (!this.__generatedMappings) { - this._parseMappings(this._mappings, this.sourceRoot); + this.types[exts[i]] = type; } - return this.__generatedMappings; - } -}); - -SourceMapConsumer.prototype.__originalMappings = null; -Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { - configurable: true, - enumerable: true, - get: function () { - if (!this.__originalMappings) { - this._parseMappings(this._mappings, this.sourceRoot); + // Default extension is the first one we encounter + if (!this.extensions[type]) { + this.extensions[type] = exts[0]; } - - return this.__originalMappings; } -}); - -SourceMapConsumer.prototype._charIsMappingSeparator = - function SourceMapConsumer_charIsMappingSeparator(aStr, index) { - var c = aStr.charAt(index); - return c === ";" || c === ","; - }; - -/** - * Parse the mappings in a string in to a data structure which we can easily - * query (the ordered arrays in the `this.__generatedMappings` and - * `this.__originalMappings` properties). - */ -SourceMapConsumer.prototype._parseMappings = - function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { - throw new Error("Subclasses must implement _parseMappings"); - }; - -SourceMapConsumer.GENERATED_ORDER = 1; -SourceMapConsumer.ORIGINAL_ORDER = 2; - -SourceMapConsumer.GREATEST_LOWER_BOUND = 1; -SourceMapConsumer.LEAST_UPPER_BOUND = 2; - -/** - * Iterate over each mapping between an original source/line/column and a - * generated line/column in this source map. - * - * @param Function aCallback - * The function that is called with each mapping. - * @param Object aContext - * Optional. If specified, this object will be the value of `this` every - * time that `aCallback` is called. - * @param aOrder - * Either `SourceMapConsumer.GENERATED_ORDER` or - * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to - * iterate over the mappings sorted by the generated file's line/column - * order or the original's source/line/column order, respectively. Defaults to - * `SourceMapConsumer.GENERATED_ORDER`. - */ -SourceMapConsumer.prototype.eachMapping = - function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { - var context = aContext || null; - var order = aOrder || SourceMapConsumer.GENERATED_ORDER; - - var mappings; - switch (order) { - case SourceMapConsumer.GENERATED_ORDER: - mappings = this._generatedMappings; - break; - case SourceMapConsumer.ORIGINAL_ORDER: - mappings = this._originalMappings; - break; - default: - throw new Error("Unknown order of iteration."); - } - - var sourceRoot = this.sourceRoot; - mappings.map(function (mapping) { - var source = mapping.source === null ? null : this._sources.at(mapping.source); - source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL); - return { - source: source, - generatedLine: mapping.generatedLine, - generatedColumn: mapping.generatedColumn, - originalLine: mapping.originalLine, - originalColumn: mapping.originalColumn, - name: mapping.name === null ? null : this._names.at(mapping.name) - }; - }, this).forEach(aCallback, context); - }; +}; /** - * Returns all generated line and column information for the original source, - * line, and column provided. If no column is provided, returns all mappings - * corresponding to a either the line we are searching for or the next - * closest line that has any mappings. Otherwise, returns all mappings - * corresponding to the given line and either the column we are searching for - * or the next closest column that has any offsets. - * - * The only argument is an object with the following properties: - * - * - source: The filename of the original source. - * - line: The line number in the original source. The line number is 1-based. - * - column: Optional. the column number in the original source. - * The column number is 0-based. + * Load an Apache2-style ".types" file * - * and an array of objects is returned, each with the following properties: + * This may be called multiple times (it's expected). Where files declare + * overlapping types/extensions, the last file wins. * - * - line: The line number in the generated source, or null. The - * line number is 1-based. - * - column: The column number in the generated source, or null. - * The column number is 0-based. + * @param file (String) path of file to load. */ -SourceMapConsumer.prototype.allGeneratedPositionsFor = - function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { - var line = util.getArg(aArgs, 'line'); - - // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping - // returns the index of the closest mapping less than the needle. By - // setting needle.originalColumn to 0, we thus find the last mapping for - // the given line, provided such a mapping exists. - var needle = { - source: util.getArg(aArgs, 'source'), - originalLine: line, - originalColumn: util.getArg(aArgs, 'column', 0) - }; - - needle.source = this._findSourceIndex(needle.source); - if (needle.source < 0) { - return []; - } - - var mappings = []; - - var index = this._findMapping(needle, - this._originalMappings, - "originalLine", - "originalColumn", - util.compareByOriginalPositions, - binarySearch.LEAST_UPPER_BOUND); - if (index >= 0) { - var mapping = this._originalMappings[index]; - - if (aArgs.column === undefined) { - var originalLine = mapping.originalLine; - - // Iterate until either we run out of mappings, or we run into - // a mapping for a different line than the one we found. Since - // mappings are sorted, this is guaranteed to find all mappings for - // the line we found. - while (mapping && mapping.originalLine === originalLine) { - mappings.push({ - line: util.getArg(mapping, 'generatedLine', null), - column: util.getArg(mapping, 'generatedColumn', null), - lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) - }); - - mapping = this._originalMappings[++index]; - } - } else { - var originalColumn = mapping.originalColumn; - - // Iterate until either we run out of mappings, or we run into - // a mapping for a different line than the one we were searching for. - // Since mappings are sorted, this is guaranteed to find all mappings for - // the line we are searching for. - while (mapping && - mapping.originalLine === line && - mapping.originalColumn == originalColumn) { - mappings.push({ - line: util.getArg(mapping, 'generatedLine', null), - column: util.getArg(mapping, 'generatedColumn', null), - lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) - }); - - mapping = this._originalMappings[++index]; - } - } - } - - return mappings; - }; - -exports.SourceMapConsumer = SourceMapConsumer; - -/** - * A BasicSourceMapConsumer instance represents a parsed source map which we can - * query for information about the original file positions by giving it a file - * position in the generated source. - * - * The first parameter is the raw source map (either as a JSON string, or - * already parsed to an object). According to the spec, source maps have the - * following attributes: - * - * - version: Which version of the source map spec this map is following. - * - sources: An array of URLs to the original source files. - * - names: An array of identifiers which can be referrenced by individual mappings. - * - sourceRoot: Optional. The URL root from which all sources are relative. - * - sourcesContent: Optional. An array of contents of the original source files. - * - mappings: A string of base64 VLQs which contain the actual mappings. - * - file: Optional. The generated file this source map is associated with. - * - * Here is an example source map, taken from the source map spec[0]: - * - * { - * version : 3, - * file: "out.js", - * sourceRoot : "", - * sources: ["foo.js", "bar.js"], - * names: ["src", "maps", "are", "fun"], - * mappings: "AA,AB;;ABCDE;" - * } - * - * The second parameter, if given, is a string whose value is the URL - * at which the source map was found. This URL is used to compute the - * sources array. - * - * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# - */ -function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) { - var sourceMap = aSourceMap; - if (typeof aSourceMap === 'string') { - sourceMap = util.parseSourceMapInput(aSourceMap); - } - - var version = util.getArg(sourceMap, 'version'); - var sources = util.getArg(sourceMap, 'sources'); - // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which - // requires the array) to play nice here. - var names = util.getArg(sourceMap, 'names', []); - var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); - var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); - var mappings = util.getArg(sourceMap, 'mappings'); - var file = util.getArg(sourceMap, 'file', null); - - // Once again, Sass deviates from the spec and supplies the version as a - // string rather than a number, so we use loose equality checking here. - if (version != this._version) { - throw new Error('Unsupported version: ' + version); - } - - if (sourceRoot) { - sourceRoot = util.normalize(sourceRoot); - } - - sources = sources - .map(String) - // Some source maps produce relative source paths like "./foo.js" instead of - // "foo.js". Normalize these first so that future comparisons will succeed. - // See bugzil.la/1090768. - .map(util.normalize) - // Always ensure that absolute sources are internally stored relative to - // the source root, if the source root is absolute. Not doing this would - // be particularly problematic when the source root is a prefix of the - // source (valid, but why??). See github issue #199 and bugzil.la/1188982. - .map(function (source) { - return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) - ? util.relative(sourceRoot, source) - : source; - }); - - // Pass `true` below to allow duplicate names and sources. While source maps - // are intended to be compressed and deduplicated, the TypeScript compiler - // sometimes generates source maps with duplicates in them. See Github issue - // #72 and bugzil.la/889492. - this._names = ArraySet.fromArray(names.map(String), true); - this._sources = ArraySet.fromArray(sources, true); +Mime.prototype.load = function(file) { + this._loading = file; + // Read file and split into lines + var map = {}, + content = fs.readFileSync(file, 'ascii'), + lines = content.split(/[\r\n]+/); - this._absoluteSources = this._sources.toArray().map(function (s) { - return util.computeSourceURL(sourceRoot, s, aSourceMapURL); + lines.forEach(function(line) { + // Clean up whitespace/comments, and split into fields + var fields = line.replace(/\s*#.*|^\s*|\s*$/g, '').split(/\s+/); + map[fields.shift()] = fields; }); - this.sourceRoot = sourceRoot; - this.sourcesContent = sourcesContent; - this._mappings = mappings; - this._sourceMapURL = aSourceMapURL; - this.file = file; -} + this.define(map); -BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); -BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; + this._loading = null; +}; /** - * Utility function to find the index of a source. Returns -1 if not - * found. + * Lookup a mime type based on extension */ -BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) { - var relativeSource = aSource; - if (this.sourceRoot != null) { - relativeSource = util.relative(this.sourceRoot, relativeSource); - } - - if (this._sources.has(relativeSource)) { - return this._sources.indexOf(relativeSource); - } - - // Maybe aSource is an absolute URL as returned by |sources|. In - // this case we can't simply undo the transform. - var i; - for (i = 0; i < this._absoluteSources.length; ++i) { - if (this._absoluteSources[i] == aSource) { - return i; - } - } +Mime.prototype.lookup = function(path, fallback) { + var ext = path.replace(/^.*[\.\/\\]/, '').toLowerCase(); - return -1; + return this.types[ext] || fallback || this.default_type; }; /** - * Create a BasicSourceMapConsumer from a SourceMapGenerator. - * - * @param SourceMapGenerator aSourceMap - * The source map that will be consumed. - * @param String aSourceMapURL - * The URL at which the source map can be found (optional) - * @returns BasicSourceMapConsumer + * Return file extension associated with a mime type */ -BasicSourceMapConsumer.fromSourceMap = - function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) { - var smc = Object.create(BasicSourceMapConsumer.prototype); - - var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); - var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); - smc.sourceRoot = aSourceMap._sourceRoot; - smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), - smc.sourceRoot); - smc.file = aSourceMap._file; - smc._sourceMapURL = aSourceMapURL; - smc._absoluteSources = smc._sources.toArray().map(function (s) { - return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL); - }); +Mime.prototype.extension = function(mimeType) { + var type = mimeType.match(/^\s*([^;\s]*)(?:;|\s|$)/)[1].toLowerCase(); + return this.extensions[type]; +}; - // Because we are modifying the entries (by converting string sources and - // names to indices into the sources and names ArraySets), we have to make - // a copy of the entry or else bad things happen. Shared mutable state - // strikes again! See github issue #191. +// Default instance +var mime = new Mime(); - var generatedMappings = aSourceMap._mappings.toArray().slice(); - var destGeneratedMappings = smc.__generatedMappings = []; - var destOriginalMappings = smc.__originalMappings = []; +// Define built-in types +mime.define(__webpack_require__(122)); - for (var i = 0, length = generatedMappings.length; i < length; i++) { - var srcMapping = generatedMappings[i]; - var destMapping = new Mapping; - destMapping.generatedLine = srcMapping.generatedLine; - destMapping.generatedColumn = srcMapping.generatedColumn; +// Default type +mime.default_type = mime.lookup('bin'); - if (srcMapping.source) { - destMapping.source = sources.indexOf(srcMapping.source); - destMapping.originalLine = srcMapping.originalLine; - destMapping.originalColumn = srcMapping.originalColumn; +// +// Additional API specific to the default instance +// - if (srcMapping.name) { - destMapping.name = names.indexOf(srcMapping.name); - } +mime.Mime = Mime; - destOriginalMappings.push(destMapping); - } +/** + * Lookup a charset based on mime type. + */ +mime.charsets = { + lookup: function(mimeType, fallback) { + // Assume text types are utf8 + return (/^text\/|^application\/(javascript|json)/).test(mimeType) ? 'UTF-8' : fallback; + } +}; - destGeneratedMappings.push(destMapping); - } +module.exports = mime; - quickSort(smc.__originalMappings, util.compareByOriginalPositions); - return smc; - }; +/***/ }), +/* 317 */ +/***/ (function(module) { /** - * The version of the source mapping spec that we are consuming. + * Helpers. */ -BasicSourceMapConsumer.prototype._version = 3; + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var w = d * 7; +var y = d * 365.25; /** - * The list of original sources. + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public */ -Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { - get: function () { - return this._absoluteSources.slice(); + +module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); } -}); + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; /** - * Provide the JIT with a nice shape / hidden class. - */ -function Mapping() { - this.generatedLine = 0; - this.generatedColumn = 0; - this.source = null; - this.originalLine = null; - this.originalColumn = null; - this.name = null; -} - -/** - * Parse the mappings in a string in to a data structure which we can easily - * query (the ordered arrays in the `this.__generatedMappings` and - * `this.__originalMappings` properties). + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private */ -BasicSourceMapConsumer.prototype._parseMappings = - function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { - var generatedLine = 1; - var previousGeneratedColumn = 0; - var previousOriginalLine = 0; - var previousOriginalColumn = 0; - var previousSource = 0; - var previousName = 0; - var length = aStr.length; - var index = 0; - var cachedSegments = {}; - var temp = {}; - var originalMappings = []; - var generatedMappings = []; - var mapping, str, segment, end, value; - - while (index < length) { - if (aStr.charAt(index) === ';') { - generatedLine++; - index++; - previousGeneratedColumn = 0; - } - else if (aStr.charAt(index) === ',') { - index++; - } - else { - mapping = new Mapping(); - mapping.generatedLine = generatedLine; - - // Because each offset is encoded relative to the previous one, - // many segments often have the same encoding. We can exploit this - // fact by caching the parsed variable length fields of each segment, - // allowing us to avoid a second parse if we encounter the same - // segment again. - for (end = index; end < length; end++) { - if (this._charIsMappingSeparator(aStr, end)) { - break; - } - } - str = aStr.slice(index, end); - - segment = cachedSegments[str]; - if (segment) { - index += str.length; - } else { - segment = []; - while (index < end) { - base64VLQ.decode(aStr, index, temp); - value = temp.value; - index = temp.rest; - segment.push(value); - } - - if (segment.length === 2) { - throw new Error('Found a source, but no line and column'); - } - - if (segment.length === 3) { - throw new Error('Found a source and line, but no column'); - } - - cachedSegments[str] = segment; - } - - // Generated column. - mapping.generatedColumn = previousGeneratedColumn + segment[0]; - previousGeneratedColumn = mapping.generatedColumn; - if (segment.length > 1) { - // Original source. - mapping.source = previousSource + segment[1]; - previousSource += segment[1]; - - // Original line. - mapping.originalLine = previousOriginalLine + segment[2]; - previousOriginalLine = mapping.originalLine; - // Lines are stored 0-based - mapping.originalLine += 1; - - // Original column. - mapping.originalColumn = previousOriginalColumn + segment[3]; - previousOriginalColumn = mapping.originalColumn; - - if (segment.length > 4) { - // Original name. - mapping.name = previousName + segment[4]; - previousName += segment[4]; - } - } - - generatedMappings.push(mapping); - if (typeof mapping.originalLine === 'number') { - originalMappings.push(mapping); - } - } - } +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'weeks': + case 'week': + case 'w': + return n * w; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} - quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated); - this.__generatedMappings = generatedMappings; +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ - quickSort(originalMappings, util.compareByOriginalPositions); - this.__originalMappings = originalMappings; - }; +function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; + } + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; + } + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; + } + if (msAbs >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} /** - * Find the mapping that best matches the hypothetical "needle" mapping that - * we are searching for in the given "haystack" of mappings. + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private */ -BasicSourceMapConsumer.prototype._findMapping = - function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, - aColumnName, aComparator, aBias) { - // To return the position we are searching for, we must first find the - // mapping for the given position and then return the opposite position it - // points to. Because the mappings are sorted, we can use binary search to - // find the best mapping. - - if (aNeedle[aLineName] <= 0) { - throw new TypeError('Line must be greater than or equal to 1, got ' - + aNeedle[aLineName]); - } - if (aNeedle[aColumnName] < 0) { - throw new TypeError('Column must be greater than or equal to 0, got ' - + aNeedle[aColumnName]); - } - return binarySearch.search(aNeedle, aMappings, aComparator, aBias); - }; +function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); + } + return ms + ' ms'; +} /** - * Compute the last column for each generated mapping. The last column is - * inclusive. + * Pluralization helper. */ -BasicSourceMapConsumer.prototype.computeColumnSpans = - function SourceMapConsumer_computeColumnSpans() { - for (var index = 0; index < this._generatedMappings.length; ++index) { - var mapping = this._generatedMappings[index]; - // Mappings do not contain a field for the last generated columnt. We - // can come up with an optimistic estimate, however, by assuming that - // mappings are contiguous (i.e. given two consecutive mappings, the - // first mapping ends where the second one starts). - if (index + 1 < this._generatedMappings.length) { - var nextMapping = this._generatedMappings[index + 1]; +function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); +} - if (mapping.generatedLine === nextMapping.generatedLine) { - mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; - continue; - } - } - // The last mapping for each line spans the entire line. - mapping.lastGeneratedColumn = Infinity; - } - }; +/***/ }), +/* 318 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { -/** - * Returns the original source, line, and column information for the generated - * source's line and column positions provided. The only argument is an object - * with the following properties: - * - * - line: The line number in the generated source. The line number - * is 1-based. - * - column: The column number in the generated source. The column - * number is 0-based. - * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or - * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. - * - * and an object is returned with the following properties: - * - * - source: The original source file, or null. - * - line: The line number in the original source, or null. The - * line number is 1-based. - * - column: The column number in the original source, or null. The - * column number is 0-based. - * - name: The original identifier, or null. - */ -BasicSourceMapConsumer.prototype.originalPositionFor = - function SourceMapConsumer_originalPositionFor(aArgs) { - var needle = { - generatedLine: util.getArg(aArgs, 'line'), - generatedColumn: util.getArg(aArgs, 'column') +Object.defineProperty(exports, "__esModule", { value: true }); +var utils_1 = __webpack_require__(657); +var SENTRY_API_VERSION = '7'; +/** Helper class to provide urls to different Sentry endpoints. */ +var API = /** @class */ (function () { + /** Create a new instance of API */ + function API(dsn) { + this.dsn = dsn; + this._dsnObject = new utils_1.Dsn(dsn); + } + /** Returns the Dsn object. */ + API.prototype.getDsn = function () { + return this._dsnObject; }; - - var index = this._findMapping( - needle, - this._generatedMappings, - "generatedLine", - "generatedColumn", - util.compareByGeneratedPositionsDeflated, - util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) - ); - - if (index >= 0) { - var mapping = this._generatedMappings[index]; - - if (mapping.generatedLine === needle.generatedLine) { - var source = util.getArg(mapping, 'source', null); - if (source !== null) { - source = this._sources.at(source); - source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL); - } - var name = util.getArg(mapping, 'name', null); - if (name !== null) { - name = this._names.at(name); + /** Returns the prefix to construct Sentry ingestion API endpoints. */ + API.prototype.getBaseApiEndpoint = function () { + var dsn = this._dsnObject; + var protocol = dsn.protocol ? dsn.protocol + ":" : ''; + var port = dsn.port ? ":" + dsn.port : ''; + return protocol + "//" + dsn.host + port + (dsn.path ? "/" + dsn.path : '') + "/api/"; + }; + /** Returns the store endpoint URL. */ + API.prototype.getStoreEndpoint = function () { + return this._getIngestEndpoint('store'); + }; + /** + * Returns the store endpoint URL with auth in the query string. + * + * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests. + */ + API.prototype.getStoreEndpointWithUrlEncodedAuth = function () { + return this.getStoreEndpoint() + "?" + this._encodedAuth(); + }; + /** + * Returns the envelope endpoint URL with auth in the query string. + * + * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests. + */ + API.prototype.getEnvelopeEndpointWithUrlEncodedAuth = function () { + return this._getEnvelopeEndpoint() + "?" + this._encodedAuth(); + }; + /** Returns only the path component for the store endpoint. */ + API.prototype.getStoreEndpointPath = function () { + var dsn = this._dsnObject; + return (dsn.path ? "/" + dsn.path : '') + "/api/" + dsn.projectId + "/store/"; + }; + /** + * Returns an object that can be used in request headers. + * This is needed for node and the old /store endpoint in sentry + */ + API.prototype.getRequestHeaders = function (clientName, clientVersion) { + var dsn = this._dsnObject; + var header = ["Sentry sentry_version=" + SENTRY_API_VERSION]; + header.push("sentry_client=" + clientName + "/" + clientVersion); + header.push("sentry_key=" + dsn.user); + if (dsn.pass) { + header.push("sentry_secret=" + dsn.pass); } return { - source: source, - line: util.getArg(mapping, 'originalLine', null), - column: util.getArg(mapping, 'originalColumn', null), - name: name + 'Content-Type': 'application/json', + 'X-Sentry-Auth': header.join(', '), }; - } - } - - return { - source: null, - line: null, - column: null, - name: null }; - }; + /** Returns the url to the report dialog endpoint. */ + API.prototype.getReportDialogEndpoint = function (dialogOptions) { + if (dialogOptions === void 0) { dialogOptions = {}; } + var dsn = this._dsnObject; + var endpoint = this.getBaseApiEndpoint() + "embed/error-page/"; + var encodedOptions = []; + encodedOptions.push("dsn=" + dsn.toString()); + for (var key in dialogOptions) { + if (key === 'user') { + if (!dialogOptions.user) { + continue; + } + if (dialogOptions.user.name) { + encodedOptions.push("name=" + encodeURIComponent(dialogOptions.user.name)); + } + if (dialogOptions.user.email) { + encodedOptions.push("email=" + encodeURIComponent(dialogOptions.user.email)); + } + } + else { + encodedOptions.push(encodeURIComponent(key) + "=" + encodeURIComponent(dialogOptions[key])); + } + } + if (encodedOptions.length) { + return endpoint + "?" + encodedOptions.join('&'); + } + return endpoint; + }; + /** Returns the envelope endpoint URL. */ + API.prototype._getEnvelopeEndpoint = function () { + return this._getIngestEndpoint('envelope'); + }; + /** Returns the ingest API endpoint for target. */ + API.prototype._getIngestEndpoint = function (target) { + var base = this.getBaseApiEndpoint(); + var dsn = this._dsnObject; + return "" + base + dsn.projectId + "/" + target + "/"; + }; + /** Returns a URL-encoded string with auth config suitable for a query string. */ + API.prototype._encodedAuth = function () { + var dsn = this._dsnObject; + var auth = { + // We send only the minimum set of required information. See + // https://github.com/getsentry/sentry-javascript/issues/2572. + sentry_key: dsn.user, + sentry_version: SENTRY_API_VERSION, + }; + return utils_1.urlEncode(auth); + }; + return API; +}()); +exports.API = API; +//# sourceMappingURL=api.js.map -/** - * Return true if we have the source content for every source in the source - * map, false otherwise. - */ -BasicSourceMapConsumer.prototype.hasContentsOfAllSources = - function BasicSourceMapConsumer_hasContentsOfAllSources() { - if (!this.sourcesContent) { - return false; - } - return this.sourcesContent.length >= this._sources.size() && - !this.sourcesContent.some(function (sc) { return sc == null; }); - }; +/***/ }), +/* 319 */ +/***/ (function(module) { /** - * Returns the original source content. The only argument is the url of the - * original source file. Returns null if no original source content is - * available. + * Helpers. */ -BasicSourceMapConsumer.prototype.sourceContentFor = - function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { - if (!this.sourcesContent) { - return null; - } - - var index = this._findSourceIndex(aSource); - if (index >= 0) { - return this.sourcesContent[index]; - } - - var relativeSource = aSource; - if (this.sourceRoot != null) { - relativeSource = util.relative(this.sourceRoot, relativeSource); - } - - var url; - if (this.sourceRoot != null - && (url = util.urlParse(this.sourceRoot))) { - // XXX: file:// URIs and absolute paths lead to unexpected behavior for - // many users. We can help them out when they expect file:// URIs to - // behave like it would if they were running a local HTTP server. See - // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. - var fileUriAbsPath = relativeSource.replace(/^file:\/\//, ""); - if (url.scheme == "file" - && this._sources.has(fileUriAbsPath)) { - return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] - } - if ((!url.path || url.path == "/") - && this._sources.has("/" + relativeSource)) { - return this.sourcesContent[this._sources.indexOf("/" + relativeSource)]; - } - } - - // This function is used recursively from - // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we - // don't want to throw if we can't find the source - we just want to - // return null, so we provide a flag to exit gracefully. - if (nullOnMissing) { - return null; - } - else { - throw new Error('"' + relativeSource + '" is not in the SourceMap.'); - } - }; +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var y = d * 365.25; /** - * Returns the generated line and column information for the original source, - * line, and column positions provided. The only argument is an object with - * the following properties: - * - * - source: The filename of the original source. - * - line: The line number in the original source. The line number - * is 1-based. - * - column: The column number in the original source. The column - * number is 0-based. - * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or - * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. - * - * and an object is returned with the following properties: - * - * - line: The line number in the generated source, or null. The - * line number is 1-based. - * - column: The column number in the generated source, or null. - * The column number is 0-based. - */ -BasicSourceMapConsumer.prototype.generatedPositionFor = - function SourceMapConsumer_generatedPositionFor(aArgs) { - var source = util.getArg(aArgs, 'source'); - source = this._findSourceIndex(source); - if (source < 0) { - return { - line: null, - column: null, - lastColumn: null - }; - } - - var needle = { - source: source, - originalLine: util.getArg(aArgs, 'line'), - originalColumn: util.getArg(aArgs, 'column') - }; - - var index = this._findMapping( - needle, - this._originalMappings, - "originalLine", - "originalColumn", - util.compareByOriginalPositions, - util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) - ); - - if (index >= 0) { - var mapping = this._originalMappings[index]; - - if (mapping.source === needle.source) { - return { - line: util.getArg(mapping, 'generatedLine', null), - column: util.getArg(mapping, 'generatedColumn', null), - lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) - }; - } - } - - return { - line: null, - column: null, - lastColumn: null - }; - }; - -exports.BasicSourceMapConsumer = BasicSourceMapConsumer; - -/** - * An IndexedSourceMapConsumer instance represents a parsed source map which - * we can query for information. It differs from BasicSourceMapConsumer in - * that it takes "indexed" source maps (i.e. ones with a "sections" field) as - * input. - * - * The first parameter is a raw source map (either as a JSON string, or already - * parsed to an object). According to the spec for indexed source maps, they - * have the following attributes: - * - * - version: Which version of the source map spec this map is following. - * - file: Optional. The generated file this source map is associated with. - * - sections: A list of section definitions. - * - * Each value under the "sections" field has two fields: - * - offset: The offset into the original specified at which this section - * begins to apply, defined as an object with a "line" and "column" - * field. - * - map: A source map definition. This source map could also be indexed, - * but doesn't have to be. - * - * Instead of the "map" field, it's also possible to have a "url" field - * specifying a URL to retrieve a source map from, but that's currently - * unsupported. - * - * Here's an example source map, taken from the source map spec[0], but - * modified to omit a section which uses the "url" field. - * - * { - * version : 3, - * file: "app.js", - * sections: [{ - * offset: {line:100, column:10}, - * map: { - * version : 3, - * file: "section.js", - * sources: ["foo.js", "bar.js"], - * names: ["src", "maps", "are", "fun"], - * mappings: "AAAA,E;;ABCDE;" - * } - * }], - * } + * Parse or format the given `val`. + * + * Options: * - * The second parameter, if given, is a string whose value is the URL - * at which the source map was found. This URL is used to compute the - * sources array. + * - `long` verbose formatting [false] * - * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public */ -function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) { - var sourceMap = aSourceMap; - if (typeof aSourceMap === 'string') { - sourceMap = util.parseSourceMapInput(aSourceMap); - } - var version = util.getArg(sourceMap, 'version'); - var sections = util.getArg(sourceMap, 'sections'); - - if (version != this._version) { - throw new Error('Unsupported version: ' + version); +module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isNaN(val) === false) { + return options.long ? fmtLong(val) : fmtShort(val); } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; - this._sources = new ArraySet(); - this._names = new ArraySet(); - - var lastOffset = { - line: -1, - column: 0 - }; - this._sections = sections.map(function (s) { - if (s.url) { - // The url field will require support for asynchronicity. - // See https://github.com/mozilla/source-map/issues/16 - throw new Error('Support for url field in sections not implemented.'); - } - var offset = util.getArg(s, 'offset'); - var offsetLine = util.getArg(offset, 'line'); - var offsetColumn = util.getArg(offset, 'column'); - - if (offsetLine < lastOffset.line || - (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { - throw new Error('Section offsets must be ordered and non-overlapping.'); - } - lastOffset = offset; +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ - return { - generatedOffset: { - // The offset fields are 0-based, but we use 1-based indices when - // encoding/decoding from VLQ. - generatedLine: offsetLine + 1, - generatedColumn: offsetColumn + 1 - }, - consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL) - } - }); +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } } -IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); -IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; - /** - * The version of the source mapping spec that we are consuming. + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private */ -IndexedSourceMapConsumer.prototype._version = 3; -/** - * The list of original sources. - */ -Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { - get: function () { - var sources = []; - for (var i = 0; i < this._sections.length; i++) { - for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { - sources.push(this._sections[i].consumer.sources[j]); - } - } - return sources; +function fmtShort(ms) { + if (ms >= d) { + return Math.round(ms / d) + 'd'; } -}); + if (ms >= h) { + return Math.round(ms / h) + 'h'; + } + if (ms >= m) { + return Math.round(ms / m) + 'm'; + } + if (ms >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} /** - * Returns the original source, line, and column information for the generated - * source's line and column positions provided. The only argument is an object - * with the following properties: - * - * - line: The line number in the generated source. The line number - * is 1-based. - * - column: The column number in the generated source. The column - * number is 0-based. - * - * and an object is returned with the following properties: + * Long format for `ms`. * - * - source: The original source file, or null. - * - line: The line number in the original source, or null. The - * line number is 1-based. - * - column: The column number in the original source, or null. The - * column number is 0-based. - * - name: The original identifier, or null. + * @param {Number} ms + * @return {String} + * @api private */ -IndexedSourceMapConsumer.prototype.originalPositionFor = - function IndexedSourceMapConsumer_originalPositionFor(aArgs) { - var needle = { - generatedLine: util.getArg(aArgs, 'line'), - generatedColumn: util.getArg(aArgs, 'column') - }; - - // Find the section containing the generated position we're trying to map - // to an original position. - var sectionIndex = binarySearch.search(needle, this._sections, - function(needle, section) { - var cmp = needle.generatedLine - section.generatedOffset.generatedLine; - if (cmp) { - return cmp; - } - - return (needle.generatedColumn - - section.generatedOffset.generatedColumn); - }); - var section = this._sections[sectionIndex]; - - if (!section) { - return { - source: null, - line: null, - column: null, - name: null - }; - } - return section.consumer.originalPositionFor({ - line: needle.generatedLine - - (section.generatedOffset.generatedLine - 1), - column: needle.generatedColumn - - (section.generatedOffset.generatedLine === needle.generatedLine - ? section.generatedOffset.generatedColumn - 1 - : 0), - bias: aArgs.bias - }); - }; +function fmtLong(ms) { + return plural(ms, d, 'day') || + plural(ms, h, 'hour') || + plural(ms, m, 'minute') || + plural(ms, s, 'second') || + ms + ' ms'; +} /** - * Return true if we have the source content for every source in the source - * map, false otherwise. + * Pluralization helper. */ -IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = - function IndexedSourceMapConsumer_hasContentsOfAllSources() { - return this._sections.every(function (s) { - return s.consumer.hasContentsOfAllSources(); - }); - }; -/** - * Returns the original source content. The only argument is the url of the - * original source file. Returns null if no original source content is - * available. - */ -IndexedSourceMapConsumer.prototype.sourceContentFor = - function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { - for (var i = 0; i < this._sections.length; i++) { - var section = this._sections[i]; +function plural(ms, n, name) { + if (ms < n) { + return; + } + if (ms < n * 1.5) { + return Math.floor(ms / n) + ' ' + name; + } + return Math.ceil(ms / n) + ' ' + name + 's'; +} - var content = section.consumer.sourceContentFor(aSource, true); - if (content) { - return content; - } - } - if (nullOnMissing) { - return null; - } - else { - throw new Error('"' + aSource + '" is not in the SourceMap.'); - } - }; -/** - * Returns the generated line and column information for the original source, - * line, and column positions provided. The only argument is an object with - * the following properties: - * - * - source: The filename of the original source. - * - line: The line number in the original source. The line number - * is 1-based. - * - column: The column number in the original source. The column - * number is 0-based. - * - * and an object is returned with the following properties: - * - * - line: The line number in the generated source, or null. The - * line number is 1-based. - * - column: The column number in the generated source, or null. - * The column number is 0-based. - */ -IndexedSourceMapConsumer.prototype.generatedPositionFor = - function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { - for (var i = 0; i < this._sections.length; i++) { - var section = this._sections[i]; +/***/ }), +/* 320 */, +/* 321 */ +/***/ (function(module) { - // Only consider this section if the requested source is in the list of - // sources of the consumer. - if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) { - continue; - } - var generatedPosition = section.consumer.generatedPositionFor(aArgs); - if (generatedPosition) { - var ret = { - line: generatedPosition.line + - (section.generatedOffset.generatedLine - 1), - column: generatedPosition.column + - (section.generatedOffset.generatedLine === generatedPosition.line - ? section.generatedOffset.generatedColumn - 1 - : 0) - }; - return ret; - } - } +"use strict"; - return { - line: null, - column: null - }; - }; +function tryStringify (o) { + try { return JSON.stringify(o) } catch(e) { return '"[Circular]"' } +} -/** - * Parse the mappings in a string in to a data structure which we can easily - * query (the ordered arrays in the `this.__generatedMappings` and - * `this.__originalMappings` properties). - */ -IndexedSourceMapConsumer.prototype._parseMappings = - function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { - this.__generatedMappings = []; - this.__originalMappings = []; - for (var i = 0; i < this._sections.length; i++) { - var section = this._sections[i]; - var sectionMappings = section.consumer._generatedMappings; - for (var j = 0; j < sectionMappings.length; j++) { - var mapping = sectionMappings[j]; - - var source = section.consumer._sources.at(mapping.source); - source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL); - this._sources.add(source); - source = this._sources.indexOf(source); - - var name = null; - if (mapping.name) { - name = section.consumer._names.at(mapping.name); - this._names.add(name); - name = this._names.indexOf(name); - } - - // The mappings coming from the consumer for the section have - // generated positions relative to the start of the section, so we - // need to offset them to be relative to the start of the concatenated - // generated file. - var adjustedMapping = { - source: source, - generatedLine: mapping.generatedLine + - (section.generatedOffset.generatedLine - 1), - generatedColumn: mapping.generatedColumn + - (section.generatedOffset.generatedLine === mapping.generatedLine - ? section.generatedOffset.generatedColumn - 1 - : 0), - originalLine: mapping.originalLine, - originalColumn: mapping.originalColumn, - name: name - }; +module.exports = format - this.__generatedMappings.push(adjustedMapping); - if (typeof adjustedMapping.originalLine === 'number') { - this.__originalMappings.push(adjustedMapping); - } +function format(f, args, opts) { + var ss = (opts && opts.stringify) || tryStringify + var offset = 1 + if (typeof f === 'object' && f !== null) { + var len = args.length + offset + if (len === 1) return f + var objects = new Array(len) + objects[0] = ss(f) + for (var index = 1; index < len; index++) { + objects[index] = ss(args[index]) + } + return objects.join(' ') + } + if (typeof f !== 'string') { + return f + } + var argLen = args.length + if (argLen === 0) return f + var x = '' + var str = '' + var a = 1 - offset + var lastPos = -1 + var flen = (f && f.length) || 0 + for (var i = 0; i < flen;) { + if (f.charCodeAt(i) === 37 && i + 1 < flen) { + lastPos = lastPos > -1 ? lastPos : 0 + switch (f.charCodeAt(i + 1)) { + case 100: // 'd' + if (a >= argLen) + break + if (lastPos < i) + str += f.slice(lastPos, i) + if (args[a] == null) break + str += Number(args[a]) + lastPos = i = i + 2 + break + case 79: // 'O' + case 111: // 'o' + case 106: // 'j' + if (a >= argLen) + break + if (lastPos < i) + str += f.slice(lastPos, i) + if (args[a] === undefined) break + var type = typeof args[a] + if (type === 'string') { + str += '\'' + args[a] + '\'' + lastPos = i + 2 + i++ + break + } + if (type === 'function') { + str += args[a].name || '' + lastPos = i + 2 + i++ + break + } + str += ss(args[a]) + lastPos = i + 2 + i++ + break + case 115: // 's' + if (a >= argLen) + break + if (lastPos < i) + str += f.slice(lastPos, i) + str += String(args[a]) + lastPos = i + 2 + i++ + break + case 37: // '%' + if (lastPos < i) + str += f.slice(lastPos, i) + str += '%' + lastPos = i + 2 + i++ + break } + ++a } + ++i + } + if (lastPos === -1) + return f + else if (lastPos < flen) { + str += f.slice(lastPos) + } - quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); - quickSort(this.__originalMappings, util.compareByOriginalPositions); - }; - -exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; + return str +} /***/ }), -/* 277 */ +/* 322 */ /***/ (function(module, __unusedexports, __webpack_require__) { -module.exports = authenticationPlugin; +"use strict"; +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ -const { createTokenAuth } = __webpack_require__(813); -const { Deprecation } = __webpack_require__(692); -const once = __webpack_require__(969); -const beforeRequest = __webpack_require__(48); -const requestError = __webpack_require__(684); -const validate = __webpack_require__(597); -const withAuthorizationPrefix = __webpack_require__(41); -const deprecateAuthBasic = once((log, deprecation) => log.warn(deprecation)); -const deprecateAuthObject = once((log, deprecation) => log.warn(deprecation)); +/** + * Module dependencies. + * @private + */ -function authenticationPlugin(octokit, options) { - // If `options.authStrategy` is set then use it and pass in `options.auth` - if (options.authStrategy) { - const auth = options.authStrategy(options.auth); - octokit.hook.wrap("request", auth.hook); - octokit.auth = auth; - return; - } +var pathRegexp = __webpack_require__(371); +var debug = __webpack_require__(590)('express:router:layer'); - // If neither `options.authStrategy` nor `options.auth` are set, the `octokit` instance - // is unauthenticated. The `octokit.auth()` method is a no-op and no request hook is registred. - if (!options.auth) { - octokit.auth = () => - Promise.resolve({ - type: "unauthenticated" - }); - return; - } +/** + * Module variables. + * @private + */ - const isBasicAuthString = - typeof options.auth === "string" && - /^basic/.test(withAuthorizationPrefix(options.auth)); +var hasOwnProperty = Object.prototype.hasOwnProperty; - // If only `options.auth` is set to a string, use the default token authentication strategy. - if (typeof options.auth === "string" && !isBasicAuthString) { - const auth = createTokenAuth(options.auth); - octokit.hook.wrap("request", auth.hook); - octokit.auth = auth; - return; - } +/** + * Module exports. + * @public + */ - // Otherwise log a deprecation message - const [deprecationMethod, deprecationMessapge] = isBasicAuthString - ? [ - deprecateAuthBasic, - 'Setting the "new Octokit({ auth })" option to a Basic Auth string is deprecated. Use https://github.com/octokit/auth-basic.js instead. See (https://octokit.github.io/rest.js/#authentication)' - ] - : [ - deprecateAuthObject, - 'Setting the "new Octokit({ auth })" option to an object without also setting the "authStrategy" option is deprecated and will be removed in v17. See (https://octokit.github.io/rest.js/#authentication)' - ]; - deprecationMethod( - octokit.log, - new Deprecation("[@octokit/rest] " + deprecationMessapge) - ); +module.exports = Layer; - octokit.auth = () => - Promise.resolve({ - type: "deprecated", - message: deprecationMessapge - }); +function Layer(path, options, fn) { + if (!(this instanceof Layer)) { + return new Layer(path, options, fn); + } - validate(options.auth); + debug('new %o', path) + var opts = options || {}; - const state = { - octokit, - auth: options.auth - }; + this.handle = fn; + this.name = fn.name || ''; + this.params = undefined; + this.path = undefined; + this.regexp = pathRegexp(path, this.keys = [], opts); - octokit.hook.before("request", beforeRequest.bind(null, state)); - octokit.hook.error("request", requestError.bind(null, state)); + // set fast path flags + this.regexp.fast_star = path === '*' + this.regexp.fast_slash = path === '/' && opts.end === false } +/** + * Handle the error for the layer. + * + * @param {Error} error + * @param {Request} req + * @param {Response} res + * @param {function} next + * @api private + */ -/***/ }), -/* 278 */, -/* 279 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +Layer.prototype.handle_error = function handle_error(error, req, res, next) { + var fn = this.handle; -var fs = __webpack_require__(747); -var ncp = __webpack_require__(670).ncp; -var path = __webpack_require__(622); -var rimraf = __webpack_require__(569); -var mkdirp = __webpack_require__(289); - -module.exports = mv; + if (fn.length !== 4) { + // not a standard error handler + return next(error); + } -function mv(source, dest, options, cb){ - if (typeof options === 'function') { - cb = options; - options = {}; + try { + fn(error, req, res, next); + } catch (err) { + next(err); } - var shouldMkdirp = !!options.mkdirp; - var clobber = options.clobber !== false; - var limit = options.limit || 16; +}; - if (shouldMkdirp) { - mkdirs(); - } else { - doRename(); +/** + * Handle the request for the layer. + * + * @param {Request} req + * @param {Response} res + * @param {function} next + * @api private + */ + +Layer.prototype.handle_request = function handle(req, res, next) { + var fn = this.handle; + + if (fn.length > 3) { + // not a standard request handler + return next(); } - function mkdirs() { - mkdirp(path.dirname(dest), function(err) { - if (err) return cb(err); - doRename(); - }); + try { + fn(req, res, next); + } catch (err) { + next(err); } +}; - function doRename() { - if (clobber) { - fs.rename(source, dest, function(err) { - if (!err) return cb(); - if (err.code !== 'EXDEV') return cb(err); - moveFileAcrossDevice(source, dest, clobber, limit, cb); - }); - } else { - fs.link(source, dest, function(err) { - if (err) { - if (err.code === 'EXDEV') { - moveFileAcrossDevice(source, dest, clobber, limit, cb); - return; - } - if (err.code === 'EISDIR' || err.code === 'EPERM') { - moveDirAcrossDevice(source, dest, clobber, limit, cb); - return; - } - cb(err); - return; - } - fs.unlink(source, cb); - }); +/** + * Check if this route matches `path`, if so + * populate `.params`. + * + * @param {String} path + * @return {Boolean} + * @api private + */ + +Layer.prototype.match = function match(path) { + var match + + if (path != null) { + // fast path non-ending match for / (any path matches) + if (this.regexp.fast_slash) { + this.params = {} + this.path = '' + return true } - } -} -function moveFileAcrossDevice(source, dest, clobber, limit, cb) { - var outFlags = clobber ? 'w' : 'wx'; - var ins = fs.createReadStream(source); - var outs = fs.createWriteStream(dest, {flags: outFlags}); - ins.on('error', function(err){ - ins.destroy(); - outs.destroy(); - outs.removeListener('close', onClose); - if (err.code === 'EISDIR' || err.code === 'EPERM') { - moveDirAcrossDevice(source, dest, clobber, limit, cb); - } else { - cb(err); + // fast path for * (everything matched in a param) + if (this.regexp.fast_star) { + this.params = {'0': decode_param(path)} + this.path = path + return true } - }); - outs.on('error', function(err){ - ins.destroy(); - outs.destroy(); - outs.removeListener('close', onClose); - cb(err); - }); - outs.once('close', onClose); - ins.pipe(outs); - function onClose(){ - fs.unlink(source, cb); - } -} -function moveDirAcrossDevice(source, dest, clobber, limit, cb) { - var options = { - stopOnErr: true, - clobber: false, - limit: limit, - }; - if (clobber) { - rimraf(dest, { disableGlob: true }, function(err) { - if (err) return cb(err); - startNcp(); - }); - } else { - startNcp(); + // match the path + match = this.regexp.exec(path) } - function startNcp() { - ncp(source, dest, options, function(errList) { - if (errList) return cb(errList[0]); - rimraf(source, { disableGlob: true }, cb); - }); + + if (!match) { + this.params = undefined; + this.path = undefined; + return false; } -} + // store values + this.params = {}; + this.path = match[0] -/***/ }), -/* 280 */ -/***/ (function(module, exports) { + var keys = this.keys; + var params = this.params; -exports = module.exports = SemVer + for (var i = 1; i < match.length; i++) { + var key = keys[i - 1]; + var prop = key.name; + var val = decode_param(match[i]) -var debug -/* istanbul ignore next */ -if (typeof process === 'object' && - process.env && - process.env.NODE_DEBUG && - /\bsemver\b/i.test(process.env.NODE_DEBUG)) { - debug = function () { - var args = Array.prototype.slice.call(arguments, 0) - args.unshift('SEMVER') - console.log.apply(console, args) + if (val !== undefined || !(hasOwnProperty.call(params, prop))) { + params[prop] = val; + } } -} else { - debug = function () {} -} -// Note: this is the semver.org version of the spec that it implements -// Not necessarily the package version of this code. -exports.SEMVER_SPEC_VERSION = '2.0.0' + return true; +}; -var MAX_LENGTH = 256 -var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || - /* istanbul ignore next */ 9007199254740991 +/** + * Decode param value. + * + * @param {string} val + * @return {string} + * @private + */ -// Max safe segment length for coercion. -var MAX_SAFE_COMPONENT_LENGTH = 16 +function decode_param(val) { + if (typeof val !== 'string' || val.length === 0) { + return val; + } -// The actual regexps go on exports.re -var re = exports.re = [] -var src = exports.src = [] -var R = 0 + try { + return decodeURIComponent(val); + } catch (err) { + if (err instanceof URIError) { + err.message = 'Failed to decode param \'' + val + '\''; + err.status = err.statusCode = 400; + } -// The following Regular Expressions can be used for tokenizing, -// validating, and parsing SemVer version strings. + throw err; + } +} -// ## Numeric Identifier -// A single `0`, or a non-zero digit followed by zero or more digits. -var NUMERICIDENTIFIER = R++ -src[NUMERICIDENTIFIER] = '0|[1-9]\\d*' -var NUMERICIDENTIFIERLOOSE = R++ -src[NUMERICIDENTIFIERLOOSE] = '[0-9]+' +/***/ }), +/* 323 */ +/***/ (function(module) { -// ## Non-numeric Identifier -// Zero or more digits, followed by a letter or hyphen, and then zero or -// more letters, digits, or hyphens. +"use strict"; -var NONNUMERICIDENTIFIER = R++ -src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*' -// ## Main Version -// Three dot-separated numeric identifiers. +var isStream = module.exports = function (stream) { + return stream !== null && typeof stream === 'object' && typeof stream.pipe === 'function'; +}; -var MAINVERSION = R++ -src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + - '(' + src[NUMERICIDENTIFIER] + ')\\.' + - '(' + src[NUMERICIDENTIFIER] + ')' +isStream.writable = function (stream) { + return isStream(stream) && stream.writable !== false && typeof stream._write === 'function' && typeof stream._writableState === 'object'; +}; -var MAINVERSIONLOOSE = R++ -src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + - '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + - '(' + src[NUMERICIDENTIFIERLOOSE] + ')' +isStream.readable = function (stream) { + return isStream(stream) && stream.readable !== false && typeof stream._read === 'function' && typeof stream._readableState === 'object'; +}; -// ## Pre-release Version Identifier -// A numeric identifier, or a non-numeric identifier. +isStream.duplex = function (stream) { + return isStream.writable(stream) && isStream.readable(stream); +}; -var PRERELEASEIDENTIFIER = R++ -src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + - '|' + src[NONNUMERICIDENTIFIER] + ')' +isStream.transform = function (stream) { + return isStream.duplex(stream) && typeof stream._transform === 'function' && typeof stream._transformState === 'object'; +}; -var PRERELEASEIDENTIFIERLOOSE = R++ -src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + - '|' + src[NONNUMERICIDENTIFIER] + ')' -// ## Pre-release Version -// Hyphen, followed by one or more dot-separated pre-release version -// identifiers. +/***/ }), +/* 324 */ +/***/ (function(module, __unusedexports, __webpack_require__) { -var PRERELEASE = R++ -src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + - '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))' +"use strict"; -var PRERELEASELOOSE = R++ -src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + - '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))' -// ## Build Metadata Identifier -// Any combination of digits, letters, or hyphens. +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } -var BUILDIDENTIFIER = R++ -src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+' +function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } -// ## Build Metadata -// Plus sign, followed by one or more period-separated build metadata -// identifiers. +function _toArray(arr) { return _arrayWithHoles(arr) || _iterableToArray(arr) || _nonIterableRest(); } -var BUILD = R++ -src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + - '(?:\\.' + src[BUILDIDENTIFIER] + ')*))' +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } -// ## Full Version String -// A main version, followed optionally by a pre-release version and -// build metadata. +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } -// Note that the only major, minor, patch, and pre-release sections of -// the version string are capturing groups. The build metadata is not a -// capturing group, because it should not ever be used in version -// comparison. +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } -var FULL = R++ -var FULLPLAIN = 'v?' + src[MAINVERSION] + - src[PRERELEASE] + '?' + - src[BUILD] + '?' +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } -src[FULL] = '^' + FULLPLAIN + '$' +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } -// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. -// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty -// common in the npm registry. -var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + - src[PRERELEASELOOSE] + '?' + - src[BUILD] + '?' +var Bottleneck, + DEFAULT_PRIORITY, + Events, + Job, + LocalDatastore, + NUM_PRIORITIES, + Queues, + RedisDatastore, + States, + Sync, + parser, + splice = [].splice; +NUM_PRIORITIES = 10; +DEFAULT_PRIORITY = 5; +parser = __webpack_require__(850); +Queues = __webpack_require__(879); +Job = __webpack_require__(461); +LocalDatastore = __webpack_require__(37); +RedisDatastore = __webpack_require__(414); +Events = __webpack_require__(833); +States = __webpack_require__(61); +Sync = __webpack_require__(328); -var LOOSE = R++ -src[LOOSE] = '^' + LOOSEPLAIN + '$' +Bottleneck = function () { + class Bottleneck { + constructor(options = {}, ...invalid) { + var storeInstanceOptions, storeOptions; + this._addToQueue = this._addToQueue.bind(this); -var GTLT = R++ -src[GTLT] = '((?:<|>)?=?)' + this._validateOptions(options, invalid); -// Something like "2.*" or "1.2.x". -// Note that "x.x" is a valid xRange identifer, meaning "any version" -// Only the first item is strictly required. -var XRANGEIDENTIFIERLOOSE = R++ -src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*' -var XRANGEIDENTIFIER = R++ -src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*' + parser.load(options, this.instanceDefaults, this); + this._queues = new Queues(NUM_PRIORITIES); + this._scheduled = {}; + this._states = new States(["RECEIVED", "QUEUED", "RUNNING", "EXECUTING"].concat(this.trackDoneStatus ? ["DONE"] : [])); + this._limiter = null; + this.Events = new Events(this); + this._submitLock = new Sync("submit", this.Promise); + this._registerLock = new Sync("register", this.Promise); + storeOptions = parser.load(options, this.storeDefaults, {}); -var XRANGEPLAIN = R++ -src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + - '(?:' + src[PRERELEASE] + ')?' + - src[BUILD] + '?' + - ')?)?' + this._store = function () { + if (this.datastore === "redis" || this.datastore === "ioredis" || this.connection != null) { + storeInstanceOptions = parser.load(options, this.redisStoreDefaults, {}); + return new RedisDatastore(this, storeOptions, storeInstanceOptions); + } else if (this.datastore === "local") { + storeInstanceOptions = parser.load(options, this.localStoreDefaults, {}); + return new LocalDatastore(this, storeOptions, storeInstanceOptions); + } else { + throw new Bottleneck.prototype.BottleneckError(`Invalid datastore type: ${this.datastore}`); + } + }.call(this); -var XRANGEPLAINLOOSE = R++ -src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:' + src[PRERELEASELOOSE] + ')?' + - src[BUILD] + '?' + - ')?)?' + this._queues.on("leftzero", () => { + var ref; + return (ref = this._store.heartbeat) != null ? typeof ref.ref === "function" ? ref.ref() : void 0 : void 0; + }); -var XRANGE = R++ -src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$' -var XRANGELOOSE = R++ -src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$' + this._queues.on("zero", () => { + var ref; + return (ref = this._store.heartbeat) != null ? typeof ref.unref === "function" ? ref.unref() : void 0 : void 0; + }); + } -// Coercion. -// Extract anything that could conceivably be a part of a valid semver -var COERCE = R++ -src[COERCE] = '(?:^|[^\\d])' + - '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + - '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + - '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + - '(?:$|[^\\d])' + _validateOptions(options, invalid) { + if (!(options != null && typeof options === "object" && invalid.length === 0)) { + throw new Bottleneck.prototype.BottleneckError("Bottleneck v2 takes a single object argument. Refer to https://github.com/SGrondin/bottleneck#upgrading-to-v2 if you're upgrading from Bottleneck v1."); + } + } -// Tilde ranges. -// Meaning is "reasonably at or greater than" -var LONETILDE = R++ -src[LONETILDE] = '(?:~>?)' + ready() { + return this._store.ready; + } -var TILDETRIM = R++ -src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+' -re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g') -var tildeTrimReplace = '$1~' + clients() { + return this._store.clients; + } -var TILDE = R++ -src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$' -var TILDELOOSE = R++ -src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$' + channel() { + return `b_${this.id}`; + } -// Caret ranges. -// Meaning is "at least and backwards compatible with" -var LONECARET = R++ -src[LONECARET] = '(?:\\^)' + channel_client() { + return `b_${this.id}_${this._store.clientId}`; + } -var CARETTRIM = R++ -src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+' -re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g') -var caretTrimReplace = '$1^' + publish(message) { + return this._store.__publish__(message); + } -var CARET = R++ -src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$' -var CARETLOOSE = R++ -src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$' + disconnect(flush = true) { + return this._store.__disconnect__(flush); + } -// A simple gt/lt/eq thing, or just "" to indicate "any version" -var COMPARATORLOOSE = R++ -src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$' -var COMPARATOR = R++ -src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$' + chain(_limiter) { + this._limiter = _limiter; + return this; + } -// An expression to strip any whitespace between the gtlt and the thing -// it modifies, so that `> 1.2.3` ==> `>1.2.3` -var COMPARATORTRIM = R++ -src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + - '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')' + queued(priority) { + return this._queues.queued(priority); + } -// this one has to use the /g flag -re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g') -var comparatorTrimReplace = '$1$2$3' + clusterQueued() { + return this._store.__queued__(); + } -// Something like `1.2.3 - 1.2.4` -// Note that these all use the loose form, because they'll be -// checked against either the strict or loose comparator form -// later. -var HYPHENRANGE = R++ -src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + - '\\s+-\\s+' + - '(' + src[XRANGEPLAIN] + ')' + - '\\s*$' + empty() { + return this.queued() === 0 && this._submitLock.isEmpty(); + } -var HYPHENRANGELOOSE = R++ -src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + - '\\s+-\\s+' + - '(' + src[XRANGEPLAINLOOSE] + ')' + - '\\s*$' + running() { + return this._store.__running__(); + } -// Star ranges basically just allow anything at all. -var STAR = R++ -src[STAR] = '(<|>)?=?\\s*\\*' + done() { + return this._store.__done__(); + } -// Compile to actual regexp objects. -// All are flag-free, unless they were created above with a flag. -for (var i = 0; i < R; i++) { - debug(i, src[i]) - if (!re[i]) { - re[i] = new RegExp(src[i]) - } -} + jobStatus(id) { + return this._states.jobStatus(id); + } -exports.parse = parse -function parse (version, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false + jobs(status) { + return this._states.statusJobs(status); } - } - if (version instanceof SemVer) { - return version - } + counts() { + return this._states.statusCounts(); + } - if (typeof version !== 'string') { - return null - } + _randomIndex() { + return Math.random().toString(36).slice(2); + } - if (version.length > MAX_LENGTH) { - return null - } + check(weight = 1) { + return this._store.__check__(weight); + } - var r = options.loose ? re[LOOSE] : re[FULL] - if (!r.test(version)) { - return null - } + _clearGlobalState(index) { + if (this._scheduled[index] != null) { + clearTimeout(this._scheduled[index].expiration); + delete this._scheduled[index]; + return true; + } else { + return false; + } + } - try { - return new SemVer(version, options) - } catch (er) { - return null - } -} + _free(index, job, options, eventInfo) { + var _this = this; -exports.valid = valid -function valid (version, options) { - var v = parse(version, options) - return v ? v.version : null -} + return _asyncToGenerator(function* () { + var e, running; -exports.clean = clean -function clean (version, options) { - var s = parse(version.trim().replace(/^[=v]+/, ''), options) - return s ? s.version : null -} + try { + var _ref = yield _this._store.__free__(index, options.weight); -exports.SemVer = SemVer + running = _ref.running; -function SemVer (version, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } - if (version instanceof SemVer) { - if (version.loose === options.loose) { - return version - } else { - version = version.version + _this.Events.trigger("debug", `Freed ${options.id}`, eventInfo); + + if (running === 0 && _this.empty()) { + return _this.Events.trigger("idle"); + } + } catch (error1) { + e = error1; + return _this.Events.trigger("error", e); + } + })(); } - } else if (typeof version !== 'string') { - throw new TypeError('Invalid Version: ' + version) - } - if (version.length > MAX_LENGTH) { - throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') - } + _run(index, job, wait) { + var clearGlobalState, free, run; + job.doRun(); + clearGlobalState = this._clearGlobalState.bind(this, index); + run = this._run.bind(this, index, job); + free = this._free.bind(this, index, job); + return this._scheduled[index] = { + timeout: setTimeout(() => { + return job.doExecute(this._limiter, clearGlobalState, run, free); + }, wait), + expiration: job.options.expiration != null ? setTimeout(function () { + return job.doExpire(clearGlobalState, run, free); + }, wait + job.options.expiration) : void 0, + job: job + }; + } - if (!(this instanceof SemVer)) { - return new SemVer(version, options) - } + _drainOne(capacity) { + return this._registerLock.schedule(() => { + var args, index, next, options, queue; - debug('SemVer', version, options) - this.options = options - this.loose = !!options.loose + if (this.queued() === 0) { + return this.Promise.resolve(null); + } - var m = version.trim().match(options.loose ? re[LOOSE] : re[FULL]) + queue = this._queues.getFirst(); - if (!m) { - throw new TypeError('Invalid Version: ' + version) - } + var _next2 = next = queue.first(); - this.raw = version + options = _next2.options; + args = _next2.args; - // these are actually numbers - this.major = +m[1] - this.minor = +m[2] - this.patch = +m[3] + if (capacity != null && options.weight > capacity) { + return this.Promise.resolve(null); + } - if (this.major > MAX_SAFE_INTEGER || this.major < 0) { - throw new TypeError('Invalid major version') - } + this.Events.trigger("debug", `Draining ${options.id}`, { + args, + options + }); + index = this._randomIndex(); + return this._store.__register__(index, options.weight, options.expiration).then(({ + success, + wait, + reservoir + }) => { + var empty; + this.Events.trigger("debug", `Drained ${options.id}`, { + success, + args, + options + }); - if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { - throw new TypeError('Invalid minor version') - } + if (success) { + queue.shift(); + empty = this.empty(); - if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { - throw new TypeError('Invalid patch version') - } + if (empty) { + this.Events.trigger("empty"); + } - // numberify any prerelease numeric ids - if (!m[4]) { - this.prerelease = [] - } else { - this.prerelease = m[4].split('.').map(function (id) { - if (/^[0-9]+$/.test(id)) { - var num = +id - if (num >= 0 && num < MAX_SAFE_INTEGER) { - return num - } - } - return id - }) - } + if (reservoir === 0) { + this.Events.trigger("depleted", empty); + } - this.build = m[5] ? m[5].split('.') : [] - this.format() -} + this._run(index, next, wait); -SemVer.prototype.format = function () { - this.version = this.major + '.' + this.minor + '.' + this.patch - if (this.prerelease.length) { - this.version += '-' + this.prerelease.join('.') - } - return this.version -} + return this.Promise.resolve(options.weight); + } else { + return this.Promise.resolve(null); + } + }); + }); + } -SemVer.prototype.toString = function () { - return this.version -} + _drainAll(capacity, total = 0) { + return this._drainOne(capacity).then(drained => { + var newCapacity; -SemVer.prototype.compare = function (other) { - debug('SemVer.compare', this.version, this.options, other) - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } + if (drained != null) { + newCapacity = capacity != null ? capacity - drained : capacity; + return this._drainAll(newCapacity, total + drained); + } else { + return this.Promise.resolve(total); + } + }).catch(e => { + return this.Events.trigger("error", e); + }); + } - return this.compareMain(other) || this.comparePre(other) -} + _dropAllQueued(message) { + return this._queues.shiftAll(function (job) { + return job.doDrop({ + message + }); + }); + } -SemVer.prototype.compareMain = function (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } + stop(options = {}) { + var done, waitForExecuting; + options = parser.load(options, this.stopDefaults); - return compareIdentifiers(this.major, other.major) || - compareIdentifiers(this.minor, other.minor) || - compareIdentifiers(this.patch, other.patch) -} + waitForExecuting = at => { + var finished; -SemVer.prototype.comparePre = function (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } + finished = () => { + var counts; + counts = this._states.counts; + return counts[0] + counts[1] + counts[2] + counts[3] === at; + }; - // NOT having a prerelease is > having one - if (this.prerelease.length && !other.prerelease.length) { - return -1 - } else if (!this.prerelease.length && other.prerelease.length) { - return 1 - } else if (!this.prerelease.length && !other.prerelease.length) { - return 0 - } + return new this.Promise((resolve, reject) => { + if (finished()) { + return resolve(); + } else { + return this.on("done", () => { + if (finished()) { + this.removeAllListeners("done"); + return resolve(); + } + }); + } + }); + }; - var i = 0 - do { - var a = this.prerelease[i] - var b = other.prerelease[i] - debug('prerelease compare', i, a, b) - if (a === undefined && b === undefined) { - return 0 - } else if (b === undefined) { - return 1 - } else if (a === undefined) { - return -1 - } else if (a === b) { - continue - } else { - return compareIdentifiers(a, b) - } - } while (++i) -} + done = options.dropWaitingJobs ? (this._run = function (index, next) { + return next.doDrop({ + message: options.dropErrorMessage + }); + }, this._drainOne = () => { + return this.Promise.resolve(null); + }, this._registerLock.schedule(() => { + return this._submitLock.schedule(() => { + var k, ref, v; + ref = this._scheduled; -// preminor will bump the version up to the next minor release, and immediately -// down to pre-release. premajor and prepatch work the same way. -SemVer.prototype.inc = function (release, identifier) { - switch (release) { - case 'premajor': - this.prerelease.length = 0 - this.patch = 0 - this.minor = 0 - this.major++ - this.inc('pre', identifier) - break - case 'preminor': - this.prerelease.length = 0 - this.patch = 0 - this.minor++ - this.inc('pre', identifier) - break - case 'prepatch': - // If this is already a prerelease, it will bump to the next version - // drop any prereleases that might already exist, since they are not - // relevant at this point. - this.prerelease.length = 0 - this.inc('patch', identifier) - this.inc('pre', identifier) - break - // If the input is a non-prerelease version, this acts the same as - // prepatch. - case 'prerelease': - if (this.prerelease.length === 0) { - this.inc('patch', identifier) - } - this.inc('pre', identifier) - break + for (k in ref) { + v = ref[k]; - case 'major': - // If this is a pre-major version, bump up to the same major version. - // Otherwise increment major. - // 1.0.0-5 bumps to 1.0.0 - // 1.1.0 bumps to 2.0.0 - if (this.minor !== 0 || - this.patch !== 0 || - this.prerelease.length === 0) { - this.major++ - } - this.minor = 0 - this.patch = 0 - this.prerelease = [] - break - case 'minor': - // If this is a pre-minor version, bump up to the same minor version. - // Otherwise increment minor. - // 1.2.0-5 bumps to 1.2.0 - // 1.2.1 bumps to 1.3.0 - if (this.patch !== 0 || this.prerelease.length === 0) { - this.minor++ - } - this.patch = 0 - this.prerelease = [] - break - case 'patch': - // If this is not a pre-release version, it will increment the patch. - // If it is a pre-release it will bump up to the same patch version. - // 1.2.0-5 patches to 1.2.0 - // 1.2.0 patches to 1.2.1 - if (this.prerelease.length === 0) { - this.patch++ - } - this.prerelease = [] - break - // This probably shouldn't be used publicly. - // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. - case 'pre': - if (this.prerelease.length === 0) { - this.prerelease = [0] - } else { - var i = this.prerelease.length - while (--i >= 0) { - if (typeof this.prerelease[i] === 'number') { - this.prerelease[i]++ - i = -2 - } - } - if (i === -1) { - // didn't increment anything - this.prerelease.push(0) - } - } - if (identifier) { - // 1.2.0-beta.1 bumps to 1.2.0-beta.2, - // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 - if (this.prerelease[0] === identifier) { - if (isNaN(this.prerelease[1])) { - this.prerelease = [identifier, 0] + if (this.jobStatus(v.job.options.id) === "RUNNING") { + clearTimeout(v.timeout); + clearTimeout(v.expiration); + v.job.doDrop({ + message: options.dropErrorMessage + }); + } } - } else { - this.prerelease = [identifier, 0] - } - } - break - default: - throw new Error('invalid increment argument: ' + release) - } - this.format() - this.raw = this.version - return this -} + this._dropAllQueued(options.dropErrorMessage); -exports.inc = inc -function inc (version, release, loose, identifier) { - if (typeof (loose) === 'string') { - identifier = loose - loose = undefined - } + return waitForExecuting(0); + }); + })) : this.schedule({ + priority: NUM_PRIORITIES - 1, + weight: 0 + }, () => { + return waitForExecuting(1); + }); - try { - return new SemVer(version, loose).inc(release, identifier).version - } catch (er) { - return null - } -} + this._receive = function (job) { + return job._reject(new Bottleneck.prototype.BottleneckError(options.enqueueErrorMessage)); + }; -exports.diff = diff -function diff (version1, version2) { - if (eq(version1, version2)) { - return null - } else { - var v1 = parse(version1) - var v2 = parse(version2) - var prefix = '' - if (v1.prerelease.length || v2.prerelease.length) { - prefix = 'pre' - var defaultResult = 'prerelease' - } - for (var key in v1) { - if (key === 'major' || key === 'minor' || key === 'patch') { - if (v1[key] !== v2[key]) { - return prefix + key - } - } - } - return defaultResult // may be undefined - } -} + this.stop = () => { + return this.Promise.reject(new Bottleneck.prototype.BottleneckError("stop() has already been called")); + }; -exports.compareIdentifiers = compareIdentifiers + return done; + } -var numeric = /^[0-9]+$/ -function compareIdentifiers (a, b) { - var anum = numeric.test(a) - var bnum = numeric.test(b) + _addToQueue(job) { + var _this2 = this; - if (anum && bnum) { - a = +a - b = +b - } + return _asyncToGenerator(function* () { + var args, blocked, error, options, reachedHWM, shifted, strategy; + args = job.args; + options = job.options; - return a === b ? 0 - : (anum && !bnum) ? -1 - : (bnum && !anum) ? 1 - : a < b ? -1 - : 1 -} + try { + var _ref2 = yield _this2._store.__submit__(_this2.queued(), options.weight); -exports.rcompareIdentifiers = rcompareIdentifiers -function rcompareIdentifiers (a, b) { - return compareIdentifiers(b, a) -} + reachedHWM = _ref2.reachedHWM; + blocked = _ref2.blocked; + strategy = _ref2.strategy; + } catch (error1) { + error = error1; -exports.major = major -function major (a, loose) { - return new SemVer(a, loose).major -} + _this2.Events.trigger("debug", `Could not queue ${options.id}`, { + args, + options, + error + }); -exports.minor = minor -function minor (a, loose) { - return new SemVer(a, loose).minor -} + job.doDrop({ + error + }); + return false; + } -exports.patch = patch -function patch (a, loose) { - return new SemVer(a, loose).patch -} + if (blocked) { + job.doDrop(); + return true; + } else if (reachedHWM) { + shifted = strategy === Bottleneck.prototype.strategy.LEAK ? _this2._queues.shiftLastFrom(options.priority) : strategy === Bottleneck.prototype.strategy.OVERFLOW_PRIORITY ? _this2._queues.shiftLastFrom(options.priority + 1) : strategy === Bottleneck.prototype.strategy.OVERFLOW ? job : void 0; -exports.compare = compare -function compare (a, b, loose) { - return new SemVer(a, loose).compare(new SemVer(b, loose)) -} + if (shifted != null) { + shifted.doDrop(); + } -exports.compareLoose = compareLoose -function compareLoose (a, b) { - return compare(a, b, true) -} + if (shifted == null || strategy === Bottleneck.prototype.strategy.OVERFLOW) { + if (shifted == null) { + job.doDrop(); + } -exports.rcompare = rcompare -function rcompare (a, b, loose) { - return compare(b, a, loose) -} + return reachedHWM; + } + } -exports.sort = sort -function sort (list, loose) { - return list.sort(function (a, b) { - return exports.compare(a, b, loose) - }) -} + job.doQueue(reachedHWM, blocked); -exports.rsort = rsort -function rsort (list, loose) { - return list.sort(function (a, b) { - return exports.rcompare(a, b, loose) - }) -} + _this2._queues.push(job); -exports.gt = gt -function gt (a, b, loose) { - return compare(a, b, loose) > 0 -} + yield _this2._drainAll(); + return reachedHWM; + })(); + } -exports.lt = lt -function lt (a, b, loose) { - return compare(a, b, loose) < 0 -} + _receive(job) { + if (this._states.jobStatus(job.options.id) != null) { + job._reject(new Bottleneck.prototype.BottleneckError(`A job with the same id already exists (id=${job.options.id})`)); -exports.eq = eq -function eq (a, b, loose) { - return compare(a, b, loose) === 0 -} - -exports.neq = neq -function neq (a, b, loose) { - return compare(a, b, loose) !== 0 -} + return false; + } else { + job.doReceive(); + return this._submitLock.schedule(this._addToQueue, job); + } + } -exports.gte = gte -function gte (a, b, loose) { - return compare(a, b, loose) >= 0 -} + submit(...args) { + var cb, fn, job, options, ref, ref1, task; -exports.lte = lte -function lte (a, b, loose) { - return compare(a, b, loose) <= 0 -} + if (typeof args[0] === "function") { + var _ref3, _ref4, _splice$call, _splice$call2; -exports.cmp = cmp -function cmp (a, op, b, loose) { - switch (op) { - case '===': - if (typeof a === 'object') - a = a.version - if (typeof b === 'object') - b = b.version - return a === b + ref = args, (_ref3 = ref, _ref4 = _toArray(_ref3), fn = _ref4[0], args = _ref4.slice(1), _ref3), (_splice$call = splice.call(args, -1), _splice$call2 = _slicedToArray(_splice$call, 1), cb = _splice$call2[0], _splice$call); + options = parser.load({}, this.jobDefaults); + } else { + var _ref5, _ref6, _splice$call3, _splice$call4; - case '!==': - if (typeof a === 'object') - a = a.version - if (typeof b === 'object') - b = b.version - return a !== b + ref1 = args, (_ref5 = ref1, _ref6 = _toArray(_ref5), options = _ref6[0], fn = _ref6[1], args = _ref6.slice(2), _ref5), (_splice$call3 = splice.call(args, -1), _splice$call4 = _slicedToArray(_splice$call3, 1), cb = _splice$call4[0], _splice$call3); + options = parser.load(options, this.jobDefaults); + } - case '': - case '=': - case '==': - return eq(a, b, loose) + task = (...args) => { + return new this.Promise(function (resolve, reject) { + return fn(...args, function (...args) { + return (args[0] != null ? reject : resolve)(args); + }); + }); + }; - case '!=': - return neq(a, b, loose) + job = new Job(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise); + job.promise.then(function (args) { + return typeof cb === "function" ? cb(...args) : void 0; + }).catch(function (args) { + if (Array.isArray(args)) { + return typeof cb === "function" ? cb(...args) : void 0; + } else { + return typeof cb === "function" ? cb(args) : void 0; + } + }); + return this._receive(job); + } - case '>': - return gt(a, b, loose) + schedule(...args) { + var job, options, task; - case '>=': - return gte(a, b, loose) + if (typeof args[0] === "function") { + var _args = args; - case '<': - return lt(a, b, loose) + var _args2 = _toArray(_args); - case '<=': - return lte(a, b, loose) + task = _args2[0]; + args = _args2.slice(1); + options = {}; + } else { + var _args3 = args; - default: - throw new TypeError('Invalid operator: ' + op) - } -} + var _args4 = _toArray(_args3); -exports.Comparator = Comparator -function Comparator (comp, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } + options = _args4[0]; + task = _args4[1]; + args = _args4.slice(2); + } - if (comp instanceof Comparator) { - if (comp.loose === !!options.loose) { - return comp - } else { - comp = comp.value - } - } + job = new Job(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise); - if (!(this instanceof Comparator)) { - return new Comparator(comp, options) - } + this._receive(job); - debug('comparator', comp, options) - this.options = options - this.loose = !!options.loose - this.parse(comp) + return job.promise; + } - if (this.semver === ANY) { - this.value = '' - } else { - this.value = this.operator + this.semver.version - } + wrap(fn) { + var schedule, wrapped; + schedule = this.schedule.bind(this); - debug('comp', this) -} + wrapped = function wrapped(...args) { + return schedule(fn.bind(this), ...args); + }; -var ANY = {} -Comparator.prototype.parse = function (comp) { - var r = this.options.loose ? re[COMPARATORLOOSE] : re[COMPARATOR] - var m = comp.match(r) + wrapped.withOptions = function (options, ...args) { + return schedule(options, fn, ...args); + }; - if (!m) { - throw new TypeError('Invalid comparator: ' + comp) - } + return wrapped; + } - this.operator = m[1] - if (this.operator === '=') { - this.operator = '' - } + updateSettings(options = {}) { + var _this3 = this; - // if it literally is just '>' or '' then allow anything. - if (!m[2]) { - this.semver = ANY - } else { - this.semver = new SemVer(m[2], this.options.loose) - } -} + return _asyncToGenerator(function* () { + yield _this3._store.__updateSettings__(parser.overwrite(options, _this3.storeDefaults)); + parser.overwrite(options, _this3.instanceDefaults, _this3); + return _this3; + })(); + } -Comparator.prototype.toString = function () { - return this.value -} + currentReservoir() { + return this._store.__currentReservoir__(); + } -Comparator.prototype.test = function (version) { - debug('Comparator.test', version, this.options.loose) + incrementReservoir(incr = 0) { + return this._store.__incrementReservoir__(incr); + } - if (this.semver === ANY) { - return true } - if (typeof version === 'string') { - version = new SemVer(version, this.options) - } + ; + Bottleneck.default = Bottleneck; + Bottleneck.Events = Events; + Bottleneck.version = Bottleneck.prototype.version = __webpack_require__(507).version; + Bottleneck.strategy = Bottleneck.prototype.strategy = { + LEAK: 1, + OVERFLOW: 2, + OVERFLOW_PRIORITY: 4, + BLOCK: 3 + }; + Bottleneck.BottleneckError = Bottleneck.prototype.BottleneckError = __webpack_require__(212); + Bottleneck.Group = Bottleneck.prototype.Group = __webpack_require__(518); + Bottleneck.RedisConnection = Bottleneck.prototype.RedisConnection = __webpack_require__(688); + Bottleneck.IORedisConnection = Bottleneck.prototype.IORedisConnection = __webpack_require__(869); + Bottleneck.Batcher = Bottleneck.prototype.Batcher = __webpack_require__(379); + Bottleneck.prototype.jobDefaults = { + priority: DEFAULT_PRIORITY, + weight: 1, + expiration: null, + id: "" + }; + Bottleneck.prototype.storeDefaults = { + maxConcurrent: null, + minTime: 0, + highWater: null, + strategy: Bottleneck.prototype.strategy.LEAK, + penalty: null, + reservoir: null, + reservoirRefreshInterval: null, + reservoirRefreshAmount: null, + reservoirIncreaseInterval: null, + reservoirIncreaseAmount: null, + reservoirIncreaseMaximum: null + }; + Bottleneck.prototype.localStoreDefaults = { + Promise: Promise, + timeout: null, + heartbeatInterval: 250 + }; + Bottleneck.prototype.redisStoreDefaults = { + Promise: Promise, + timeout: null, + heartbeatInterval: 5000, + clientTimeout: 10000, + Redis: null, + clientOptions: {}, + clusterNodes: null, + clearDatastore: false, + connection: null + }; + Bottleneck.prototype.instanceDefaults = { + datastore: "local", + connection: null, + id: "", + rejectOnDrop: true, + trackDoneStatus: false, + Promise: Promise + }; + Bottleneck.prototype.stopDefaults = { + enqueueErrorMessage: "This limiter has been stopped and cannot accept new jobs.", + dropWaitingJobs: true, + dropErrorMessage: "This limiter has been stopped." + }; + return Bottleneck; +}.call(void 0); - return cmp(version, this.operator, this.semver, this.options) -} +module.exports = Bottleneck; -Comparator.prototype.intersects = function (comp, options) { - if (!(comp instanceof Comparator)) { - throw new TypeError('a Comparator is required') - } +/***/ }), +/* 325 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false +"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.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __generator = (this && this.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } - } +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +var dotenv = __importStar(__webpack_require__(63)); +dotenv.config(); +var express_1 = __importDefault(__webpack_require__(754)); +var build_body_1 = __importDefault(__webpack_require__(735)); +var rtd_1 = __importDefault(__webpack_require__(272)); +module.exports = function (app) { + app.on("pull_request", function (context) { return __awaiter(void 0, void 0, void 0, function () { + var log, token, rtd, config, project, head, files, branch, translates, disabled, enabled, body; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + log = context.log.child({ + name: "rtd-bot", + }); + token = process.env.RTD_TOKEN; + if (token == undefined) { + throw new Error('RTD_TOKEN is not set'); + } + rtd = new rtd_1.default(token); + return [4 /*yield*/, context.config("config.yml")]; + case 1: + config = _a.sent(); + if (config === null) { + context.github.issues.createComment(context.issue({ + body: "The rtd-bot is activated, but no .github/config.yml found in this repository.\n" + + "Make sure that you have it in your default branch.", + })); + return [2 /*return*/]; + } + if (config.rtd.project === "") { + context.github.issues.createComment(context.issue({ + body: "The rtd-bot is activated, but .github/config.yml does not have necessary configuration.\n" + + "Make sure that you have it in your default branch.", + })); + return [2 /*return*/]; + } + project = config.rtd.project; + head = context.payload.pull_request.head; + if (head.repo === null) { + log.debug("HEAD branch not found."); + } + else if (context.payload.pull_request.base.repo.full_name !== head.repo.full_name) { + log.debug("PR made from another Git repo is not supported."); + return [2 /*return*/]; + } + return [4 /*yield*/, context.github.paginate(context.github.pulls.listFiles, context.pullRequest({}))]; + case 2: + files = _a.sent(); + if (undefined === files.find(function (file) { return file.filename.startsWith('docs/'); })) { + log.debug("no need to build RTD document."); + return [2 /*return*/]; + } + branch = head.ref; + log.debug("Confirmed configuration of %s branch in %s: %s", branch, project, config); + return [4 /*yield*/, rtd.getTranslates(project)]; + case 3: + translates = _a.sent(); + if (!(context.payload.action === "closed")) return [3 /*break*/, 5]; + if (!branch) { + log.debug("HEAD branch not found, impossible to specify which RTD build should be disabled."); + return [2 /*return*/]; + } + return [4 /*yield*/, Promise.all(translates.map(function (p) { return p.slug; }).map(function (slug) { + return rtd.disableBuild(slug, branch); + })).then(function (allResult) { + return allResult.reduce(function (l, r) { return l || r; }); + }).catch(function (e) { + context.github.issues.createComment(context.issue({ + body: e.message, + })); + throw e; + })]; + case 4: + disabled = _a.sent(); + if (disabled) { + log.debug("Disabled RTD build for " + branch + " branch in " + project + "."); + } + else { + log.debug("RTD build for " + branch + " branch in " + project + " is already disabled."); + } + return [3 /*break*/, 8]; + case 5: + if (!(context.payload.pull_request.state === "closed")) return [3 /*break*/, 6]; + log.debug("The target pull request is already closed, no reaction needed."); + return [2 /*return*/]; + case 6: return [4 /*yield*/, Promise.all(translates.map(function (p) { return p.slug; }).map(function (slug) { + return rtd.enableBuild(slug, branch); + })).then(function (allResult) { + return allResult.reduce(function (l, r) { return l || r; }); + }).catch(function (e) { + context.github.issues.createComment(context.issue({ + body: e.message, + })); + throw e; + })]; + case 7: + enabled = _a.sent(); + if (enabled) { + log.debug("Reporting document URL to GitHub PR page of " + branch + " branch in " + project + "."); + body = build_body_1.default(context.payload.pull_request.body, project, branch, translates.map(function (t) { return t.language; })); + context.github.issues.update(context.issue({ + body: body, + })); + } + else { + log.debug("RTD build for " + branch + " branch in " + project + " is already activated."); + } + _a.label = 8; + case 8: return [2 /*return*/]; + } + }); + }); }); + var router = app.route("/welcome"); + router.get("/", function (req, res) { + res.sendFile(__dirname + "/welcome.html"); + }); + app.route("/static").use(express_1.default.static("asset")); +}; - var rangeTmp - if (this.operator === '') { - rangeTmp = new Range(comp.value, options) - return satisfies(this.value, rangeTmp, options) - } else if (comp.operator === '') { - rangeTmp = new Range(this.value, options) - return satisfies(comp.semver, rangeTmp, options) - } +/***/ }), +/* 326 */, +/* 327 */, +/* 328 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - var sameDirectionIncreasing = - (this.operator === '>=' || this.operator === '>') && - (comp.operator === '>=' || comp.operator === '>') - var sameDirectionDecreasing = - (this.operator === '<=' || this.operator === '<') && - (comp.operator === '<=' || comp.operator === '<') - var sameSemVer = this.semver.version === comp.semver.version - var differentDirectionsInclusive = - (this.operator === '>=' || this.operator === '<=') && - (comp.operator === '>=' || comp.operator === '<=') - var oppositeDirectionsLessThan = - cmp(this.semver, '<', comp.semver, options) && - ((this.operator === '>=' || this.operator === '>') && - (comp.operator === '<=' || comp.operator === '<')) - var oppositeDirectionsGreaterThan = - cmp(this.semver, '>', comp.semver, options) && - ((this.operator === '<=' || this.operator === '<') && - (comp.operator === '>=' || comp.operator === '>')) +"use strict"; - return sameDirectionIncreasing || sameDirectionDecreasing || - (sameSemVer && differentDirectionsInclusive) || - oppositeDirectionsLessThan || oppositeDirectionsGreaterThan -} -exports.Range = Range -function Range (range, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } - if (range instanceof Range) { - if (range.loose === !!options.loose && - range.includePrerelease === !!options.includePrerelease) { - return range - } else { - return new Range(range.raw, options) - } - } +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } - if (range instanceof Comparator) { - return new Range(range.value, options) +var DLList, Sync; +DLList = __webpack_require__(222); +Sync = class Sync { + constructor(name, Promise) { + this.schedule = this.schedule.bind(this); + this.name = name; + this.Promise = Promise; + this._running = 0; + this._queue = new DLList(); } - if (!(this instanceof Range)) { - return new Range(range, options) + isEmpty() { + return this._queue.length === 0; } - this.options = options - this.loose = !!options.loose - this.includePrerelease = !!options.includePrerelease + _tryToRun() { + var _this = this; - // First, split based on boolean or || - this.raw = range - this.set = range.split(/\s*\|\|\s*/).map(function (range) { - return this.parseRange(range.trim()) - }, this).filter(function (c) { - // throw out any that are not relevant for whatever reason - return c.length - }) + return _asyncToGenerator(function* () { + var args, cb, error, reject, resolve, returned, task; - if (!this.set.length) { - throw new TypeError('Invalid SemVer Range: ' + range) + if (_this._running < 1 && _this._queue.length > 0) { + _this._running++; + + var _this$_queue$shift = _this._queue.shift(); + + task = _this$_queue$shift.task; + args = _this$_queue$shift.args; + resolve = _this$_queue$shift.resolve; + reject = _this$_queue$shift.reject; + cb = yield _asyncToGenerator(function* () { + try { + returned = yield task(...args); + return function () { + return resolve(returned); + }; + } catch (error1) { + error = error1; + return function () { + return reject(error); + }; + } + })(); + _this._running--; + + _this._tryToRun(); + + return cb(); + } + })(); } - this.format() -} + schedule(task, ...args) { + var promise, reject, resolve; + resolve = reject = null; + promise = new this.Promise(function (_resolve, _reject) { + resolve = _resolve; + return reject = _reject; + }); -Range.prototype.format = function () { - this.range = this.set.map(function (comps) { - return comps.join(' ').trim() - }).join('||').trim() - return this.range -} + this._queue.push({ + task, + args, + resolve, + reject + }); -Range.prototype.toString = function () { - return this.range -} + this._tryToRun(); -Range.prototype.parseRange = function (range) { - var loose = this.options.loose - range = range.trim() - // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` - var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE] - range = range.replace(hr, hyphenReplace) - debug('hyphen replace', range) - // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` - range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace) - debug('comparator trim', range, re[COMPARATORTRIM]) + return promise; + } - // `~ 1.2.3` => `~1.2.3` - range = range.replace(re[TILDETRIM], tildeTrimReplace) +}; +module.exports = Sync; - // `^ 1.2.3` => `^1.2.3` - range = range.replace(re[CARETTRIM], caretTrimReplace) +/***/ }), +/* 329 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - // normalize spaces - range = range.split(/\s+/).join(' ') +"use strict"; - // At this point, the range is completely trimmed and - // ready to be split into comparators. - var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR] - var set = range.split(' ').map(function (comp) { - return parseComparator(comp, this.options) - }, this).join(' ').split(/\s+/) - if (this.options.loose) { - // in loose mode, throw out any that are not valid comparators - set = set.filter(function (comp) { - return !!comp.match(compRe) - }) - } - set = set.map(function (comp) { - return new Comparator(comp, this.options) - }, this) +var errSerializer = __webpack_require__(621) +var reqSerializers = __webpack_require__(307) +var resSerializers = __webpack_require__(578) - return set -} +module.exports = { + err: errSerializer, + mapHttpRequest: reqSerializers.mapHttpRequest, + mapHttpResponse: resSerializers.mapHttpResponse, + req: reqSerializers.reqSerializer, + res: resSerializers.resSerializer, -Range.prototype.intersects = function (range, options) { - if (!(range instanceof Range)) { - throw new TypeError('a Range is required') - } + wrapErrorSerializer: function wrapErrorSerializer (customSerializer) { + if (customSerializer === errSerializer) return customSerializer + return function wrapErrSerializer (err) { + return customSerializer(errSerializer(err)) + } + }, - return this.set.some(function (thisComparators) { - return thisComparators.every(function (thisComparator) { - return range.set.some(function (rangeComparators) { - return rangeComparators.every(function (rangeComparator) { - return thisComparator.intersects(rangeComparator, options) - }) - }) - }) - }) -} + wrapRequestSerializer: function wrapRequestSerializer (customSerializer) { + if (customSerializer === reqSerializers.reqSerializer) return customSerializer + return function wrappedReqSerializer (req) { + return customSerializer(reqSerializers.reqSerializer(req)) + } + }, -// Mostly just for testing and legacy API reasons -exports.toComparators = toComparators -function toComparators (range, options) { - return new Range(range, options).set.map(function (comp) { - return comp.map(function (c) { - return c.value - }).join(' ').trim().split(' ') - }) + wrapResponseSerializer: function wrapResponseSerializer (customSerializer) { + if (customSerializer === resSerializers.resSerializer) return customSerializer + return function wrappedResSerializer (res) { + return customSerializer(resSerializers.resSerializer(res)) + } + } } -// comprised of xranges, tildes, stars, and gtlt's at this point. -// already replaced the hyphen ranges -// turn into a set of JUST comparators. -function parseComparator (comp, options) { - debug('comp', comp, options) - comp = replaceCarets(comp, options) - debug('caret', comp) - comp = replaceTildes(comp, options) - debug('tildes', comp) - comp = replaceXRanges(comp, options) - debug('xrange', comp) - comp = replaceStars(comp, options) - debug('stars', comp) - return comp -} -function isX (id) { - return !id || id.toLowerCase() === 'x' || id === '*' -} +/***/ }), +/* 330 */, +/* 331 */ +/***/ (function(module, __unusedexports, __webpack_require__) { -// ~, ~> --> * (any, kinda silly) -// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 -// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 -// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 -// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 -// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 -function replaceTildes (comp, options) { - return comp.trim().split(/\s+/).map(function (comp) { - return replaceTilde(comp, options) - }).join(' ') -} +"use strict"; -function replaceTilde (comp, options) { - var r = options.loose ? re[TILDELOOSE] : re[TILDE] - return comp.replace(r, function (_, M, m, p, pr) { - debug('tilde', comp, _, M, m, p, pr) - var ret - if (isX(M)) { - ret = '' - } else if (isX(m)) { - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' - } else if (isX(p)) { - // ~1.2 == >=1.2.0 <1.3.0 - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' - } else if (pr) { - debug('replaceTilde pr', pr) - ret = '>=' + M + '.' + m + '.' + p + '-' + pr + - ' <' + M + '.' + (+m + 1) + '.0' - } else { - // ~1.2.3 == >=1.2.3 <1.3.0 - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + (+m + 1) + '.0' - } +const { version } = __webpack_require__(929) - debug('tilde return', ret) - return ret - }) -} +module.exports = { version } -// ^ --> * (any, kinda silly) -// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 -// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 -// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 -// ^1.2.3 --> >=1.2.3 <2.0.0 -// ^1.2.0 --> >=1.2.0 <2.0.0 -function replaceCarets (comp, options) { - return comp.trim().split(/\s+/).map(function (comp) { - return replaceCaret(comp, options) - }).join(' ') -} -function replaceCaret (comp, options) { - debug('caret', comp, options) - var r = options.loose ? re[CARETLOOSE] : re[CARET] - return comp.replace(r, function (_, M, m, p, pr) { - debug('caret', comp, _, M, m, p, pr) - var ret +/***/ }), +/* 332 */, +/* 333 */, +/* 334 */, +/* 335 */, +/* 336 */, +/* 337 */ +/***/ (function(__unusedmodule, exports) { - if (isX(M)) { - ret = '' - } else if (isX(m)) { - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' - } else if (isX(p)) { - if (M === '0') { - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' - } else { - ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0' - } - } else if (pr) { - debug('replaceCaret pr', pr) - if (M === '0') { - if (m === '0') { - ret = '>=' + M + '.' + m + '.' + p + '-' + pr + - ' <' + M + '.' + m + '.' + (+p + 1) - } else { - ret = '>=' + M + '.' + m + '.' + p + '-' + pr + - ' <' + M + '.' + (+m + 1) + '.0' - } - } else { - ret = '>=' + M + '.' + m + '.' + p + '-' + pr + - ' <' + (+M + 1) + '.0.0' - } - } else { - debug('no pr') - if (M === '0') { - if (m === '0') { - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + m + '.' + (+p + 1) - } else { - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + (+m + 1) + '.0' - } - } else { - ret = '>=' + M + '.' + m + '.' + p + - ' <' + (+M + 1) + '.0.0' - } - } +"use strict"; - debug('caret return', ret) - return ret - }) +Object.defineProperty(exports, "__esModule", { value: true }); +function isPromise(obj) { + return (!!obj && + (typeof obj === "object" || typeof obj === "function") && + typeof obj.then === "function"); } - -function replaceXRanges (comp, options) { - debug('replaceXRanges', comp, options) - return comp.split(/\s+/).map(function (comp) { - return replaceXRange(comp, options) - }).join(' ') +exports.isPromise = isPromise; +let promise = Promise; +function get() { + return promise; +} +exports.get = get; +function set(lib) { + if (typeof lib !== "function") { + throw new Error(`Provided Promise must be a function, got ${lib}`); + } + promise = lib; } +exports.set = set; -function replaceXRange (comp, options) { - comp = comp.trim() - var r = options.loose ? re[XRANGELOOSE] : re[XRANGE] - return comp.replace(r, function (ret, gtlt, M, m, p, pr) { - debug('xRange', comp, ret, gtlt, M, m, p, pr) - var xM = isX(M) - var xm = xM || isX(m) - var xp = xm || isX(p) - var anyX = xp - if (gtlt === '=' && anyX) { - gtlt = '' - } +/***/ }), +/* 338 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - if (xM) { - if (gtlt === '>' || gtlt === '<') { - // nothing is allowed - ret = '<0.0.0' - } else { - // nothing is forbidden - ret = '*' - } - } else if (gtlt && anyX) { - // we know patch is an x, because we have any x at all. - // replace X with 0 - if (xm) { - m = 0 - } - p = 0 +"use strict"; - if (gtlt === '>') { - // >1 => >=2.0.0 - // >1.2 => >=1.3.0 - // >1.2.3 => >= 1.2.4 - gtlt = '>=' - if (xm) { - M = +M + 1 - m = 0 - p = 0 - } else { - m = +m + 1 - p = 0 - } - } else if (gtlt === '<=') { - // <=0.7.x is actually <0.8.0, since any 0.7.x should - // pass. Similarly, <=7.x is actually <8.0.0, etc. - gtlt = '<' - if (xm) { - M = +M + 1 - } else { - m = +m + 1 - } - } +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +const agent_1 = __importDefault(__webpack_require__(40)); +function createHttpsProxyAgent(opts) { + return new agent_1.default(opts); +} +(function (createHttpsProxyAgent) { + createHttpsProxyAgent.HttpsProxyAgent = agent_1.default; + createHttpsProxyAgent.prototype = agent_1.default.prototype; +})(createHttpsProxyAgent || (createHttpsProxyAgent = {})); +module.exports = createHttpsProxyAgent; +//# sourceMappingURL=index.js.map - ret = gtlt + M + '.' + m + '.' + p - } else if (xm) { - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' - } else if (xp) { - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' - } +/***/ }), +/* 339 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - debug('xRange return', ret) +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. - return ret - }) -} -// Because * is AND-ed with everything else in the comparator, -// and '' means "any version", just remove the *s entirely. -function replaceStars (comp, options) { - debug('replaceStars', comp, options) - // Looseness is ignored here. star is always as loose as it gets! - return comp.trim().replace(re[STAR], '') -} +module.exports = Transform; -// This function is passed to string.replace(re[HYPHENRANGE]) -// M, m, patch, prerelease, build -// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 -// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do -// 1.2 - 3.4 => >=1.2.0 <3.5.0 -function hyphenReplace ($0, - from, fM, fm, fp, fpr, fb, - to, tM, tm, tp, tpr, tb) { - if (isX(fM)) { - from = '' - } else if (isX(fm)) { - from = '>=' + fM + '.0.0' - } else if (isX(fp)) { - from = '>=' + fM + '.' + fm + '.0' - } else { - from = '>=' + from - } +var _require$codes = __webpack_require__(954).codes, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, + ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; - if (isX(tM)) { - to = '' - } else if (isX(tm)) { - to = '<' + (+tM + 1) + '.0.0' - } else if (isX(tp)) { - to = '<' + tM + '.' + (+tm + 1) + '.0' - } else if (tpr) { - to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr - } else { - to = '<=' + to - } +var Duplex = __webpack_require__(238); - return (from + ' ' + to).trim() -} +__webpack_require__(689)(Transform, Duplex); -// if ANY of the sets match ALL of its comparators, then pass -Range.prototype.test = function (version) { - if (!version) { - return false - } +function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; + var cb = ts.writecb; - if (typeof version === 'string') { - version = new SemVer(version, this.options) + if (cb === null) { + return this.emit('error', new ERR_MULTIPLE_CALLBACK()); } - for (var i = 0; i < this.set.length; i++) { - if (testSet(this.set[i], version, this.options)) { - return true - } + ts.writechunk = null; + ts.writecb = null; + if (data != null) // single equals check for both `null` and `undefined` + this.push(data); + cb(er); + var rs = this._readableState; + rs.reading = false; + + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); } - return false } -function testSet (set, version, options) { - for (var i = 0; i < set.length; i++) { - if (!set[i].test(version)) { - return false - } - } +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + Duplex.call(this, options); + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; // start out asking for a readable event once data is transformed. - if (version.prerelease.length && !options.includePrerelease) { - // Find the set of versions that are allowed to have prereleases - // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 - // That should allow `1.2.3-pr.2` to pass. - // However, `1.2.4-alpha.notready` should NOT be allowed, - // even though it's within the range set by the comparators. - for (i = 0; i < set.length; i++) { - debug(set[i].semver) - if (set[i].semver === ANY) { - continue - } + this._readableState.needReadable = true; // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. - if (set[i].semver.prerelease.length > 0) { - var allowed = set[i].semver - if (allowed.major === version.major && - allowed.minor === version.minor && - allowed.patch === version.patch) { - return true - } - } - } + this._readableState.sync = false; - // Version has a -pre, but it's not one of the ones we like. - return false - } + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + if (typeof options.flush === 'function') this._flush = options.flush; + } // When the writable side finishes, then flush out anything remaining. - return true -} -exports.satisfies = satisfies -function satisfies (version, range, options) { - try { - range = new Range(range, options) - } catch (er) { - return false - } - return range.test(version) + this.on('prefinish', prefinish); } -exports.maxSatisfying = maxSatisfying -function maxSatisfying (versions, range, options) { - var max = null - var maxSV = null - try { - var rangeObj = new Range(range, options) - } catch (er) { - return null - } - versions.forEach(function (v) { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!max || maxSV.compare(v) === -1) { - // compare(max, v, true) - max = v - maxSV = new SemVer(max, options) - } - } - }) - return max -} +function prefinish() { + var _this = this; -exports.minSatisfying = minSatisfying -function minSatisfying (versions, range, options) { - var min = null - var minSV = null - try { - var rangeObj = new Range(range, options) - } catch (er) { - return null + if (typeof this._flush === 'function' && !this._readableState.destroyed) { + this._flush(function (er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); } - versions.forEach(function (v) { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!min || minSV.compare(v) === 1) { - // compare(min, v, true) - min = v - minSV = new SemVer(min, options) - } - } - }) - return min } -exports.minVersion = minVersion -function minVersion (range, loose) { - range = new Range(range, loose) +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; // This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. - var minver = new SemVer('0.0.0') - if (range.test(minver)) { - return minver - } - minver = new SemVer('0.0.0-0') - if (range.test(minver)) { - return minver +Transform.prototype._transform = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); +}; + +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); } +}; // Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. - minver = null - for (var i = 0; i < range.set.length; ++i) { - var comparators = range.set[i] - comparators.forEach(function (comparator) { - // Clone to avoid manipulating the comparator's semver object. - var compver = new SemVer(comparator.semver.version) - switch (comparator.operator) { - case '>': - if (compver.prerelease.length === 0) { - compver.patch++ - } else { - compver.prerelease.push(0) - } - compver.raw = compver.format() - /* fallthrough */ - case '': - case '>=': - if (!minver || gt(minver, compver)) { - minver = compver - } - break - case '<': - case '<=': - /* Ignore maximum versions */ - break - /* istanbul ignore next */ - default: - throw new Error('Unexpected operation: ' + comparator.operator) - } - }) - } +Transform.prototype._read = function (n) { + var ts = this._transformState; - if (minver && range.test(minver)) { - return minver + if (ts.writechunk !== null && !ts.transforming) { + ts.transforming = true; + + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; } +}; - return null -} +Transform.prototype._destroy = function (err, cb) { + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + }); +}; -exports.validRange = validRange -function validRange (range, options) { - try { - // Return '*' instead of '' so that truthiness works. - // This will throw if it's invalid anyway - return new Range(range, options).range || '*' - } catch (er) { - return null - } -} +function done(stream, er, data) { + if (er) return stream.emit('error', er); + if (data != null) // single equals check for both `null` and `undefined` + stream.push(data); // TODO(BridgeAR): Write a test for these two error cases + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided -// Determine if version is less than all the versions possible in the range -exports.ltr = ltr -function ltr (version, range, options) { - return outside(version, range, '<', options) + if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); + if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); + return stream.push(null); } -// Determine if version is greater than all the versions possible in the range. -exports.gtr = gtr -function gtr (version, range, options) { - return outside(version, range, '>', options) -} +/***/ }), +/* 340 */ +/***/ (function(module, __unusedexports, __webpack_require__) { -exports.outside = outside -function outside (version, range, hilo, options) { - version = new SemVer(version, options) - range = new Range(range, options) +"use strict"; - var gtfn, ltefn, ltfn, comp, ecomp - switch (hilo) { - case '>': - gtfn = gt - ltefn = lte - ltfn = lt - comp = '>' - ecomp = '>=' - break - case '<': - gtfn = lt - ltefn = gte - ltfn = gt - comp = '<' - ecomp = '<=' - break - default: - throw new TypeError('Must provide a hilo val of "<" or ">"') - } - // If it satisifes the range it is not outside - if (satisfies(version, range, options)) { - return false +const Buffer = __webpack_require__(293).Buffer +const StringDecoder = __webpack_require__(304).StringDecoder +const decoder = new StringDecoder() +const errors = __webpack_require__(400) +const ReplyError = errors.ReplyError +const ParserError = errors.ParserError +var bufferPool = Buffer.allocUnsafe(32 * 1024) +var bufferOffset = 0 +var interval = null +var counter = 0 +var notDecreased = 0 + +/** + * Used for integer numbers only + * @param {JavascriptRedisParser} parser + * @returns {undefined|number} + */ +function parseSimpleNumbers (parser) { + const length = parser.buffer.length - 1 + var offset = parser.offset + var number = 0 + var sign = 1 + + if (parser.buffer[offset] === 45) { + sign = -1 + offset++ } - // From now on, variable terms are as if we're in "gtr" mode. - // but note that everything is flipped for the "ltr" function. + while (offset < length) { + const c1 = parser.buffer[offset++] + if (c1 === 13) { // \r\n + parser.offset = offset + 1 + return sign * number + } + number = (number * 10) + (c1 - 48) + } +} - for (var i = 0; i < range.set.length; ++i) { - var comparators = range.set[i] +/** + * Used for integer numbers in case of the returnNumbers option + * + * Reading the string as parts of n SMI is more efficient than + * using a string directly. + * + * @param {JavascriptRedisParser} parser + * @returns {undefined|string} + */ +function parseStringNumbers (parser) { + const length = parser.buffer.length - 1 + var offset = parser.offset + var number = 0 + var res = '' - var high = null - var low = null + if (parser.buffer[offset] === 45) { + res += '-' + offset++ + } - comparators.forEach(function (comparator) { - if (comparator.semver === ANY) { - comparator = new Comparator('>=0.0.0') - } - high = high || comparator - low = low || comparator - if (gtfn(comparator.semver, high.semver, options)) { - high = comparator - } else if (ltfn(comparator.semver, low.semver, options)) { - low = comparator + while (offset < length) { + var c1 = parser.buffer[offset++] + if (c1 === 13) { // \r\n + parser.offset = offset + 1 + if (number !== 0) { + res += number } - }) - - // If the edge version comparator has a operator then our version - // isn't outside it - if (high.operator === comp || high.operator === ecomp) { - return false + return res + } else if (number > 429496728) { + res += (number * 10) + (c1 - 48) + number = 0 + } else if (c1 === 48 && number === 0) { + res += 0 + } else { + number = (number * 10) + (c1 - 48) } + } +} - // If the lowest version comparator has an operator and our version - // is less than it then it isn't higher than the range - if ((!low.operator || low.operator === comp) && - ltefn(version, low.semver)) { - return false - } else if (low.operator === ecomp && ltfn(version, low.semver)) { - return false +/** + * Parse a '+' redis simple string response but forward the offsets + * onto convertBufferRange to generate a string. + * @param {JavascriptRedisParser} parser + * @returns {undefined|string|Buffer} + */ +function parseSimpleString (parser) { + const start = parser.offset + const buffer = parser.buffer + const length = buffer.length - 1 + var offset = start + + while (offset < length) { + if (buffer[offset++] === 13) { // \r\n + parser.offset = offset + 1 + if (parser.optionReturnBuffers === true) { + return parser.buffer.slice(start, offset - 1) + } + return parser.buffer.toString('utf8', start, offset - 1) } } - return true } -exports.prerelease = prerelease -function prerelease (version, options) { - var parsed = parse(version, options) - return (parsed && parsed.prerelease.length) ? parsed.prerelease : null -} +/** + * Returns the read length + * @param {JavascriptRedisParser} parser + * @returns {undefined|number} + */ +function parseLength (parser) { + const length = parser.buffer.length - 1 + var offset = parser.offset + var number = 0 -exports.intersects = intersects -function intersects (r1, r2, options) { - r1 = new Range(r1, options) - r2 = new Range(r2, options) - return r1.intersects(r2) + while (offset < length) { + const c1 = parser.buffer[offset++] + if (c1 === 13) { + parser.offset = offset + 1 + return number + } + number = (number * 10) + (c1 - 48) + } } -exports.coerce = coerce -function coerce (version) { - if (version instanceof SemVer) { - return version +/** + * Parse a ':' redis integer response + * + * If stringNumbers is activated the parser always returns numbers as string + * This is important for big numbers (number > Math.pow(2, 53)) as js numbers + * are 64bit floating point numbers with reduced precision + * + * @param {JavascriptRedisParser} parser + * @returns {undefined|number|string} + */ +function parseInteger (parser) { + if (parser.optionStringNumbers === true) { + return parseStringNumbers(parser) } + return parseSimpleNumbers(parser) +} - if (typeof version !== 'string') { +/** + * Parse a '$' redis bulk string response + * @param {JavascriptRedisParser} parser + * @returns {undefined|null|string} + */ +function parseBulkString (parser) { + const length = parseLength(parser) + if (length === undefined) { + return + } + if (length < 0) { return null } + const offset = parser.offset + length + if (offset + 2 > parser.buffer.length) { + parser.bigStrSize = offset + 2 + parser.totalChunkSize = parser.buffer.length + parser.bufferCache.push(parser.buffer) + return + } + const start = parser.offset + parser.offset = offset + 2 + if (parser.optionReturnBuffers === true) { + return parser.buffer.slice(start, offset) + } + return parser.buffer.toString('utf8', start, offset) +} - var match = version.match(re[COERCE]) - - if (match == null) { - return null +/** + * Parse a '-' redis error response + * @param {JavascriptRedisParser} parser + * @returns {ReplyError} + */ +function parseError (parser) { + var string = parseSimpleString(parser) + if (string !== undefined) { + if (parser.optionReturnBuffers === true) { + string = string.toString() + } + return new ReplyError(string) } +} - return parse(match[1] + - '.' + (match[2] || '0') + - '.' + (match[3] || '0')) +/** + * Parsing error handler, resets parser buffer + * @param {JavascriptRedisParser} parser + * @param {number} type + * @returns {undefined} + */ +function handleError (parser, type) { + const err = new ParserError( + 'Protocol error, got ' + JSON.stringify(String.fromCharCode(type)) + ' as reply type byte', + JSON.stringify(parser.buffer), + parser.offset + ) + parser.buffer = null + parser.returnFatalError(err) } +/** + * Parse a '*' redis array response + * @param {JavascriptRedisParser} parser + * @returns {undefined|null|any[]} + */ +function parseArray (parser) { + const length = parseLength(parser) + if (length === undefined) { + return + } + if (length < 0) { + return null + } + const responses = new Array(length) + return parseArrayElements(parser, responses, 0) +} -/***/ }), -/* 281 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { +/** + * Push a partly parsed array to the stack + * + * @param {JavascriptRedisParser} parser + * @param {any[]} array + * @param {number} pos + * @returns {undefined} + */ +function pushArrayCache (parser, array, pos) { + parser.arrayCache.push(array) + parser.arrayPos.push(pos) +} -"use strict"; +/** + * Parse chunked redis array response + * @param {JavascriptRedisParser} parser + * @returns {undefined|any[]} + */ +function parseArrayChunks (parser) { + const tmp = parser.arrayCache.pop() + var pos = parser.arrayPos.pop() + if (parser.arrayCache.length) { + const res = parseArrayChunks(parser) + if (res === undefined) { + pushArrayCache(parser, tmp, pos) + return + } + tmp[pos++] = res + } + return parseArrayElements(parser, tmp, pos) +} +/** + * Parse redis array response elements + * @param {JavascriptRedisParser} parser + * @param {Array} responses + * @param {number} i + * @returns {undefined|null|any[]} + */ +function parseArrayElements (parser, responses, i) { + const bufferLength = parser.buffer.length + while (i < responses.length) { + const offset = parser.offset + if (parser.offset >= bufferLength) { + pushArrayCache(parser, responses, i) + return + } + const response = parseType(parser, parser.buffer[parser.offset++]) + if (response === undefined) { + if (!(parser.arrayCache.length || parser.bufferCache.length)) { + parser.offset = offset + } + pushArrayCache(parser, responses, i) + return + } + responses[i] = response + i++ + } -var commands = __webpack_require__(433) + return responses +} /** - * Redis command list + * Called the appropriate parser for the specified type. * - * All commands are lowercased. + * 36: $ + * 43: + + * 42: * + * 58: : + * 45: - * - * @var {string[]} - * @public + * @param {JavascriptRedisParser} parser + * @param {number} type + * @returns {*} */ -exports.list = Object.keys(commands) +function parseType (parser, type) { + switch (type) { + case 36: + return parseBulkString(parser) + case 43: + return parseSimpleString(parser) + case 42: + return parseArray(parser) + case 58: + return parseInteger(parser) + case 45: + return parseError(parser) + default: + return handleError(parser, type) + } +} -var flags = {} -exports.list.forEach(function (commandName) { - flags[commandName] = commands[commandName].flags.reduce(function (flags, flag) { - flags[flag] = true - return flags - }, {}) -}) /** - * Check if the command exists + * Decrease the bufferPool size over time * - * @param {string} commandName - the command name - * @return {boolean} result - * @public + * Balance between increasing and decreasing the bufferPool. + * Decrease the bufferPool by 10% by removing the first 10% of the current pool. + * @returns {undefined} */ -exports.exists = function (commandName) { - return Boolean(commands[commandName]) +function decreaseBufferPool () { + if (bufferPool.length > 50 * 1024) { + if (counter === 1 || notDecreased > counter * 2) { + const minSliceLen = Math.floor(bufferPool.length / 10) + const sliceLength = minSliceLen < bufferOffset + ? bufferOffset + : minSliceLen + bufferOffset = 0 + bufferPool = bufferPool.slice(sliceLength, bufferPool.length) + } else { + notDecreased++ + counter-- + } + } else { + clearInterval(interval) + counter = 0 + notDecreased = 0 + interval = null + } } /** - * Check if the command has the flag + * Check if the requested size fits in the current bufferPool. + * If it does not, reset and increase the bufferPool accordingly. * - * Some of possible flags: readonly, noscript, loading - * @param {string} commandName - the command name - * @param {string} flag - the flag to check - * @return {boolean} result - * @public + * @param {number} length + * @returns {undefined} */ -exports.hasFlag = function (commandName, flag) { - if (!flags[commandName]) { - throw new Error('Unknown command ' + commandName) +function resizeBuffer (length) { + if (bufferPool.length < length + bufferOffset) { + const multiplier = length > 1024 * 1024 * 75 ? 2 : 3 + if (bufferOffset > 1024 * 1024 * 111) { + bufferOffset = 1024 * 1024 * 50 + } + bufferPool = Buffer.allocUnsafe(length * multiplier + bufferOffset) + bufferOffset = 0 + counter++ + if (interval === null) { + interval = setInterval(decreaseBufferPool, 50) + } } - - return Boolean(flags[commandName][flag]) } /** - * Get indexes of keys in the command arguments + * Concat a bulk string containing multiple chunks * - * @param {string} commandName - the command name - * @param {string[]} args - the arguments of the command - * @param {object} [options] - options - * @param {boolean} [options.parseExternalKey] - parse external keys - * @return {number[]} - the list of the index - * @public + * Notes: + * 1) The first chunk might contain the whole bulk string including the \r + * 2) We are only safe to fully add up elements that are neither the first nor any of the last two elements * - * @example - * ```javascript - * getKeyIndexes('set', ['key', 'value']) // [0] - * getKeyIndexes('mget', ['key1', 'key2']) // [0, 1] - * ``` + * @param {JavascriptRedisParser} parser + * @returns {String} */ -exports.getKeyIndexes = function (commandName, args, options) { - var command = commands[commandName] - if (!command) { - throw new Error('Unknown command ' + commandName) +function concatBulkString (parser) { + const list = parser.bufferCache + const oldOffset = parser.offset + var chunks = list.length + var offset = parser.bigStrSize - parser.totalChunkSize + parser.offset = offset + if (offset <= 2) { + if (chunks === 2) { + return list[0].toString('utf8', oldOffset, list[0].length + offset - 2) + } + chunks-- + offset = list[list.length - 2].length + offset } + var res = decoder.write(list[0].slice(oldOffset)) + for (var i = 1; i < chunks - 1; i++) { + res += decoder.write(list[i]) + } + res += decoder.end(list[i].slice(0, offset - 2)) + return res +} - if (!Array.isArray(args)) { - throw new Error('Expect args to be an array') +/** + * Concat the collected chunks from parser.bufferCache. + * + * Increases the bufferPool size beforehand if necessary. + * + * @param {JavascriptRedisParser} parser + * @returns {Buffer} + */ +function concatBulkBuffer (parser) { + const list = parser.bufferCache + const oldOffset = parser.offset + const length = parser.bigStrSize - oldOffset - 2 + var chunks = list.length + var offset = parser.bigStrSize - parser.totalChunkSize + parser.offset = offset + if (offset <= 2) { + if (chunks === 2) { + return list[0].slice(oldOffset, list[0].length + offset - 2) + } + chunks-- + offset = list[list.length - 2].length + offset + } + resizeBuffer(length) + const start = bufferOffset + list[0].copy(bufferPool, start, oldOffset, list[0].length) + bufferOffset += list[0].length - oldOffset + for (var i = 1; i < chunks - 1; i++) { + list[i].copy(bufferPool, bufferOffset) + bufferOffset += list[i].length } + list[i].copy(bufferPool, bufferOffset, 0, offset - 2) + bufferOffset += offset - 2 + return bufferPool.slice(start, bufferOffset) +} - var keys = [] - var i, keyStart, keyStop, parseExternalKey - switch (commandName) { - case 'zunionstore': - case 'zinterstore': - keys.push(0) - // fall through - case 'eval': - case 'evalsha': - keyStop = Number(args[1]) + 2 - for (i = 2; i < keyStop; i++) { - keys.push(i) - } - break - case 'sort': - parseExternalKey = options && options.parseExternalKey - keys.push(0) - for (i = 1; i < args.length - 1; i++) { - if (typeof args[i] !== 'string') { - continue - } - var directive = args[i].toUpperCase() - if (directive === 'GET') { - i += 1 - if (args[i] !== '#') { - if (parseExternalKey) { - keys.push([i, getExternalKeyNameLength(args[i])]) - } else { - keys.push(i) - } - } - } else if (directive === 'BY') { - i += 1 - if (parseExternalKey) { - keys.push([i, getExternalKeyNameLength(args[i])]) - } else { - keys.push(i) - } - } else if (directive === 'STORE') { - i += 1 - keys.push(i) - } - } - break - case 'migrate': - if (args[2] === '') { - for (i = 5; i < args.length - 1; i++) { - if (args[i].toUpperCase() === 'KEYS') { - for (var j = i + 1; j < args.length; j++) { - keys.push(j) - } - break - } +class JavascriptRedisParser { + /** + * Javascript Redis Parser constructor + * @param {{returnError: Function, returnReply: Function, returnFatalError?: Function, returnBuffers: boolean, stringNumbers: boolean }} options + * @constructor + */ + constructor (options) { + if (!options) { + throw new TypeError('Options are mandatory.') + } + if (typeof options.returnError !== 'function' || typeof options.returnReply !== 'function') { + throw new TypeError('The returnReply and returnError options have to be functions.') + } + this.setReturnBuffers(!!options.returnBuffers) + this.setStringNumbers(!!options.stringNumbers) + this.returnError = options.returnError + this.returnFatalError = options.returnFatalError || options.returnError + this.returnReply = options.returnReply + this.reset() + } + + /** + * Reset the parser values to the initial state + * + * @returns {undefined} + */ + reset () { + this.offset = 0 + this.buffer = null + this.bigStrSize = 0 + this.totalChunkSize = 0 + this.bufferCache = [] + this.arrayCache = [] + this.arrayPos = [] + } + + /** + * Set the returnBuffers option + * + * @param {boolean} returnBuffers + * @returns {undefined} + */ + setReturnBuffers (returnBuffers) { + if (typeof returnBuffers !== 'boolean') { + throw new TypeError('The returnBuffers argument has to be a boolean') + } + this.optionReturnBuffers = returnBuffers + } + + /** + * Set the stringNumbers option + * + * @param {boolean} stringNumbers + * @returns {undefined} + */ + setStringNumbers (stringNumbers) { + if (typeof stringNumbers !== 'boolean') { + throw new TypeError('The stringNumbers argument has to be a boolean') + } + this.optionStringNumbers = stringNumbers + } + + /** + * Parse the redis buffer + * @param {Buffer} buffer + * @returns {undefined} + */ + execute (buffer) { + if (this.buffer === null) { + this.buffer = buffer + this.offset = 0 + } else if (this.bigStrSize === 0) { + const oldLength = this.buffer.length + const remainingLength = oldLength - this.offset + const newBuffer = Buffer.allocUnsafe(remainingLength + buffer.length) + this.buffer.copy(newBuffer, 0, this.offset, oldLength) + buffer.copy(newBuffer, remainingLength, 0, buffer.length) + this.buffer = newBuffer + this.offset = 0 + if (this.arrayCache.length) { + const arr = parseArrayChunks(this) + if (arr === undefined) { + return } - } else { - keys.push(2) + this.returnReply(arr) } - break - case 'xreadgroup': - case 'xread': - // Keys are 1st half of the args after STREAMS argument. - for (i = commandName === 'xread' ? 0 : 3; i < args.length - 1; i++) { - if (String(args[i]).toUpperCase() === 'STREAMS') { - for (j = i + 1; j <= i + ((args.length - 1 - i) / 2); j++) { - keys.push(j) - } - break + } else if (this.totalChunkSize + buffer.length >= this.bigStrSize) { + this.bufferCache.push(buffer) + var tmp = this.optionReturnBuffers ? concatBulkBuffer(this) : concatBulkString(this) + this.bigStrSize = 0 + this.bufferCache = [] + this.buffer = buffer + if (this.arrayCache.length) { + this.arrayCache[0][this.arrayPos[0]++] = tmp + tmp = parseArrayChunks(this) + if (tmp === undefined) { + return } } - break - default: - // Step has to be at least one in this case, otherwise the command does - // not contain a key. - if (command.step > 0) { - keyStart = command.keyStart - 1 - keyStop = command.keyStop > 0 ? command.keyStop : args.length + command.keyStop + 1 - for (i = keyStart; i < keyStop; i += command.step) { - keys.push(i) + this.returnReply(tmp) + } else { + this.bufferCache.push(buffer) + this.totalChunkSize += buffer.length + return + } + + while (this.offset < this.buffer.length) { + const offset = this.offset + const type = this.buffer[this.offset++] + const response = parseType(this, type) + if (response === undefined) { + if (!(this.arrayCache.length || this.bufferCache.length)) { + this.offset = offset } + return } - break - } - return keys -} + if (type === 45) { + this.returnError(response) + } else { + this.returnReply(response) + } + } -function getExternalKeyNameLength (key) { - if (typeof key !== 'string') { - key = String(key) + this.buffer = null } - var hashPos = key.indexOf('->') - return hashPos === -1 ? key.length : hashPos } +module.exports = JavascriptRedisParser -/***/ }), -/* 282 */ -/***/ (function(module) { - -module.exports = require("module"); /***/ }), -/* 283 */ -/***/ (function(module) { +/* 341 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; -/*! - * vary - * Copyright(c) 2014-2017 Douglas Christopher Wilson - * MIT Licensed - */ - +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.setupAppFactory = void 0; +const body_parser_1 = __importDefault(__webpack_require__(420)); +const child_process_1 = __webpack_require__(129); +const update_dotenv_1 = __importDefault(__webpack_require__(836)); +const manifest_creation_1 = __webpack_require__(174); +const logging_middleware_1 = __webpack_require__(14); +exports.setupAppFactory = (host, port) => async function setupApp(app) { + const setup = new manifest_creation_1.ManifestCreation(); + // If not on Glitch or Production, create a smee URL + if (process.env.NODE_ENV !== "production" && + !(process.env.PROJECT_DOMAIN || process.env.WEBHOOK_PROXY_URL)) { + await setup.createWebhookChannel(); + } + const route = app.route(); + route.use(logging_middleware_1.getLoggingMiddleware(app.log)); + printWelcomeMessage(app, host, port); + route.get("/probot", async (req, res) => { + const baseUrl = getBaseUrl(req); + const pkg = setup.pkg; + const manifest = setup.getManifest(pkg, baseUrl); + const createAppUrl = setup.createAppUrl; + // Pass the manifest to be POST'd + res.render("setup.hbs", { pkg, createAppUrl, manifest }); + }); + route.get("/probot/setup", async (req, res) => { + const { code } = req.query; + const response = await setup.createAppFromCode(code); + // If using glitch, restart the app + if (process.env.PROJECT_DOMAIN) { + child_process_1.exec("refresh", (error) => { + if (error) { + app.log.error(error); + } + }); + } + res.redirect(`${response}/installations/new`); + }); + route.get("/probot/import", async (_req, res) => { + const { WEBHOOK_PROXY_URL, GHE_HOST } = process.env; + const GH_HOST = `https://${GHE_HOST !== null && GHE_HOST !== void 0 ? GHE_HOST : "github.com"}`; + res.render("import.hbs", { WEBHOOK_PROXY_URL, GH_HOST }); + }); + route.post("/probot/import", body_parser_1.default.json(), async (req, res) => { + const { appId, pem, webhook_secret } = req.body; + if (!appId || !pem || !webhook_secret) { + res.status(400).send("appId and/or pem and/or webhook_secret missing"); + return; + } + update_dotenv_1.default({ + APP_ID: appId, + PRIVATE_KEY: `"${pem}"`, + WEBHOOK_SECRET: webhook_secret, + }); + res.end(); + }); + route.get("/probot/success", async (req, res) => { + res.render("success.hbs"); + }); + route.get("/", (req, res, next) => res.redirect("/probot")); +}; +function printWelcomeMessage(app, host, port) { + // use glitch env to get correct domain welcome message + // https://glitch.com/help/project/ + const domain = process.env.PROJECT_DOMAIN || + `http://${host !== null && host !== void 0 ? host : "localhost"}:${port || 3000}`; + [ + ``, + `Welcome to Probot!`, + `Probot is in setup mode, webhooks cannot be received and`, + `custom routes will not work until APP_ID and PRIVATE_KEY`, + `are configured in .env.`, + `Please follow the instructions at ${domain} to configure .env.`, + `Once you are done, restart the server.`, + ``, + ].forEach((line) => { + app.log.info(line); + }); +} +function getBaseUrl(req) { + const protocols = req.headers["x-forwarded-proto"] || req.protocol; + const protocol = typeof protocols === "string" ? protocols.split(",")[0] : protocols[0]; + const host = req.headers["x-forwarded-host"] || req.get("host"); + const baseUrl = `${protocol}://${host}`; + return baseUrl; +} +//# sourceMappingURL=setup.js.map -/** - * Module exports. - */ +/***/ }), +/* 342 */, +/* 343 */ +/***/ (function(module, __unusedexports, __webpack_require__) { -module.exports = vary -module.exports.append = append +module.exports = __webpack_require__(413); -/** - * RegExp to match field-name in RFC 7230 sec 3.2 - * - * field-name = token - * token = 1*tchar - * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" - * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" - * / DIGIT / ALPHA - * ; any VCHAR, except delimiters - */ -var FIELD_NAME_REGEXP = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/ +/***/ }), +/* 344 */, +/* 345 */ +/***/ (function(module) { /** - * Append a field to a vary header. - * - * @param {String} header - * @param {String|Array} field - * @return {String} - * @public + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors */ -function append (header, field) { - if (typeof header !== 'string') { - throw new TypeError('header argument is required') - } - - if (!field) { - throw new TypeError('field argument is required') - } - - // get fields array - var fields = !Array.isArray(field) - ? parse(String(field)) - : field - - // assert on invalid field names - for (var j = 0; j < fields.length; j++) { - if (!FIELD_NAME_REGEXP.test(fields[j])) { - throw new TypeError('field argument contains an invalid header name') - } - } - - // existing, unspecified vary - if (header === '*') { - return header - } - - // enumerate current values - var val = header - var vals = parse(header.toLowerCase()) +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; - // unspecified vary - if (fields.indexOf('*') !== -1 || vals.indexOf('*') !== -1) { - return '*' - } +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]'; - for (var i = 0; i < fields.length; i++) { - var fld = fields[i].toLowerCase() +/** Detect free variable `global` from Node.js. */ +var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; - // append value (case-preserving) - if (vals.indexOf(fld) === -1) { - vals.push(fld) - val = val - ? val + ', ' + fields[i] - : fields[i] - } - } +/** Detect free variable `self`. */ +var freeSelf = typeof self == 'object' && self && self.Object === Object && self; - return val -} +/** Used as a reference to the global object. */ +var root = freeGlobal || freeSelf || Function('return this')(); /** - * Parse a vary header into an array. + * Appends the elements of `values` to `array`. * - * @param {String} header - * @return {Array} * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. */ +function arrayPush(array, values) { + var index = -1, + length = values.length, + offset = array.length; -function parse (header) { - var end = 0 - var list = [] - var start = 0 - - // gather tokens - for (var i = 0, len = header.length; i < len; i++) { - switch (header.charCodeAt(i)) { - case 0x20: /* */ - if (start === end) { - start = end = i + 1 - } - break - case 0x2c: /* , */ - list.push(header.substring(start, end)) - start = end = i + 1 - break - default: - end = i + 1 - break - } + while (++index < length) { + array[offset + index] = values[index]; } + return array; +} - // final token - list.push(header.substring(start, end)) +/** Used for built-in method references. */ +var objectProto = Object.prototype; - return list -} +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; /** - * Mark that a request is varied on a header field. - * - * @param {Object} res - * @param {String|Array} field - * @public + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. */ +var objectToString = objectProto.toString; -function vary (res, field) { - if (!res || !res.getHeader || !res.setHeader) { - // quack quack - throw new TypeError('res argument is required') - } - - // get existing header - var val = res.getHeader('Vary') || '' - var header = Array.isArray(val) - ? val.join(', ') - : String(val) - - // set new header - if ((val = append(header, field))) { - res.setHeader('Vary', val) - } -} - - -/***/ }), -/* 284 */ -/***/ (function(module) { - -"use strict"; - -module.exports = balanced; -function balanced(a, b, str) { - if (a instanceof RegExp) a = maybeMatch(a, str); - if (b instanceof RegExp) b = maybeMatch(b, str); - - var r = range(a, b, str); - - return r && { - start: r[0], - end: r[1], - pre: str.slice(0, r[0]), - body: str.slice(r[0] + a.length, r[1]), - post: str.slice(r[1] + b.length) - }; -} - -function maybeMatch(reg, str) { - var m = str.match(reg); - return m ? m[0] : null; -} +/** Built-in value references. */ +var Symbol = root.Symbol, + propertyIsEnumerable = objectProto.propertyIsEnumerable, + spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined; -balanced.range = range; -function range(a, b, str) { - var begs, beg, left, right, result; - var ai = str.indexOf(a); - var bi = str.indexOf(b, ai + 1); - var i = ai; +/** + * The base implementation of `_.flatten` with support for restricting flattening. + * + * @private + * @param {Array} array The array to flatten. + * @param {number} depth The maximum recursion depth. + * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. + * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. + * @param {Array} [result=[]] The initial result value. + * @returns {Array} Returns the new flattened array. + */ +function baseFlatten(array, depth, predicate, isStrict, result) { + var index = -1, + length = array.length; - if (ai >= 0 && bi > 0) { - begs = []; - left = str.length; + predicate || (predicate = isFlattenable); + result || (result = []); - while (i >= 0 && !result) { - if (i == ai) { - begs.push(i); - ai = str.indexOf(a, i + 1); - } else if (begs.length == 1) { - result = [ begs.pop(), bi ]; + while (++index < length) { + var value = array[index]; + if (depth > 0 && predicate(value)) { + if (depth > 1) { + // Recursively flatten arrays (susceptible to call stack limits). + baseFlatten(value, depth - 1, predicate, isStrict, result); } else { - beg = begs.pop(); - if (beg < left) { - left = beg; - right = bi; - } - - bi = str.indexOf(b, i + 1); + arrayPush(result, value); } - - i = ai < bi && ai >= 0 ? ai : bi; - } - - if (begs.length) { - result = [ left, right ]; + } else if (!isStrict) { + result[result.length] = value; } } - return result; } - -/***/ }), -/* 285 */, -/* 286 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -var baseIsTypedArray = __webpack_require__(661), - baseUnary = __webpack_require__(157), - nodeUtil = __webpack_require__(344); - -/* Node.js helper references. */ -var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; +/** + * Checks if `value` is a flattenable `arguments` object or array. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. + */ +function isFlattenable(value) { + return isArray(value) || isArguments(value) || + !!(spreadableSymbol && value && value[spreadableSymbol]); +} /** - * Checks if `value` is classified as a typed array. + * Flattens `array` a single level deep. * * @static * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + * @since 0.1.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. * @example * - * _.isTypedArray(new Uint8Array); - * // => true - * - * _.isTypedArray([]); - * // => false + * _.flatten([1, [2, [3, [4]], 5]]); + * // => [1, 2, [3, [4]], 5] */ -var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; - -module.exports = isTypedArray; - - -/***/ }), -/* 287 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -var path_1 = __importDefault(__webpack_require__(622)); -module.exports = function (app) { - var route = app.route(); - route.get('/probot', function (req, res) { - var pkg; - try { - pkg = require(path_1.default.join(process.cwd(), 'package.json')); - } - catch (e) { - pkg = {}; - } - res.render('probot.hbs', pkg); - }); - route.get('/', function (req, res, next) { return res.redirect('/probot'); }); -}; -//# sourceMappingURL=default.js.map - -/***/ }), -/* 288 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - - -// Update this array if you add/rename/remove files in this directory. -// We support Browserify by skipping automatic module discovery and requiring modules directly. -var modules = [ - __webpack_require__(162), - __webpack_require__(797), - __webpack_require__(645), - __webpack_require__(877), - __webpack_require__(762), - __webpack_require__(28), - __webpack_require__(189), - __webpack_require__(92), -]; - -// Put all encoding/alias/codec definitions to single object and export it. -for (var i = 0; i < modules.length; i++) { - var module = modules[i]; - for (var enc in module) - if (Object.prototype.hasOwnProperty.call(module, enc)) - exports[enc] = module[enc]; +function flatten(array) { + var length = array ? array.length : 0; + return length ? baseFlatten(array, 1) : []; } - -/***/ }), -/* 289 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -var path = __webpack_require__(622); -var fs = __webpack_require__(747); -var _0777 = parseInt('0777', 8); - -module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; - -function mkdirP (p, opts, f, made) { - if (typeof opts === 'function') { - f = opts; - opts = {}; - } - else if (!opts || typeof opts !== 'object') { - opts = { mode: opts }; - } - - var mode = opts.mode; - var xfs = opts.fs || fs; - - if (mode === undefined) { - mode = _0777 - } - if (!made) made = null; - - var cb = f || function () {}; - p = path.resolve(p); - - xfs.mkdir(p, mode, function (er) { - if (!er) { - made = made || p; - return cb(null, made); - } - switch (er.code) { - case 'ENOENT': - if (path.dirname(p) === p) return cb(er); - mkdirP(path.dirname(p), opts, function (er, made) { - if (er) cb(er, made); - else mkdirP(p, opts, cb, made); - }); - break; - - // In the case of any other error, just see if there's a dir - // there already. If so, then hooray! If not, then something - // is borked. - default: - xfs.stat(p, function (er2, stat) { - // if the stat fails, then that's super weird. - // let the original error be the failure reason. - if (er2 || !stat.isDirectory()) cb(er, made) - else cb(null, made); - }); - break; - } - }); +/** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ +function isArguments(value) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && + (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); } -mkdirP.sync = function sync (p, opts, made) { - if (!opts || typeof opts !== 'object') { - opts = { mode: opts }; - } - - var mode = opts.mode; - var xfs = opts.fs || fs; - - if (mode === undefined) { - mode = _0777 - } - if (!made) made = null; - - p = path.resolve(p); - - try { - xfs.mkdirSync(p, mode); - made = made || p; - } - catch (err0) { - switch (err0.code) { - case 'ENOENT' : - made = sync(path.dirname(p), opts, made); - sync(p, opts, made); - break; - - // In the case of any other error, just see if there's a dir - // there already. If so, then hooray! If not, then something - // is borked. - default: - var stat; - try { - stat = xfs.statSync(p); - } - catch (err1) { - throw err0; - } - if (!stat.isDirectory()) throw err0; - break; - } - } - - return made; -}; - - -/***/ }), -/* 290 */, -/* 291 */, -/* 292 */, -/* 293 */ -/***/ (function(module) { - -module.exports = require("buffer"); - -/***/ }), -/* 294 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; - -const fs = __webpack_require__(747); - -module.exports = fp => new Promise(resolve => { - fs.access(fp, err => { - resolve(!err); - }); -}); - -module.exports.sync = fp => { - try { - fs.accessSync(fp); - return true; - } catch (err) { - return false; - } -}; - - -/***/ }), -/* 295 */ -/***/ (function(module) { - -var charenc = { - // UTF-8 encoding - utf8: { - // Convert a string to a byte array - stringToBytes: function(str) { - return charenc.bin.stringToBytes(unescape(encodeURIComponent(str))); - }, - - // Convert a byte array to a string - bytesToString: function(bytes) { - return decodeURIComponent(escape(charenc.bin.bytesToString(bytes))); - } - }, - - // Binary encoding - bin: { - // Convert a string to a byte array - stringToBytes: function(str) { - for (var bytes = [], i = 0; i < str.length; i++) - bytes.push(str.charCodeAt(i) & 0xFF); - return bytes; - }, - - // Convert a byte array to a string - bytesToString: function(bytes) { - for (var str = [], i = 0; i < bytes.length; i++) - str.push(String.fromCharCode(bytes[i])); - return str.join(''); - } - } -}; - -module.exports = charenc; - - -/***/ }), -/* 296 */, -/* 297 */ -/***/ (function(module) { - -module.exports = class HttpError extends Error { - constructor (message, code, headers) { - super(message) - - // Maintains proper stack trace (only available on V8) - /* istanbul ignore next */ - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor) - } +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; - this.name = 'HttpError' - this.code = code - this.headers = headers - } +/** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ +function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); } - -/***/ }), -/* 298 */ -/***/ (function(module) { - /** - * lodash 4.0.1 (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright 2012-2016 The Dojo Foundation - * Based on Underscore.js 1.8.3 - * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - * Available under MIT license + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false */ - -/** `Object#toString` result references. */ -var stringTag = '[object String]'; - -/** Used for built-in method references. */ -var objectProto = Object.prototype; +function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); +} /** - * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) - * of values. + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false */ -var objectToString = objectProto.toString; +function isFunction(value) { + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 8-9 which returns 'object' for typed array and other constructors. + var tag = isObject(value) ? objectToString.call(value) : ''; + return tag == funcTag || tag == genTag; +} /** - * Checks if `value` is classified as an `Array` object. + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ - * @type Function + * @since 4.0.0 * @category Lang * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. * @example * - * _.isArray([1, 2, 3]); + * _.isLength(3); * // => true * - * _.isArray(document.body.children); + * _.isLength(Number.MIN_VALUE); * // => false * - * _.isArray('abc'); + * _.isLength(Infinity); * // => false * - * _.isArray(_.noop); + * _.isLength('3'); * // => false */ -var isArray = Array.isArray; +function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; +} /** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ + * @since 0.1.0 * @category Lang * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * - * _.isObjectLike({}); + * _.isObject({}); * // => true * - * _.isObjectLike([1, 2, 3]); + * _.isObject([1, 2, 3]); * // => true * - * _.isObjectLike(_.noop); - * // => false + * _.isObject(_.noop); + * // => true * - * _.isObjectLike(null); + * _.isObject(null); * // => false */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; +function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); } /** - * Checks if `value` is classified as a `String` primitive or object. + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". * * @static * @memberOf _ + * @since 4.0.0 * @category Lang * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * - * _.isString('abc'); + * _.isObjectLike({}); * // => true * - * _.isString(1); + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); * // => false */ -function isString(value) { - return typeof value == 'string' || - (!isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag); +function isObjectLike(value) { + return !!value && typeof value == 'object'; } -module.exports = isString; +module.exports = flatten; + + +/***/ }), +/* 346 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { +Object.defineProperty(exports, "__esModule", { value: true }); +var tslib_1 = __webpack_require__(422); +var types_1 = __webpack_require__(279); +exports.Severity = types_1.Severity; +exports.Status = types_1.Status; +var core_1 = __webpack_require__(196); +exports.addGlobalEventProcessor = core_1.addGlobalEventProcessor; +exports.addBreadcrumb = core_1.addBreadcrumb; +exports.captureException = core_1.captureException; +exports.captureEvent = core_1.captureEvent; +exports.captureMessage = core_1.captureMessage; +exports.configureScope = core_1.configureScope; +exports.getHubFromCarrier = core_1.getHubFromCarrier; +exports.getCurrentHub = core_1.getCurrentHub; +exports.Hub = core_1.Hub; +exports.makeMain = core_1.makeMain; +exports.Scope = core_1.Scope; +exports.startTransaction = core_1.startTransaction; +exports.setContext = core_1.setContext; +exports.setExtra = core_1.setExtra; +exports.setExtras = core_1.setExtras; +exports.setTag = core_1.setTag; +exports.setTags = core_1.setTags; +exports.setUser = core_1.setUser; +exports.withScope = core_1.withScope; +var backend_1 = __webpack_require__(876); +exports.NodeBackend = backend_1.NodeBackend; +var client_1 = __webpack_require__(106); +exports.NodeClient = client_1.NodeClient; +var sdk_1 = __webpack_require__(526); +exports.defaultIntegrations = sdk_1.defaultIntegrations; +exports.init = sdk_1.init; +exports.lastEventId = sdk_1.lastEventId; +exports.flush = sdk_1.flush; +exports.close = sdk_1.close; +var version_1 = __webpack_require__(706); +exports.SDK_NAME = version_1.SDK_NAME; +exports.SDK_VERSION = version_1.SDK_VERSION; +var core_2 = __webpack_require__(196); +var hub_1 = __webpack_require__(698); +var domain = __webpack_require__(229); +var Handlers = __webpack_require__(807); +exports.Handlers = Handlers; +var NodeIntegrations = __webpack_require__(27); +var Transports = __webpack_require__(177); +exports.Transports = Transports; +var INTEGRATIONS = tslib_1.__assign(tslib_1.__assign({}, core_2.Integrations), NodeIntegrations); +exports.Integrations = INTEGRATIONS; +// We need to patch domain on the global __SENTRY__ object to make it work for node in cross-platform packages like +// @sentry/hub. If we don't do this, browser bundlers will have troubles resolving `require('domain')`. +var carrier = hub_1.getMainCarrier(); +if (carrier.__SENTRY__) { + carrier.__SENTRY__.extensions = carrier.__SENTRY__.extensions || {}; + carrier.__SENTRY__.extensions.domain = carrier.__SENTRY__.extensions.domain || domain; +} +//# sourceMappingURL=index.js.map /***/ }), -/* 299 */ +/* 347 */ /***/ (function(module, __unusedexports, __webpack_require__) { -var baseGetAllKeys = __webpack_require__(857), - getSymbolsIn = __webpack_require__(778), - keysIn = __webpack_require__(331); +"use strict"; +/*! + * statuses + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2016 Douglas Christopher Wilson + * MIT Licensed + */ + + /** - * Creates an array of own and inherited enumerable property names and - * symbols of `object`. - * + * Module dependencies. * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names and symbols. */ -function getAllKeysIn(object) { - return baseGetAllKeys(object, keysIn, getSymbolsIn); -} -module.exports = getAllKeysIn; +var codes = __webpack_require__(563) +/** + * Module exports. + * @public + */ -/***/ }), -/* 300 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +module.exports = status -var getTag = __webpack_require__(965), - isObjectLike = __webpack_require__(458); +// status code to message map +status.STATUS_CODES = codes -/** `Object#toString` result references. */ -var setTag = '[object Set]'; +// array of status codes +status.codes = populateStatusesMap(status, codes) + +// status codes for redirects +status.redirect = { + 300: true, + 301: true, + 302: true, + 303: true, + 305: true, + 307: true, + 308: true +} + +// status codes for empty bodies +status.empty = { + 204: true, + 205: true, + 304: true +} + +// status codes for when you should retry the request +status.retry = { + 502: true, + 503: true, + 504: true +} /** - * The base implementation of `_.isSet` without Node.js optimizations. - * + * Populate the statuses map for given codes. * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a set, else `false`. */ -function baseIsSet(value) { - return isObjectLike(value) && getTag(value) == setTag; -} -module.exports = baseIsSet; +function populateStatusesMap (statuses, codes) { + var arr = [] + Object.keys(codes).forEach(function forEachCode (code) { + var message = codes[code] + var status = Number(code) -/***/ }), -/* 301 */, -/* 302 */, -/* 303 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + // Populate properties + statuses[status] = message + statuses[message] = status + statuses[message.toLowerCase()] = status + + // Add to array + arr.push(status) + }) -var assocIndexOf = __webpack_require__(820); + return arr +} /** - * Sets the list cache `key` to `value`. + * Get the status code. * - * @private - * @name set - * @memberOf ListCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the list cache instance. - */ -function listCacheSet(key, value) { - var data = this.__data__, - index = assocIndexOf(data, key); - - if (index < 0) { - ++this.size; - data.push([key, value]); - } else { - data[index][1] = value; + * Given a number, this will throw if it is not a known status + * code, otherwise the code will be returned. Given a string, + * the string will be parsed for a number and return the code + * if valid, otherwise will lookup the code assuming this is + * the status message. + * + * @param {string|number} code + * @returns {number} + * @public + */ + +function status (code) { + if (typeof code === 'number') { + if (!status[code]) throw new Error('invalid status code: ' + code) + return code } - return this; -} -module.exports = listCacheSet; + if (typeof code !== 'string') { + throw new TypeError('code must be a number or string') + } + // '403' + var n = parseInt(code, 10) + if (!isNaN(n)) { + if (!status[n]) throw new Error('invalid status code: ' + n) + return n + } -/***/ }), -/* 304 */ -/***/ (function(module) { + n = status[code.toLowerCase()] + if (!n) throw new Error('invalid status message: "' + code + '"') + return n +} -module.exports = require("string_decoder"); /***/ }), -/* 305 */, -/* 306 */ +/* 348 */, +/* 349 */, +/* 350 */ /***/ (function(module, __unusedexports, __webpack_require__) { -var concatMap = __webpack_require__(896); -var balanced = __webpack_require__(284); +"use strict"; -module.exports = expandTop; -var escSlash = '\0SLASH'+Math.random()+'\0'; -var escOpen = '\0OPEN'+Math.random()+'\0'; -var escClose = '\0CLOSE'+Math.random()+'\0'; -var escComma = '\0COMMA'+Math.random()+'\0'; -var escPeriod = '\0PERIOD'+Math.random()+'\0'; +const { LEVELS, LEVEL_NAMES } = __webpack_require__(819) -function numeric(str) { - return parseInt(str, 10) == str - ? parseInt(str, 10) - : str.charCodeAt(0); +const nocolor = input => input +const plain = { + default: nocolor, + 60: nocolor, + 50: nocolor, + 40: nocolor, + 30: nocolor, + 20: nocolor, + 10: nocolor, + message: nocolor } -function escapeBraces(str) { - return str.split('\\\\').join(escSlash) - .split('\\{').join(escOpen) - .split('\\}').join(escClose) - .split('\\,').join(escComma) - .split('\\.').join(escPeriod); +const chalk = __webpack_require__(198) +const ctx = new chalk.Instance({ level: 3 }) +const colored = { + default: ctx.white, + 60: ctx.bgRed, + 50: ctx.red, + 40: ctx.yellow, + 30: ctx.green, + 20: ctx.blue, + 10: ctx.grey, + message: ctx.cyan } -function unescapeBraces(str) { - return str.split(escSlash).join('\\') - .split(escOpen).join('{') - .split(escClose).join('}') - .split(escComma).join(',') - .split(escPeriod).join('.'); +function colorizeLevel (level, colorizer) { + if (Number.isInteger(+level)) { + return Object.prototype.hasOwnProperty.call(LEVELS, level) + ? colorizer[level](LEVELS[level]) + : colorizer.default(LEVELS.default) + } + const levelNum = LEVEL_NAMES[level.toLowerCase()] || 'default' + return colorizer[levelNum](LEVELS[levelNum]) } +function plainColorizer (level) { + return colorizeLevel(level, plain) +} +plainColorizer.message = plain.message -// Basically just str.split(","), but handling cases -// where we have nested braced sections, which should be -// treated as individual members, like {a,{b,c},d} -function parseCommaParts(str) { - if (!str) - return ['']; +function coloredColorizer (level) { + return colorizeLevel(level, colored) +} +coloredColorizer.message = colored.message - var parts = []; - var m = balanced('{', '}', str); +/** + * Factory function get a function to colorized levels. The returned function + * also includes a `.message(str)` method to colorize strings. + * + * @param {bool} [useColors=false] When `true` a function that applies standard + * terminal colors is returned. + * + * @returns {function} `function (level) {}` has a `.message(str)` method to + * apply colorization to a string. The core function accepts either an integer + * `level` or a `string` level. The integer level will map to a known level + * string or to `USERLVL` if not known. The string `level` will map to the same + * colors as the integer `level` and will also default to `USERLVL` if the given + * string is not a recognized level name. + */ +module.exports = function getColorizer (useColors = false) { + return useColors ? coloredColorizer : plainColorizer +} - if (!m) - return str.split(','); - var pre = m.pre; - var body = m.body; - var post = m.post; - var p = pre.split(','); +/***/ }), +/* 351 */, +/* 352 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - p[p.length-1] += '{' + body + '}'; - var postParts = parseCommaParts(post); - if (post.length) { - p[p.length-1] += postParts.shift(); - p.push.apply(p, postParts); - } +"use strict"; +// Ported from https://github.com/mafintosh/end-of-stream with +// permission from the author, Mathias Buus (@mafintosh). - parts.push.apply(parts, p); - return parts; -} +var ERR_STREAM_PREMATURE_CLOSE = __webpack_require__(954).codes.ERR_STREAM_PREMATURE_CLOSE; -function expandTop(str) { - if (!str) - return []; +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; - // I don't know why Bash 4.3 does this, but it does. - // Anything starting with {} will have the first two bytes preserved - // but *only* at the top level, so {},a}b will not expand to anything, - // but a{},b}c will be expanded to [a}c,abc]. - // One could argue that this is a bug in Bash, but since the goal of - // this module is to match Bash's rules, we escape a leading {} - if (str.substr(0, 2) === '{}') { - str = '\\{\\}' + str.substr(2); - } + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } - return expand(escapeBraces(str), true).map(unescapeBraces); + callback.apply(this, args); + }; } -function identity(e) { - return e; -} +function noop() {} -function embrace(str) { - return '{' + str + '}'; -} -function isPadded(el) { - return /^-?0\d/.test(el); +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; } -function lte(i, y) { - return i <= y; -} -function gte(i, y) { - return i >= y; -} +function eos(stream, opts, callback) { + if (typeof opts === 'function') return eos(stream, null, opts); + if (!opts) opts = {}; + callback = once(callback || noop); + var readable = opts.readable || opts.readable !== false && stream.readable; + var writable = opts.writable || opts.writable !== false && stream.writable; -function expand(str, isTop) { - var expansions = []; + var onlegacyfinish = function onlegacyfinish() { + if (!stream.writable) onfinish(); + }; - var m = balanced('{', '}', str); - if (!m || /\$$/.test(m.pre)) return [str]; + var writableEnded = stream._writableState && stream._writableState.finished; - var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); - var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); - var isSequence = isNumericSequence || isAlphaSequence; - var isOptions = m.body.indexOf(',') >= 0; - if (!isSequence && !isOptions) { - // {a},b} - if (m.post.match(/,.*\}/)) { - str = m.pre + '{' + m.body + escClose + m.post; - return expand(str); - } - return [str]; - } + var onfinish = function onfinish() { + writable = false; + writableEnded = true; + if (!readable) callback.call(stream); + }; - var n; - if (isSequence) { - n = m.body.split(/\.\./); - } else { - n = parseCommaParts(m.body); - if (n.length === 1) { - // x{{a,b}}y ==> x{a}y x{b}y - n = expand(n[0], false).map(embrace); - if (n.length === 1) { - var post = m.post.length - ? expand(m.post, false) - : ['']; - return post.map(function(p) { - return m.pre + n[0] + p; - }); - } - } - } + var readableEnded = stream._readableState && stream._readableState.endEmitted; - // at this point, n is the parts, and we know it's not a comma set - // with a single entry. + var onend = function onend() { + readable = false; + readableEnded = true; + if (!writable) callback.call(stream); + }; - // no need to expand pre, since it is guaranteed to be free of brace-sets - var pre = m.pre; - var post = m.post.length - ? expand(m.post, false) - : ['']; + var onerror = function onerror(err) { + callback.call(stream, err); + }; - var N; + var onclose = function onclose() { + var err; - if (isSequence) { - var x = numeric(n[0]); - var y = numeric(n[1]); - var width = Math.max(n[0].length, n[1].length) - var incr = n.length == 3 - ? Math.abs(numeric(n[2])) - : 1; - var test = lte; - var reverse = y < x; - if (reverse) { - incr *= -1; - test = gte; + if (readable && !readableEnded) { + if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); } - var pad = n.some(isPadded); - N = []; - - for (var i = x; test(i, y); i += incr) { - var c; - if (isAlphaSequence) { - c = String.fromCharCode(i); - if (c === '\\') - c = ''; - } else { - c = String(i); - if (pad) { - var need = width - c.length; - if (need > 0) { - var z = new Array(need + 1).join('0'); - if (i < 0) - c = '-' + z + c.slice(1); - else - c = z + c; - } - } - } - N.push(c); + if (writable && !writableEnded) { + if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); } - } else { - N = concatMap(n, function(el) { return expand(el, false) }); - } + }; - for (var j = 0; j < N.length; j++) { - for (var k = 0; k < post.length; k++) { - var expansion = pre + N[j] + post[k]; - if (!isTop || isSequence || expansion) - expansions.push(expansion); - } + var onrequest = function onrequest() { + stream.req.on('finish', onfinish); + }; + + if (isRequest(stream)) { + stream.on('complete', onfinish); + stream.on('abort', onclose); + if (stream.req) onrequest();else stream.on('request', onrequest); + } else if (writable && !stream._writableState) { + // legacy streams + stream.on('end', onlegacyfinish); + stream.on('close', onlegacyfinish); } - return expansions; + stream.on('end', onend); + stream.on('finish', onfinish); + if (opts.error !== false) stream.on('error', onerror); + stream.on('close', onclose); + return function () { + stream.removeListener('complete', onfinish); + stream.removeListener('abort', onclose); + stream.removeListener('request', onrequest); + if (stream.req) stream.req.removeListener('finish', onfinish); + stream.removeListener('end', onlegacyfinish); + stream.removeListener('close', onlegacyfinish); + stream.removeListener('finish', onfinish); + stream.removeListener('end', onend); + stream.removeListener('error', onerror); + stream.removeListener('close', onclose); + }; } - +module.exports = eos; /***/ }), -/* 307 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -/*global module*/ -var Buffer = __webpack_require__(149).Buffer; -var DataStream = __webpack_require__(32); -var jwa = __webpack_require__(108); -var Stream = __webpack_require__(413); -var toString = __webpack_require__(975); -var util = __webpack_require__(669); -var JWS_REGEX = /^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/; - -function isObject(thing) { - return Object.prototype.toString.call(thing) === '[object Object]'; -} - -function safeJsonParse(thing) { - if (isObject(thing)) - return thing; - try { return JSON.parse(thing); } - catch (e) { return undefined; } -} - -function headerFromJWS(jwsSig) { - var encodedHeader = jwsSig.split('.', 1)[0]; - return safeJsonParse(Buffer.from(encodedHeader, 'base64').toString('binary')); -} +/* 353 */ +/***/ (function(module) { -function securedInputFromJWS(jwsSig) { - return jwsSig.split('.', 2).join('.'); -} +"use strict"; -function signatureFromJWS(jwsSig) { - return jwsSig.split('.')[2]; -} -function payloadFromJWS(jwsSig, encoding) { - encoding = encoding || 'utf8'; - var payload = jwsSig.split('.')[1]; - return Buffer.from(payload, 'base64').toString(encoding); -} +/** + * Tries to execute a function and discards any error that occurs. + * @param {Function} fn - Function that might or might not throw an error. + * @returns {?*} Return-value of the function when no error occurred. + */ +module.exports = function(fn) { -function isValidJws(string) { - return JWS_REGEX.test(string) && !!headerFromJWS(string); -} + try { return fn() } catch (e) {} -function jwsVerify(jwsSig, algorithm, secretOrKey) { - if (!algorithm) { - var err = new Error("Missing algorithm parameter for jws.verify"); - err.code = "MISSING_ALGORITHM"; - throw err; - } - jwsSig = toString(jwsSig); - var signature = signatureFromJWS(jwsSig); - var securedInput = securedInputFromJWS(jwsSig); - var algo = jwa(algorithm); - return algo.verify(securedInput, signature, secretOrKey); } -function jwsDecode(jwsSig, opts) { - opts = opts || {}; - jwsSig = toString(jwsSig); - - if (!isValidJws(jwsSig)) - return null; +/***/ }), +/* 354 */ +/***/ (function(module, exports, __webpack_require__) { - var header = headerFromJWS(jwsSig); - if (!header) - return null; +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + * + * Expose `debug()` as the module. + */ - var payload = payloadFromJWS(jwsSig); - if (header.typ === 'JWT' || opts.json) - payload = JSON.parse(payload, opts.encoding); +exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; +exports.coerce = coerce; +exports.disable = disable; +exports.enable = enable; +exports.enabled = enabled; +exports.humanize = __webpack_require__(922); - return { - header: header, - payload: payload, - signature: signatureFromJWS(jwsSig) - }; -} +/** + * The currently active debug mode names, and names to skip. + */ -function VerifyStream(opts) { - opts = opts || {}; - var secretOrKey = opts.secret||opts.publicKey||opts.key; - var secretStream = new DataStream(secretOrKey); - this.readable = true; - this.algorithm = opts.algorithm; - this.encoding = opts.encoding; - this.secret = this.publicKey = this.key = secretStream; - this.signature = new DataStream(opts.signature); - this.secret.once('close', function () { - if (!this.signature.writable && this.readable) - this.verify(); - }.bind(this)); +exports.names = []; +exports.skips = []; - this.signature.once('close', function () { - if (!this.secret.writable && this.readable) - this.verify(); - }.bind(this)); -} -util.inherits(VerifyStream, Stream); -VerifyStream.prototype.verify = function verify() { - try { - var valid = jwsVerify(this.signature.buffer, this.algorithm, this.key.buffer); - var obj = jwsDecode(this.signature.buffer, this.encoding); - this.emit('done', valid, obj); - this.emit('data', valid); - this.emit('end'); - this.readable = false; - return valid; - } catch (e) { - this.readable = false; - this.emit('error', e); - this.emit('close'); - } -}; +/** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ -VerifyStream.decode = jwsDecode; -VerifyStream.isValid = isValidJws; -VerifyStream.verify = jwsVerify; +exports.formatters = {}; -module.exports = VerifyStream; +/** + * Previous log timestamp. + */ +var prevTime; -/***/ }), -/* 308 */, -/* 309 */ -/***/ (function(module, exports, __webpack_require__) { +/** + * Select a color. + * @param {String} namespace + * @return {Number} + * @api private + */ -/* eslint-disable node/no-deprecated-api */ -var buffer = __webpack_require__(293) -var Buffer = buffer.Buffer +function selectColor(namespace) { + var hash = 0, i; -// alternative to using Object.keys for old browsers -function copyProps (src, dst) { - for (var key in src) { - dst[key] = src[key] + for (i in namespace) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer } -} -if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { - module.exports = buffer -} else { - // Copy properties from require('buffer') - copyProps(buffer, exports) - exports.Buffer = SafeBuffer -} -function SafeBuffer (arg, encodingOrOffset, length) { - return Buffer(arg, encodingOrOffset, length) + return exports.colors[Math.abs(hash) % exports.colors.length]; } -// Copy static methods from Buffer -copyProps(Buffer, SafeBuffer) - -SafeBuffer.from = function (arg, encodingOrOffset, length) { - if (typeof arg === 'number') { - throw new TypeError('Argument must not be a number') - } - return Buffer(arg, encodingOrOffset, length) -} +/** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ -SafeBuffer.alloc = function (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - var buf = Buffer(size) - if (fill !== undefined) { - if (typeof encoding === 'string') { - buf.fill(fill, encoding) - } else { - buf.fill(fill) - } - } else { - buf.fill(0) - } - return buf -} +function createDebug(namespace) { -SafeBuffer.allocUnsafe = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return Buffer(size) -} + function debug() { + // disabled? + if (!debug.enabled) return; -SafeBuffer.allocUnsafeSlow = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return buffer.SlowBuffer(size) -} + var self = debug; + // set `diff` timestamp + var curr = +new Date(); + var ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; -/***/ }), -/* 310 */, -/* 311 */, -/* 312 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + // turn the `arguments` into a proper Array + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } -"use strict"; + args[0] = exports.coerce(args[0]); + if ('string' !== typeof args[0]) { + // anything else let's inspect with %O + args.unshift('%O'); + } -var common = __webpack_require__(740); -var Type = __webpack_require__(945); + // apply any `formatters` transformations + var index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { + // if we encounter an escaped % then don't increase the array index + if (match === '%%') return match; + index++; + var formatter = exports.formatters[format]; + if ('function' === typeof formatter) { + var val = args[index]; + match = formatter.call(self, val); -var YAML_FLOAT_PATTERN = new RegExp( - // 2.5e4, 2.5 and integers - '^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' + - // .2e4, .2 - // special case, seems not from spec - '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' + - // 20:59 - '|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*' + - // .inf - '|[-+]?\\.(?:inf|Inf|INF)' + - // .nan - '|\\.(?:nan|NaN|NAN))$'); + // now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); -function resolveYamlFloat(data) { - if (data === null) return false; + // apply env-specific formatting (colors, etc.) + exports.formatArgs.call(self, args); - if (!YAML_FLOAT_PATTERN.test(data) || - // Quick hack to not allow integers end with `_` - // Probably should update regexp & check speed - data[data.length - 1] === '_') { - return false; + var logFn = debug.log || exports.log || console.log.bind(console); + logFn.apply(self, args); } - return true; -} - -function constructYamlFloat(data) { - var value, sign, base, digits; - - value = data.replace(/_/g, '').toLowerCase(); - sign = value[0] === '-' ? -1 : 1; - digits = []; + debug.namespace = namespace; + debug.enabled = exports.enabled(namespace); + debug.useColors = exports.useColors(); + debug.color = selectColor(namespace); - if ('+-'.indexOf(value[0]) >= 0) { - value = value.slice(1); + // env-specific initialization logic for debug instances + if ('function' === typeof exports.init) { + exports.init(debug); } - if (value === '.inf') { - return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; - - } else if (value === '.nan') { - return NaN; + return debug; +} - } else if (value.indexOf(':') >= 0) { - value.split(':').forEach(function (v) { - digits.unshift(parseFloat(v, 10)); - }); +/** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ - value = 0.0; - base = 1; +function enable(namespaces) { + exports.save(namespaces); - digits.forEach(function (d) { - value += d * base; - base *= 60; - }); + exports.names = []; + exports.skips = []; - return sign * value; + var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + var len = split.length; + for (var i = 0; i < len; i++) { + if (!split[i]) continue; // ignore empty strings + namespaces = split[i].replace(/\*/g, '.*?'); + if (namespaces[0] === '-') { + exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + exports.names.push(new RegExp('^' + namespaces + '$')); + } } - return sign * parseFloat(value, 10); } +/** + * Disable debug output. + * + * @api public + */ -var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; +function disable() { + exports.enable(''); +} -function representYamlFloat(object, style) { - var res; +/** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ - if (isNaN(object)) { - switch (style) { - case 'lowercase': return '.nan'; - case 'uppercase': return '.NAN'; - case 'camelcase': return '.NaN'; - } - } else if (Number.POSITIVE_INFINITY === object) { - switch (style) { - case 'lowercase': return '.inf'; - case 'uppercase': return '.INF'; - case 'camelcase': return '.Inf'; +function enabled(name) { + var i, len; + for (i = 0, len = exports.skips.length; i < len; i++) { + if (exports.skips[i].test(name)) { + return false; } - } else if (Number.NEGATIVE_INFINITY === object) { - switch (style) { - case 'lowercase': return '-.inf'; - case 'uppercase': return '-.INF'; - case 'camelcase': return '-.Inf'; + } + for (i = 0, len = exports.names.length; i < len; i++) { + if (exports.names[i].test(name)) { + return true; } - } else if (common.isNegativeZero(object)) { - return '-0.0'; } - - res = object.toString(10); - - // JS stringifier can build scientific format without dots: 5e-100, - // while YAML requres dot: 5.e-100. Fix it with simple hack - - return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res; + return false; } -function isFloat(object) { - return (Object.prototype.toString.call(object) === '[object Number]') && - (object % 1 !== 0 || common.isNegativeZero(object)); -} +/** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ -module.exports = new Type('tag:yaml.org,2002:float', { - kind: 'scalar', - resolve: resolveYamlFloat, - construct: constructYamlFloat, - predicate: isFloat, - represent: representYamlFloat, - defaultStyle: 'lowercase' -}); +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; +} /***/ }), -/* 313 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +/* 355 */, +/* 356 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createWebhookProxy = void 0; +exports.createWebhookProxy = (opts) => { + try { + const SmeeClient = __webpack_require__(902); + const smee = new SmeeClient({ + logger: opts.logger, + source: opts.url, + target: `http://localhost:${opts.port}${opts.path}`, + }); + return smee.start(); + } + catch (error) { + opts.logger.warn("Run `npm install --save-dev smee-client` to proxy webhooks to localhost."); + return; + } +}; +//# sourceMappingURL=webhook-proxy.js.map -var Buffer = __webpack_require__(293).Buffer, - Transform = __webpack_require__(413).Transform; +/***/ }), +/* 357 */ +/***/ (function(module) { +module.exports = require("assert"); -// == Exports ================================================================== -module.exports = function(iconv) { - - // Additional Public API. - iconv.encodeStream = function encodeStream(encoding, options) { - return new IconvLiteEncoderStream(iconv.getEncoder(encoding, options), options); - } +/***/ }), +/* 358 */, +/* 359 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - iconv.decodeStream = function decodeStream(encoding, options) { - return new IconvLiteDecoderStream(iconv.getDecoder(encoding, options), options); - } +"use strict"; - iconv.supportsStreams = true; +var Buffer = __webpack_require__(293).Buffer; +// Note: not polyfilled with safer-buffer on a purpose, as overrides Buffer +// == Extend Node primitives to use iconv-lite ================================= - // Not published yet. - iconv.IconvLiteEncoderStream = IconvLiteEncoderStream; - iconv.IconvLiteDecoderStream = IconvLiteDecoderStream; - iconv._collect = IconvLiteDecoderStream.prototype.collect; -}; +module.exports = function (iconv) { + var original = undefined; // Place to keep original methods. + // Node authors rewrote Buffer internals to make it compatible with + // Uint8Array and we cannot patch key functions since then. + // Note: this does use older Buffer API on a purpose + iconv.supportsNodeEncodingsExtension = !(Buffer.from || new Buffer(0) instanceof Uint8Array); -// == Encoder stream ======================================================= -function IconvLiteEncoderStream(conv, options) { - this.conv = conv; - options = options || {}; - options.decodeStrings = false; // We accept only strings, so we don't need to decode them. - Transform.call(this, options); -} + iconv.extendNodeEncodings = function extendNodeEncodings() { + if (original) return; + original = {}; -IconvLiteEncoderStream.prototype = Object.create(Transform.prototype, { - constructor: { value: IconvLiteEncoderStream } -}); + if (!iconv.supportsNodeEncodingsExtension) { + console.error("ACTION NEEDED: require('iconv-lite').extendNodeEncodings() is not supported in your version of Node"); + console.error("See more info at https://github.com/ashtuchkin/iconv-lite/wiki/Node-v4-compatibility"); + return; + } -IconvLiteEncoderStream.prototype._transform = function(chunk, encoding, done) { - if (typeof chunk != 'string') - return done(new Error("Iconv encoding stream needs strings as its input.")); - try { - var res = this.conv.write(chunk); - if (res && res.length) this.push(res); - done(); - } - catch (e) { - done(e); - } -} + var nodeNativeEncodings = { + 'hex': true, 'utf8': true, 'utf-8': true, 'ascii': true, 'binary': true, + 'base64': true, 'ucs2': true, 'ucs-2': true, 'utf16le': true, 'utf-16le': true, + }; -IconvLiteEncoderStream.prototype._flush = function(done) { - try { - var res = this.conv.end(); - if (res && res.length) this.push(res); - done(); - } - catch (e) { - done(e); - } -} + Buffer.isNativeEncoding = function(enc) { + return enc && nodeNativeEncodings[enc.toLowerCase()]; + } -IconvLiteEncoderStream.prototype.collect = function(cb) { - var chunks = []; - this.on('error', cb); - this.on('data', function(chunk) { chunks.push(chunk); }); - this.on('end', function() { - cb(null, Buffer.concat(chunks)); - }); - return this; -} + // -- SlowBuffer ----------------------------------------------------------- + var SlowBuffer = __webpack_require__(293).SlowBuffer; + original.SlowBufferToString = SlowBuffer.prototype.toString; + SlowBuffer.prototype.toString = function(encoding, start, end) { + encoding = String(encoding || 'utf8').toLowerCase(); -// == Decoder stream ======================================================= -function IconvLiteDecoderStream(conv, options) { - this.conv = conv; - options = options || {}; - options.encoding = this.encoding = 'utf8'; // We output strings. - Transform.call(this, options); -} + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.SlowBufferToString.call(this, encoding, start, end); -IconvLiteDecoderStream.prototype = Object.create(Transform.prototype, { - constructor: { value: IconvLiteDecoderStream } -}); + // Otherwise, use our decoding method. + if (typeof start == 'undefined') start = 0; + if (typeof end == 'undefined') end = this.length; + return iconv.decode(this.slice(start, end), encoding); + } -IconvLiteDecoderStream.prototype._transform = function(chunk, encoding, done) { - if (!Buffer.isBuffer(chunk)) - return done(new Error("Iconv decoding stream needs buffers as its input.")); - try { - var res = this.conv.write(chunk); - if (res && res.length) this.push(res, this.encoding); - done(); - } - catch (e) { - done(e); - } -} + original.SlowBufferWrite = SlowBuffer.prototype.write; + SlowBuffer.prototype.write = function(string, offset, length, encoding) { + // Support both (string, offset, length, encoding) + // and the legacy (string, encoding, offset, length) + if (isFinite(offset)) { + if (!isFinite(length)) { + encoding = length; + length = undefined; + } + } else { // legacy + var swap = encoding; + encoding = offset; + offset = length; + length = swap; + } -IconvLiteDecoderStream.prototype._flush = function(done) { - try { - var res = this.conv.end(); - if (res && res.length) this.push(res, this.encoding); - done(); - } - catch (e) { - done(e); - } -} + offset = +offset || 0; + var remaining = this.length - offset; + if (!length) { + length = remaining; + } else { + length = +length; + if (length > remaining) { + length = remaining; + } + } + encoding = String(encoding || 'utf8').toLowerCase(); -IconvLiteDecoderStream.prototype.collect = function(cb) { - var res = ''; - this.on('error', cb); - this.on('data', function(chunk) { res += chunk; }); - this.on('end', function() { - cb(null, res); - }); - return this; -} + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.SlowBufferWrite.call(this, string, offset, length, encoding); + if (string.length > 0 && (length < 0 || offset < 0)) + throw new RangeError('attempt to write beyond buffer bounds'); + // Otherwise, use our encoding method. + var buf = iconv.encode(string, encoding); + if (buf.length < length) length = buf.length; + buf.copy(this, offset, 0, length); + return length; + } -/***/ }), -/* 314 */, -/* 315 */ -/***/ (function(module) { + // -- Buffer --------------------------------------------------------------- -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true + original.BufferIsEncoding = Buffer.isEncoding; + Buffer.isEncoding = function(encoding) { + return Buffer.isNativeEncoding(encoding) || iconv.encodingExists(encoding); } - }) - } - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } - } -} + original.BufferByteLength = Buffer.byteLength; + Buffer.byteLength = SlowBuffer.byteLength = function(str, encoding) { + encoding = String(encoding || 'utf8').toLowerCase(); -/***/ }), -/* 316 */ -/***/ (function(module, __unusedexports, __webpack_require__) { + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.BufferByteLength.call(this, str, encoding); -var path = __webpack_require__(622); -var fs = __webpack_require__(747); + // Slow, I know, but we don't have a better way yet. + return iconv.encode(str, encoding).length; + } -function Mime() { - // Map of extension -> mime type - this.types = Object.create(null); + original.BufferToString = Buffer.prototype.toString; + Buffer.prototype.toString = function(encoding, start, end) { + encoding = String(encoding || 'utf8').toLowerCase(); - // Map of mime type -> extension - this.extensions = Object.create(null); -} + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.BufferToString.call(this, encoding, start, end); -/** - * Define mimetype -> extension mappings. Each key is a mime-type that maps - * to an array of extensions associated with the type. The first extension is - * used as the default extension for the type. - * - * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']}); - * - * @param map (Object) type definitions - */ -Mime.prototype.define = function (map) { - for (var type in map) { - var exts = map[type]; - for (var i = 0; i < exts.length; i++) { - if (process.env.DEBUG_MIME && this.types[exts[i]]) { - console.warn((this._loading || "define()").replace(/.*\//, ''), 'changes "' + exts[i] + '" extension type from ' + - this.types[exts[i]] + ' to ' + type); - } + // Otherwise, use our decoding method. + if (typeof start == 'undefined') start = 0; + if (typeof end == 'undefined') end = this.length; + return iconv.decode(this.slice(start, end), encoding); + } - this.types[exts[i]] = type; - } + original.BufferWrite = Buffer.prototype.write; + Buffer.prototype.write = function(string, offset, length, encoding) { + var _offset = offset, _length = length, _encoding = encoding; + // Support both (string, offset, length, encoding) + // and the legacy (string, encoding, offset, length) + if (isFinite(offset)) { + if (!isFinite(length)) { + encoding = length; + length = undefined; + } + } else { // legacy + var swap = encoding; + encoding = offset; + offset = length; + length = swap; + } - // Default extension is the first one we encounter - if (!this.extensions[type]) { - this.extensions[type] = exts[0]; - } - } -}; + encoding = String(encoding || 'utf8').toLowerCase(); -/** - * Load an Apache2-style ".types" file - * - * This may be called multiple times (it's expected). Where files declare - * overlapping types/extensions, the last file wins. - * - * @param file (String) path of file to load. - */ -Mime.prototype.load = function(file) { - this._loading = file; - // Read file and split into lines - var map = {}, - content = fs.readFileSync(file, 'ascii'), - lines = content.split(/[\r\n]+/); + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.BufferWrite.call(this, string, _offset, _length, _encoding); - lines.forEach(function(line) { - // Clean up whitespace/comments, and split into fields - var fields = line.replace(/\s*#.*|^\s*|\s*$/g, '').split(/\s+/); - map[fields.shift()] = fields; - }); + offset = +offset || 0; + var remaining = this.length - offset; + if (!length) { + length = remaining; + } else { + length = +length; + if (length > remaining) { + length = remaining; + } + } - this.define(map); + if (string.length > 0 && (length < 0 || offset < 0)) + throw new RangeError('attempt to write beyond buffer bounds'); - this._loading = null; -}; + // Otherwise, use our encoding method. + var buf = iconv.encode(string, encoding); + if (buf.length < length) length = buf.length; + buf.copy(this, offset, 0, length); + return length; -/** - * Lookup a mime type based on extension - */ -Mime.prototype.lookup = function(path, fallback) { - var ext = path.replace(/^.*[\.\/\\]/, '').toLowerCase(); + // TODO: Set _charsWritten. + } - return this.types[ext] || fallback || this.default_type; -}; -/** - * Return file extension associated with a mime type - */ -Mime.prototype.extension = function(mimeType) { - var type = mimeType.match(/^\s*([^;\s]*)(?:;|\s|$)/)[1].toLowerCase(); - return this.extensions[type]; -}; + // -- Readable ------------------------------------------------------------- + if (iconv.supportsStreams) { + var Readable = __webpack_require__(413).Readable; -// Default instance -var mime = new Mime(); + original.ReadableSetEncoding = Readable.prototype.setEncoding; + Readable.prototype.setEncoding = function setEncoding(enc, options) { + // Use our own decoder, it has the same interface. + // We cannot use original function as it doesn't handle BOM-s. + this._readableState.decoder = iconv.getDecoder(enc, options); + this._readableState.encoding = enc; + } -// Define built-in types -mime.define(__webpack_require__(122)); + Readable.prototype.collect = iconv._collect; + } + } -// Default type -mime.default_type = mime.lookup('bin'); + // Remove iconv-lite Node primitive extensions. + iconv.undoExtendNodeEncodings = function undoExtendNodeEncodings() { + if (!iconv.supportsNodeEncodingsExtension) + return; + if (!original) + throw new Error("require('iconv-lite').undoExtendNodeEncodings(): Nothing to undo; extendNodeEncodings() is not called.") -// -// Additional API specific to the default instance -// + delete Buffer.isNativeEncoding; -mime.Mime = Mime; + var SlowBuffer = __webpack_require__(293).SlowBuffer; -/** - * Lookup a charset based on mime type. - */ -mime.charsets = { - lookup: function(mimeType, fallback) { - // Assume text types are utf8 - return (/^text\/|^application\/(javascript|json)/).test(mimeType) ? 'UTF-8' : fallback; - } -}; + SlowBuffer.prototype.toString = original.SlowBufferToString; + SlowBuffer.prototype.write = original.SlowBufferWrite; -module.exports = mime; + Buffer.isEncoding = original.BufferIsEncoding; + Buffer.byteLength = original.BufferByteLength; + Buffer.prototype.toString = original.BufferToString; + Buffer.prototype.write = original.BufferWrite; + + if (iconv.supportsStreams) { + var Readable = __webpack_require__(413).Readable; + + Readable.prototype.setEncoding = original.ReadableSetEncoding; + delete Readable.prototype.collect; + } + + original = undefined; + } +} /***/ }), -/* 317 */ +/* 360 */, +/* 361 */, +/* 362 */, +/* 363 */ /***/ (function(module) { -/** - * Helpers. - */ +module.exports = register -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var w = d * 7; -var y = d * 365.25; +function register (state, name, method, options) { + if (typeof method !== 'function') { + throw new Error('method for before hook must be a function') + } -/** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public - */ + if (!options) { + options = {} + } -module.exports = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isFinite(val)) { - return options.long ? fmtLong(val) : fmtShort(val); + if (Array.isArray(name)) { + return name.reverse().reduce(function (callback, name) { + return register.bind(null, state, name, callback, options) + }, method)() } - throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) - ); + + return Promise.resolve() + .then(function () { + if (!state.registry[name]) { + return method(options) + } + + return (state.registry[name]).reduce(function (method, registered) { + return registered.hook.bind(null, method, options) + }, method)() + }) +} + + +/***/ }), +/* 364 */ +/***/ (function(module) { + +"use strict"; + + +module.exports = (flag, argv = process.argv) => { + const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); + const position = argv.indexOf(prefix + flag); + const terminatorPosition = argv.indexOf('--'); + return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); }; -/** - * Parse the given `str` and return milliseconds. + +/***/ }), +/* 365 */, +/* 366 */ +/***/ (function(__unusedmodule, exports) { + +"use strict"; + + +Object.defineProperty(exports, '__esModule', { value: true }); + +/*! + * is-plain-object * - * @param {String} str - * @return {Number} - * @api private + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. */ -function parse(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'weeks': - case 'week': - case 'w': - return n * w; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; - } +function isObject(o) { + return Object.prototype.toString.call(o) === '[object Object]'; } -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ +function isPlainObject(o) { + var ctor,prot; -function fmtShort(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return Math.round(ms / d) + 'd'; - } - if (msAbs >= h) { - return Math.round(ms / h) + 'h'; - } - if (msAbs >= m) { - return Math.round(ms / m) + 'm'; - } - if (msAbs >= s) { - return Math.round(ms / s) + 's'; + if (isObject(o) === false) return false; + + // If has modified constructor + ctor = o.constructor; + if (ctor === undefined) return true; + + // If has modified prototype + prot = ctor.prototype; + if (isObject(prot) === false) return false; + + // If constructor does not have an Object-specific method + if (prot.hasOwnProperty('isPrototypeOf') === false) { + return false; } - return ms + 'ms'; + + // Most likely a plain Object + return true; } -/** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ +exports.isPlainObject = isPlainObject; -function fmtLong(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return plural(ms, msAbs, d, 'day'); - } - if (msAbs >= h) { - return plural(ms, msAbs, h, 'hour'); + +/***/ }), +/* 367 */, +/* 368 */ +/***/ (function(__unusedmodule, exports) { + +"use strict"; + + +Object.defineProperty(exports, '__esModule', { value: true }); + +const Endpoints = { + actions: { + addSelectedRepoToOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"], + cancelWorkflowRun: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel"], + createOrUpdateOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}"], + createOrUpdateRepoSecret: ["PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}", {}, { + renamedParameters: { + name: "secret_name" + } + }], + createOrUpdateSecretForRepo: ["PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}", {}, { + renamed: ["actions", "createOrUpdateRepoSecret"], + renamedParameters: { + name: "secret_name" + } + }], + createRegistrationToken: ["POST /repos/{owner}/{repo}/actions/runners/registration-token", {}, { + renamed: ["actions", "createRegistrationTokenForRepo"] + }], + createRegistrationTokenForOrg: ["POST /orgs/{org}/actions/runners/registration-token"], + createRegistrationTokenForRepo: ["POST /repos/{owner}/{repo}/actions/runners/registration-token"], + createRemoveToken: ["POST /repos/{owner}/{repo}/actions/runners/remove-token", {}, { + renamed: ["actions", "createRemoveTokenForRepo"] + }], + createRemoveTokenForOrg: ["POST /orgs/{org}/actions/runners/remove-token"], + createRemoveTokenForRepo: ["POST /repos/{owner}/{repo}/actions/runners/remove-token"], + deleteArtifact: ["DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"], + deleteOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}"], + deleteRepoSecret: ["DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}", {}, { + renamedParameters: { + name: "secret_name" + } + }], + deleteSecretFromRepo: ["DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}", {}, { + renamed: ["actions", "deleteRepoSecret"], + renamedParameters: { + name: "secret_name" + } + }], + deleteSelfHostedRunnerFromOrg: ["DELETE /orgs/{org}/actions/runners/{runner_id}"], + deleteSelfHostedRunnerFromRepo: ["DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}"], + deleteWorkflowRunLogs: ["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs"], + downloadArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}"], + downloadJobLogsForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs"], + downloadWorkflowJobLogs: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs", {}, { + renamed: ["actions", "downloadJobLogsForWorkflowRun"] + }], + downloadWorkflowRunLogs: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs"], + getArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"], + getJobForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}"], + getOrgPublicKey: ["GET /orgs/{org}/actions/secrets/public-key"], + getOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}"], + getPublicKey: ["GET /repos/{owner}/{repo}/actions/secrets/public-key", {}, { + renamed: ["actions", "getRepoPublicKey"] + }], + getRepoPublicKey: ["GET /repos/{owner}/{repo}/actions/secrets/public-key"], + getRepoSecret: ["GET /repos/{owner}/{repo}/actions/secrets/{secret_name}", {}, { + renamedParameters: { + name: "secret_name" + } + }], + getSecret: ["GET /repos/{owner}/{repo}/actions/secrets/{secret_name}", {}, { + renamed: ["actions", "getRepoSecret"], + renamedParameters: { + name: "secret_name" + } + }], + getSelfHostedRunner: ["GET /repos/{owner}/{repo}/actions/runners/{runner_id}", {}, { + renamed: ["actions", "getSelfHostedRunnerForRepo"] + }], + getSelfHostedRunnerForOrg: ["GET /orgs/{org}/actions/runners/{runner_id}"], + getSelfHostedRunnerForRepo: ["GET /repos/{owner}/{repo}/actions/runners/{runner_id}"], + getWorkflow: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}"], + getWorkflowJob: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}", {}, { + renamed: ["actions", "getJobForWorkflowRun"] + }], + getWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}"], + getWorkflowRunUsage: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing"], + getWorkflowUsage: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing"], + listArtifactsForRepo: ["GET /repos/{owner}/{repo}/actions/artifacts"], + listDownloadsForSelfHostedRunnerApplication: ["GET /repos/{owner}/{repo}/actions/runners/downloads", {}, { + renamed: ["actions", "listRunnerApplicationsForRepo"] + }], + listJobsForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs"], + listOrgSecrets: ["GET /orgs/{org}/actions/secrets"], + listRepoSecrets: ["GET /repos/{owner}/{repo}/actions/secrets"], + listRepoWorkflowRuns: ["GET /repos/{owner}/{repo}/actions/runs", {}, { + renamed: ["actions", "listWorkflowRunsForRepo"] + }], + listRepoWorkflows: ["GET /repos/{owner}/{repo}/actions/workflows"], + listRunnerApplicationsForOrg: ["GET /orgs/{org}/actions/runners/downloads"], + listRunnerApplicationsForRepo: ["GET /repos/{owner}/{repo}/actions/runners/downloads"], + listSecretsForRepo: ["GET /repos/{owner}/{repo}/actions/secrets", {}, { + renamed: ["actions", "listRepoSecrets"] + }], + listSelectedReposForOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}/repositories"], + listSelfHostedRunnersForOrg: ["GET /orgs/{org}/actions/runners"], + listSelfHostedRunnersForRepo: ["GET /repos/{owner}/{repo}/actions/runners"], + listWorkflowJobLogs: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs", {}, { + renamed: ["actions", "downloadWorkflowJobLogs"] + }], + listWorkflowRunArtifacts: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts"], + listWorkflowRunLogs: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs", {}, { + renamed: ["actions", "downloadWorkflowRunLogs"] + }], + listWorkflowRuns: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs"], + listWorkflowRunsForRepo: ["GET /repos/{owner}/{repo}/actions/runs"], + reRunWorkflow: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun"], + removeSelectedRepoFromOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"], + removeSelfHostedRunner: ["DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}", {}, { + renamed: ["actions", "deleteSelfHostedRunnerFromRepo"] + }], + setSelectedReposForOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}/repositories"] + }, + activity: { + checkRepoIsStarredByAuthenticatedUser: ["GET /user/starred/{owner}/{repo}"], + checkStarringRepo: ["GET /user/starred/{owner}/{repo}", {}, { + renamed: ["activity", "checkRepoIsStarredByAuthenticatedUser"] + }], + deleteRepoSubscription: ["DELETE /repos/{owner}/{repo}/subscription"], + deleteThreadSubscription: ["DELETE /notifications/threads/{thread_id}/subscription"], + getFeeds: ["GET /feeds"], + getRepoSubscription: ["GET /repos/{owner}/{repo}/subscription"], + getThread: ["GET /notifications/threads/{thread_id}"], + getThreadSubscription: ["PUT /notifications", {}, { + renamed: ["activity", "getThreadSubscriptionForAuthenticatedUser"] + }], + getThreadSubscriptionForAuthenticatedUser: ["GET /notifications/threads/{thread_id}/subscription"], + listEventsForAuthenticatedUser: ["GET /users/{username}/events"], + listEventsForOrg: ["GET /users/{username}/events/orgs/{org}", {}, { + renamed: ["activity", "listOrgEventsForAuthenticatedUser"] + }], + listEventsForUser: ["GET /users/{username}/events", {}, { + renamed: ["activity", "listEventsForAuthenticatedUser"] + }], + listFeeds: ["GET /feeds", {}, { + renamed: ["activity", "getFeeds"] + }], + listNotifications: ["GET /notifications", {}, { + renamed: ["activity", "listNotificationsForAuthenticatedUser"] + }], + listNotificationsForAuthenticatedUser: ["GET /notifications"], + listNotificationsForRepo: ["GET /repos/{owner}/{repo}/notifications", {}, { + renamed: ["activity", "listRepoNotificationsForAuthenticatedUser"] + }], + listOrgEventsForAuthenticatedUser: ["GET /users/{username}/events/orgs/{org}"], + listPublicEvents: ["GET /events"], + listPublicEventsForOrg: ["GET /orgs/{org}/events", {}, { + renamed: ["activity", "listPublicOrgEvents"] + }], + listPublicEventsForRepoNetwork: ["GET /networks/{owner}/{repo}/events"], + listPublicEventsForUser: ["GET /users/{username}/events/public"], + listPublicOrgEvents: ["GET /orgs/{org}/events"], + listReceivedEventsForUser: ["GET /users/{username}/received_events"], + listReceivedPublicEventsForUser: ["GET /users/{username}/received_events/public"], + listRepoEvents: ["GET /repos/{owner}/{repo}/events"], + listRepoNotificationsForAuthenticatedUser: ["GET /repos/{owner}/{repo}/notifications"], + listReposStarredByAuthenticatedUser: ["GET /user/starred"], + listReposStarredByUser: ["GET /users/{username}/starred"], + listReposWatchedByUser: ["GET /users/{username}/subscriptions"], + listStargazersForRepo: ["GET /repos/{owner}/{repo}/stargazers"], + listWatchedReposForAuthenticatedUser: ["GET /user/subscriptions"], + listWatchersForRepo: ["GET /repos/{owner}/{repo}/subscribers"], + markAsRead: ["PUT /notifications", {}, { + renamed: ["activity", "markNotificationsAsRead"] + }], + markNotificationsAsRead: ["PUT /notifications"], + markNotificationsAsReadForRepo: ["PUT /repos/{owner}/{repo}/notifications", {}, { + renamed: ["activity", "markRepoNotificationsAsRead"] + }], + markRepoNotificationsAsRead: ["PUT /repos/{owner}/{repo}/notifications"], + markThreadAsRead: ["PATCH /notifications/threads/{thread_id}"], + setRepoSubscription: ["PUT /repos/{owner}/{repo}/subscription"], + setThreadSubscription: ["PUT /notifications/threads/{thread_id}/subscription"], + starRepo: ["PUT /user/starred/{owner}/{repo}", {}, { + renamed: ["activity", "starRepoForAuthenticatedUser"] + }], + starRepoForAuthenticatedUser: ["PUT /user/starred/{owner}/{repo}"], + unstarRepo: ["DELETE /user/starred/{owner}/{repo}", {}, { + renamed: ["activity", "unstarRepoForAuthenticatedUser"] + }], + unstarRepoForAuthenticatedUser: ["DELETE /user/starred/{owner}/{repo}"] + }, + apps: { + addRepoToInstallation: ["PUT /user/installations/{installation_id}/repositories/{repository_id}", { + mediaType: { + previews: ["machine-man"] + } + }], + checkAccountIsAssociatedWithAny: ["GET /marketplace_listing/accounts/{account_id}", {}, { + renamed: ["apps", "getSubscriptionPlanForAccount"] + }], + checkAccountIsAssociatedWithAnyStubbed: ["GET /marketplace_listing/stubbed/accounts/{account_id}", {}, { + renamed: ["apps", "getSubscriptionPlanForAccountStubbed"] + }], + checkToken: ["POST /applications/{client_id}/token"], + createContentAttachment: ["POST /content_references/{content_reference_id}/attachments", { + mediaType: { + previews: ["corsair"] + } + }], + createFromManifest: ["POST /app-manifests/{code}/conversions"], + createInstallationAccessToken: ["POST /app/installations/{installation_id}/access_tokens", { + mediaType: { + previews: ["machine-man"] + } + }], + createInstallationToken: ["POST /app/installations/{installation_id}/access_tokens", { + mediaType: { + previews: ["machine-man"] + } + }, { + renamed: ["apps", "createInstallationAccessToken"] + }], + deleteAuthorization: ["DELETE /applications/{client_id}/grant"], + deleteInstallation: ["DELETE /app/installations/{installation_id}", { + mediaType: { + previews: ["machine-man"] + } + }], + deleteToken: ["DELETE /applications/{client_id}/token"], + getAuthenticated: ["GET /app", { + mediaType: { + previews: ["machine-man"] + } + }], + getBySlug: ["GET /apps/{app_slug}", { + mediaType: { + previews: ["machine-man"] + } + }], + getInstallation: ["GET /app/installations/{installation_id}", { + mediaType: { + previews: ["machine-man"] + } + }], + getOrgInstallation: ["GET /orgs/{org}/installation", { + mediaType: { + previews: ["machine-man"] + } + }], + getRepoInstallation: ["GET /repos/{owner}/{repo}/installation", { + mediaType: { + previews: ["machine-man"] + } + }], + getSubscriptionPlanForAccount: ["GET /marketplace_listing/accounts/{account_id}"], + getSubscriptionPlanForAccountStubbed: ["GET /marketplace_listing/stubbed/accounts/{account_id}"], + getUserInstallation: ["GET /users/{username}/installation", { + mediaType: { + previews: ["machine-man"] + } + }], + listAccountsForPlan: ["GET /marketplace_listing/plans/{plan_id}/accounts"], + listAccountsForPlanStubbed: ["GET /marketplace_listing/stubbed/plans/{plan_id}/accounts"], + listAccountsUserOrOrgOnPlan: ["GET /marketplace_listing/plans/{plan_id}/accounts", {}, { + renamed: ["apps", "listAccountsForPlan"] + }], + listAccountsUserOrOrgOnPlanStubbed: ["GET /marketplace_listing/stubbed/plans/{plan_id}/accounts", {}, { + renamed: ["apps", "listAccountsForPlanStubbed"] + }], + listInstallationReposForAuthenticatedUser: ["GET /user/installations/{installation_id}/repositories", { + mediaType: { + previews: ["machine-man"] + } + }], + listInstallations: ["GET /app/installations", { + mediaType: { + previews: ["machine-man"] + } + }], + listInstallationsForAuthenticatedUser: ["GET /user/installations", { + mediaType: { + previews: ["machine-man"] + } + }], + listMarketplacePurchasesForAuthenticatedUser: ["GET /user/marketplace_purchases", {}, { + renamed: ["apps", "listSubscriptionsForAuthenticatedUser"] + }], + listMarketplacePurchasesForAuthenticatedUserStubbed: ["GET /user/marketplace_purchases/stubbed", {}, { + renamed: ["apps", "listSubscriptionsForAuthenticatedUserStubbed"] + }], + listPlans: ["GET /marketplace_listing/plans"], + listPlansStubbed: ["GET /marketplace_listing/stubbed/plans"], + listRepos: ["GET /installation/repositories", { + mediaType: { + previews: ["machine-man"] + } + }, { + renamed: ["apps", "listReposAccessibleToInstallation"] + }], + listReposAccessibleToInstallation: ["GET /installation/repositories", { + mediaType: { + previews: ["machine-man"] + } + }], + listSubscriptionsForAuthenticatedUser: ["GET /user/marketplace_purchases"], + listSubscriptionsForAuthenticatedUserStubbed: ["GET /user/marketplace_purchases/stubbed"], + removeRepoFromInstallation: ["DELETE /user/installations/{installation_id}/repositories/{repository_id}", { + mediaType: { + previews: ["machine-man"] + } + }], + resetToken: ["PATCH /applications/{client_id}/token"], + revokeInstallationAccessToken: ["DELETE /installation/token"], + revokeInstallationToken: ["DELETE /installation/token", {}, { + renamed: ["apps", "revokeInstallationAccessToken"] + }], + suspendInstallation: ["PUT /app/installations/{installation_id}/suspended"], + unsuspendInstallation: ["DELETE /app/installations/{installation_id}/suspended"] + }, + checks: { + create: ["POST /repos/{owner}/{repo}/check-runs", { + mediaType: { + previews: ["antiope"] + } + }], + createSuite: ["POST /repos/{owner}/{repo}/check-suites", { + mediaType: { + previews: ["antiope"] + } + }], + get: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}", { + mediaType: { + previews: ["antiope"] + } + }], + getSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}", { + mediaType: { + previews: ["antiope"] + } + }], + listAnnotations: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations", { + mediaType: { + previews: ["antiope"] + } + }], + listForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-runs", { + mediaType: { + previews: ["antiope"] + } + }], + listForSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs", { + mediaType: { + previews: ["antiope"] + } + }], + listSuitesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-suites", { + mediaType: { + previews: ["antiope"] + } + }], + rerequestSuite: ["POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest", { + mediaType: { + previews: ["antiope"] + } + }], + setSuitesPreferences: ["PATCH /repos/{owner}/{repo}/check-suites/preferences", { + mediaType: { + previews: ["antiope"] + } + }], + update: ["PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}", { + mediaType: { + previews: ["antiope"] + } + }] + }, + codeScanning: { + getAlert: ["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_id}"], + listAlertsForRepo: ["GET /repos/{owner}/{repo}/code-scanning/alerts"] + }, + codesOfConduct: { + getAllCodesOfConduct: ["GET /codes_of_conduct", { + mediaType: { + previews: ["scarlet-witch"] + } + }], + getConductCode: ["GET /codes_of_conduct/{key}", { + mediaType: { + previews: ["scarlet-witch"] + } + }], + getForRepo: ["GET /repos/{owner}/{repo}/community/code_of_conduct", { + mediaType: { + previews: ["scarlet-witch"] + } + }], + listConductCodes: ["GET /codes_of_conduct", { + mediaType: { + previews: ["scarlet-witch"] + } + }, { + renamed: ["codesOfConduct", "getAllCodesOfConduct"] + }] + }, + emojis: { + get: ["GET /emojis"] + }, + gists: { + checkIsStarred: ["GET /gists/{gist_id}/star"], + create: ["POST /gists"], + createComment: ["POST /gists/{gist_id}/comments"], + delete: ["DELETE /gists/{gist_id}"], + deleteComment: ["DELETE /gists/{gist_id}/comments/{comment_id}"], + fork: ["POST /gists/{gist_id}/forks"], + get: ["GET /gists/{gist_id}"], + getComment: ["GET /gists/{gist_id}/comments/{comment_id}"], + getRevision: ["GET /gists/{gist_id}/{sha}"], + list: ["GET /gists"], + listComments: ["GET /gists/{gist_id}/comments"], + listCommits: ["GET /gists/{gist_id}/commits"], + listForUser: ["GET /users/{username}/gists"], + listForks: ["GET /gists/{gist_id}/forks"], + listPublic: ["GET /gists/public"], + listPublicForUser: ["GET /users/{username}/gists", {}, { + renamed: ["gists", "listForUser"] + }], + listStarred: ["GET /gists/starred"], + star: ["PUT /gists/{gist_id}/star"], + unstar: ["DELETE /gists/{gist_id}/star"], + update: ["PATCH /gists/{gist_id}"], + updateComment: ["PATCH /gists/{gist_id}/comments/{comment_id}"] + }, + git: { + createBlob: ["POST /repos/{owner}/{repo}/git/blobs"], + createCommit: ["POST /repos/{owner}/{repo}/git/commits"], + createRef: ["POST /repos/{owner}/{repo}/git/refs"], + createTag: ["POST /repos/{owner}/{repo}/git/tags"], + createTree: ["POST /repos/{owner}/{repo}/git/trees"], + deleteRef: ["DELETE /repos/{owner}/{repo}/git/refs/{ref}"], + getBlob: ["GET /repos/{owner}/{repo}/git/blobs/{file_sha}"], + getCommit: ["GET /repos/{owner}/{repo}/git/commits/{commit_sha}"], + getRef: ["GET /repos/{owner}/{repo}/git/ref/{ref}"], + getTag: ["GET /repos/{owner}/{repo}/git/tags/{tag_sha}"], + getTree: ["GET /repos/{owner}/{repo}/git/trees/{tree_sha}"], + listMatchingRefs: ["GET /repos/{owner}/{repo}/git/matching-refs/{ref}"], + updateRef: ["PATCH /repos/{owner}/{repo}/git/refs/{ref}"] + }, + gitignore: { + getAllTemplates: ["GET /gitignore/templates"], + getTemplate: ["GET /gitignore/templates/{name}"], + listTemplates: ["GET /gitignore/templates", {}, { + renamed: ["gitignore", "getAllTemplates"] + }] + }, + interactions: { + addOrUpdateRestrictionsForOrg: ["PUT /orgs/{org}/interaction-limits", { + mediaType: { + previews: ["sombra"] + } + }, { + renamed: ["interactions", "setRestrictionsForOrg"] + }], + addOrUpdateRestrictionsForRepo: ["PUT /repos/{owner}/{repo}/interaction-limits", { + mediaType: { + previews: ["sombra"] + } + }, { + renamed: ["interactions", "setRestrictionsForRepo"] + }], + getRestrictionsForOrg: ["GET /orgs/{org}/interaction-limits", { + mediaType: { + previews: ["sombra"] + } + }], + getRestrictionsForRepo: ["GET /repos/{owner}/{repo}/interaction-limits", { + mediaType: { + previews: ["sombra"] + } + }], + removeRestrictionsForOrg: ["DELETE /orgs/{org}/interaction-limits", { + mediaType: { + previews: ["sombra"] + } + }], + removeRestrictionsForRepo: ["DELETE /repos/{owner}/{repo}/interaction-limits", { + mediaType: { + previews: ["sombra"] + } + }], + setRestrictionsForOrg: ["PUT /orgs/{org}/interaction-limits", { + mediaType: { + previews: ["sombra"] + } + }], + setRestrictionsForRepo: ["PUT /repos/{owner}/{repo}/interaction-limits", { + mediaType: { + previews: ["sombra"] + } + }] + }, + issues: { + addAssignees: ["POST /repos/{owner}/{repo}/issues/{issue_number}/assignees"], + addLabels: ["POST /repos/{owner}/{repo}/issues/{issue_number}/labels"], + checkAssignee: ["GET /repos/{owner}/{repo}/assignees/{assignee}", {}, { + renamed: ["issues", "checkUserCanBeAssigned"] + }], + checkUserCanBeAssigned: ["GET /repos/{owner}/{repo}/assignees/{assignee}"], + create: ["POST /repos/{owner}/{repo}/issues"], + createComment: ["POST /repos/{owner}/{repo}/issues/{issue_number}/comments"], + createLabel: ["POST /repos/{owner}/{repo}/labels"], + createMilestone: ["POST /repos/{owner}/{repo}/milestones"], + deleteComment: ["DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}"], + deleteLabel: ["DELETE /repos/{owner}/{repo}/labels/{name}"], + deleteMilestone: ["DELETE /repos/{owner}/{repo}/milestones/{milestone_number}"], + get: ["GET /repos/{owner}/{repo}/issues/{issue_number}"], + getComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}"], + getEvent: ["GET /repos/{owner}/{repo}/issues/events/{event_id}"], + getLabel: ["GET /repos/{owner}/{repo}/labels/{name}"], + getMilestone: ["GET /repos/{owner}/{repo}/milestones/{milestone_number}"], + list: ["GET /issues"], + listAssignees: ["GET /repos/{owner}/{repo}/assignees"], + listComments: ["GET /repos/{owner}/{repo}/issues/{issue_number}/comments"], + listCommentsForRepo: ["GET /repos/{owner}/{repo}/issues/comments"], + listEvents: ["GET /repos/{owner}/{repo}/issues/{issue_number}/events"], + listEventsForRepo: ["GET /repos/{owner}/{repo}/issues/events"], + listEventsForTimeline: ["GET /repos/{owner}/{repo}/issues/{issue_number}/timeline", { + mediaType: { + previews: ["mockingbird"] + } + }], + listForAuthenticatedUser: ["GET /user/issues"], + listForOrg: ["GET /orgs/{org}/issues"], + listForRepo: ["GET /repos/{owner}/{repo}/issues"], + listLabelsForMilestone: ["GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels"], + listLabelsForRepo: ["GET /repos/{owner}/{repo}/labels"], + listLabelsOnIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/labels"], + listMilestones: ["GET /repos/{owner}/{repo}/milestones"], + listMilestonesForRepo: ["GET /repos/{owner}/{repo}/milestones", {}, { + renamed: ["issues", "listMilestones"] + }], + lock: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/lock"], + removeAllLabels: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels"], + removeAssignees: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees"], + removeLabel: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}"], + removeLabels: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels", {}, { + renamed: ["issues", "removeAllLabels"] + }], + replaceAllLabels: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/labels", {}, { + renamed: ["issues", "setLabels"] + }], + replaceLabels: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/labels", {}, { + renamed: ["issues", "replaceAllLabels"] + }], + setLabels: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/labels"], + unlock: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock"], + update: ["PATCH /repos/{owner}/{repo}/issues/{issue_number}"], + updateComment: ["PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}"], + updateLabel: ["PATCH /repos/{owner}/{repo}/labels/{name}"], + updateMilestone: ["PATCH /repos/{owner}/{repo}/milestones/{milestone_number}"] + }, + licenses: { + get: ["GET /licenses/{license}"], + getAllCommonlyUsed: ["GET /licenses"], + getForRepo: ["GET /repos/{owner}/{repo}/license"], + listCommonlyUsed: ["GET /licenses", {}, { + renamed: ["licenses", "getAllCommonlyUsed"] + }] + }, + markdown: { + render: ["POST /markdown"], + renderRaw: ["POST /markdown/raw", { + headers: { + "content-type": "text/plain; charset=utf-8" + } + }] + }, + meta: { + get: ["GET /meta"] + }, + migrations: { + cancelImport: ["DELETE /repos/{owner}/{repo}/import"], + deleteArchiveForAuthenticatedUser: ["DELETE /user/migrations/{migration_id}/archive", { + mediaType: { + previews: ["wyandotte"] + } + }], + deleteArchiveForOrg: ["DELETE /orgs/{org}/migrations/{migration_id}/archive", { + mediaType: { + previews: ["wyandotte"] + } + }], + downloadArchiveForOrg: ["GET /orgs/{org}/migrations/{migration_id}/archive", { + mediaType: { + previews: ["wyandotte"] + } + }], + getArchiveForAuthenticatedUser: ["GET /user/migrations/{migration_id}/archive", { + mediaType: { + previews: ["wyandotte"] + } + }], + getCommitAuthors: ["GET /repos/{owner}/{repo}/import/authors"], + getImportProgress: ["GET /repos/{owner}/{repo}/import", {}, { + renamed: ["migrations", "getImportStatus"] + }], + getImportStatus: ["GET /repos/{owner}/{repo}/import"], + getLargeFiles: ["GET /repos/{owner}/{repo}/import/large_files"], + getStatusForAuthenticatedUser: ["GET /user/migrations/{migration_id}", { + mediaType: { + previews: ["wyandotte"] + } + }], + getStatusForOrg: ["GET /orgs/{org}/migrations/{migration_id}", { + mediaType: { + previews: ["wyandotte"] + } + }], + listForAuthenticatedUser: ["GET /user/migrations", { + mediaType: { + previews: ["wyandotte"] + } + }], + listForOrg: ["GET /orgs/{org}/migrations", { + mediaType: { + previews: ["wyandotte"] + } + }], + listReposForOrg: ["GET /orgs/{org}/migrations/{migration_id}/repositories", { + mediaType: { + previews: ["wyandotte"] + } + }], + listReposForUser: ["GET /user/{migration_id}/repositories", { + mediaType: { + previews: ["wyandotte"] + } + }], + mapCommitAuthor: ["PATCH /repos/{owner}/{repo}/import/authors/{author_id}"], + setLfsPreference: ["PATCH /repos/{owner}/{repo}/import/lfs"], + startForAuthenticatedUser: ["POST /user/migrations"], + startForOrg: ["POST /orgs/{org}/migrations"], + startImport: ["PUT /repos/{owner}/{repo}/import"], + unlockRepoForAuthenticatedUser: ["DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock", { + mediaType: { + previews: ["wyandotte"] + } + }], + unlockRepoForOrg: ["DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock", { + mediaType: { + previews: ["wyandotte"] + } + }], + updateImport: ["PATCH /repos/{owner}/{repo}/import"] + }, + orgs: { + addOrUpdateMembership: ["PUT /orgs/{org}/memberships/{username}", {}, { + renamed: ["orgs", "setMembershipForUser"] + }], + blockUser: ["PUT /orgs/{org}/blocks/{username}"], + checkBlockedUser: ["GET /orgs/{org}/blocks/{username}"], + checkMembership: ["GET /orgs/{org}/members/{username}", {}, { + renamed: ["orgs", "checkMembershipForUser"] + }], + checkMembershipForUser: ["GET /orgs/{org}/members/{username}"], + checkPublicMembership: ["GET /orgs/{org}/public_members/{username}", {}, { + renamed: ["orgs", "checkPublicMembershipForUser"] + }], + checkPublicMembershipForUser: ["GET /orgs/{org}/public_members/{username}"], + concealMembership: ["DELETE /orgs/{org}/public_members/{username}", {}, { + renamed: ["orgs", "removePublicMembershipForAuthenticatedUser"] + }], + convertMemberToOutsideCollaborator: ["PUT /orgs/{org}/outside_collaborators/{username}"], + createHook: ["POST /orgs/{org}/hooks", {}, { + renamed: ["orgs", "createWebhook"] + }], + createInvitation: ["POST /orgs/{org}/invitations"], + createWebhook: ["POST /orgs/{org}/hooks"], + deleteHook: ["DELETE /orgs/{org}/hooks/{hook_id}", {}, { + renamed: ["orgs", "deleteWebhook"] + }], + deleteWebhook: ["DELETE /orgs/{org}/hooks/{hook_id}"], + get: ["GET /orgs/{org}"], + getHook: ["GET /orgs/{org}/hooks/{hook_id}", {}, { + renamed: ["orgs", "getWebhook"] + }], + getMembership: ["GET /orgs/{org}/memberships/{username}", {}, { + renamed: ["orgs", "getMembershipForUser"] + }], + getMembershipForAuthenticatedUser: ["GET /user/memberships/orgs/{org}"], + getMembershipForUser: ["GET /orgs/{org}/memberships/{username}"], + getWebhook: ["GET /orgs/{org}/hooks/{hook_id}"], + list: ["GET /organizations"], + listAppInstallations: ["GET /orgs/{org}/installations", { + mediaType: { + previews: ["machine-man"] + } + }], + listBlockedUsers: ["GET /orgs/{org}/blocks"], + listForAuthenticatedUser: ["GET /user/orgs"], + listForUser: ["GET /users/{username}/orgs"], + listHooks: ["GET /orgs/{org}/hooks", {}, { + renamed: ["orgs", "listWebhooks"] + }], + listInstallations: ["GET /orgs/{org}/installations", { + mediaType: { + previews: ["machine-man"] + } + }, { + renamed: ["orgs", "listAppInstallations"] + }], + listInvitationTeams: ["GET /orgs/{org}/invitations/{invitation_id}/teams"], + listMembers: ["GET /orgs/{org}/members"], + listMemberships: ["GET /user/memberships/orgs", {}, { + renamed: ["orgs", "listMembershipsForAuthenticatedUser"] + }], + listMembershipsForAuthenticatedUser: ["GET /user/memberships/orgs"], + listOutsideCollaborators: ["GET /orgs/{org}/outside_collaborators"], + listPendingInvitations: ["GET /orgs/{org}/invitations"], + listPublicMembers: ["GET /orgs/{org}/public_members"], + listWebhooks: ["GET /orgs/{org}/hooks"], + pingHook: ["POST /orgs/{org}/hooks/{hook_id}/pings", {}, { + renamed: ["orgs", "pingWebhook"] + }], + pingWebhook: ["POST /orgs/{org}/hooks/{hook_id}/pings"], + publicizeMembership: ["PUT /orgs/{org}/public_members/{username}", {}, { + renamed: ["orgs", "setPublicMembershipForAuthenticatedUser"] + }], + removeMember: ["DELETE /orgs/{org}/members/{username}"], + removeMembership: ["DELETE /orgs/{org}/memberships/{username}", {}, { + renamed: ["orgs", "removeMembershipForUser"] + }], + removeMembershipForUser: ["DELETE /orgs/{org}/memberships/{username}"], + removeOutsideCollaborator: ["DELETE /orgs/{org}/outside_collaborators/{username}"], + removePublicMembershipForAuthenticatedUser: ["DELETE /orgs/{org}/public_members/{username}"], + setMembershipForUser: ["PUT /orgs/{org}/memberships/{username}"], + setPublicMembershipForAuthenticatedUser: ["PUT /orgs/{org}/public_members/{username}"], + unblockUser: ["DELETE /orgs/{org}/blocks/{username}"], + update: ["PATCH /orgs/{org}"], + updateHook: ["PATCH /orgs/{org}/hooks/{hook_id}", {}, { + renamed: ["orgs", "updateWebhook"] + }], + updateMembership: ["PATCH /user/memberships/orgs/{org}", {}, { + renamed: ["orgs", "updateMembershipForAuthenticatedUser"] + }], + updateMembershipForAuthenticatedUser: ["PATCH /user/memberships/orgs/{org}"], + updateWebhook: ["PATCH /orgs/{org}/hooks/{hook_id}"] + }, + projects: { + addCollaborator: ["PUT /projects/{project_id}/collaborators/{username}", { + mediaType: { + previews: ["inertia"] + } + }], + createCard: ["POST /projects/columns/{column_id}/cards", { + mediaType: { + previews: ["inertia"] + } + }], + createColumn: ["POST /projects/{project_id}/columns", { + mediaType: { + previews: ["inertia"] + } + }], + createForAuthenticatedUser: ["POST /user/projects", { + mediaType: { + previews: ["inertia"] + } + }], + createForOrg: ["POST /orgs/{org}/projects", { + mediaType: { + previews: ["inertia"] + } + }], + createForRepo: ["POST /repos/{owner}/{repo}/projects", { + mediaType: { + previews: ["inertia"] + } + }], + delete: ["DELETE /projects/{project_id}", { + mediaType: { + previews: ["inertia"] + } + }], + deleteCard: ["DELETE /projects/columns/cards/{card_id}", { + mediaType: { + previews: ["inertia"] + } + }], + deleteColumn: ["DELETE /projects/columns/{column_id}", { + mediaType: { + previews: ["inertia"] + } + }], + get: ["GET /projects/{project_id}", { + mediaType: { + previews: ["inertia"] + } + }], + getCard: ["GET /projects/columns/cards/{card_id}", { + mediaType: { + previews: ["inertia"] + } + }], + getColumn: ["GET /projects/columns/{column_id}", { + mediaType: { + previews: ["inertia"] + } + }], + getPermissionForUser: ["GET /projects/{project_id}/collaborators/{username}/permission", { + mediaType: { + previews: ["inertia"] + } + }], + listCards: ["GET /projects/columns/{column_id}/cards", { + mediaType: { + previews: ["inertia"] + } + }], + listCollaborators: ["GET /projects/{project_id}/collaborators", { + mediaType: { + previews: ["inertia"] + } + }], + listColumns: ["GET /projects/{project_id}/columns", { + mediaType: { + previews: ["inertia"] + } + }], + listForOrg: ["GET /orgs/{org}/projects", { + mediaType: { + previews: ["inertia"] + } + }], + listForRepo: ["GET /repos/{owner}/{repo}/projects", { + mediaType: { + previews: ["inertia"] + } + }], + listForUser: ["GET /users/{username}/projects", { + mediaType: { + previews: ["inertia"] + } + }], + moveCard: ["POST /projects/columns/cards/{card_id}/moves", { + mediaType: { + previews: ["inertia"] + } + }], + moveColumn: ["POST /projects/columns/{column_id}/moves", { + mediaType: { + previews: ["inertia"] + } + }], + removeCollaborator: ["DELETE /projects/{project_id}/collaborators/{username}", { + mediaType: { + previews: ["inertia"] + } + }], + reviewUserPermissionLevel: ["GET /projects/{project_id}/collaborators/{username}/permission", { + mediaType: { + previews: ["inertia"] + } + }, { + renamed: ["projects", "getPermissionForUser"] + }], + update: ["PATCH /projects/{project_id}", { + mediaType: { + previews: ["inertia"] + } + }], + updateCard: ["PATCH /projects/columns/cards/{card_id}", { + mediaType: { + previews: ["inertia"] + } + }], + updateColumn: ["PATCH /projects/columns/{column_id}", { + mediaType: { + previews: ["inertia"] + } + }] + }, + pulls: { + checkIfMerged: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/merge"], + create: ["POST /repos/{owner}/{repo}/pulls"], + createComment: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/comments", {}, { + renamed: ["pulls", "createReviewComment"] + }], + createReplyForReviewComment: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies"], + createReview: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], + createReviewComment: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/comments"], + createReviewCommentReply: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies", {}, { + renamed: ["pulls", "createReplyForReviewComment"] + }], + createReviewRequest: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers", {}, { + renamed: ["pulls", "requestReviewers"] + }], + deleteComment: ["DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}", {}, { + renamed: ["pulls", "deleteReviewComment"] + }], + deletePendingReview: ["DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"], + deleteReviewComment: ["DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}"], + deleteReviewRequest: ["DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers", {}, { + renamed: ["pulls", "removeRequestedReviewers"] + }], + dismissReview: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals"], + get: ["GET /repos/{owner}/{repo}/pulls/{pull_number}"], + getComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}", {}, { + renamed: ["pulls", "getReviewComment"] + }], + getCommentsForReview: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments", {}, { + renamed: ["pulls", "listCommentsForReview"] + }], + getReview: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"], + getReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}"], + list: ["GET /repos/{owner}/{repo}/pulls"], + listComments: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/comments", {}, { + renamed: ["pulls", "listReviewComments"] + }], + listCommentsForRepo: ["GET /repos/{owner}/{repo}/pulls/comments", {}, { + renamed: ["pulls", "listReviewCommentsForRepo"] + }], + listCommentsForReview: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments"], + listCommits: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/commits"], + listFiles: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/files"], + listRequestedReviewers: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"], + listReviewComments: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/comments"], + listReviewCommentsForRepo: ["GET /repos/{owner}/{repo}/pulls/comments"], + listReviewRequests: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers", {}, { + renamed: ["pulls", "listRequestedReviewers"] + }], + listReviews: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], + merge: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge"], + removeRequestedReviewers: ["DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"], + requestReviewers: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"], + submitReview: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events"], + update: ["PATCH /repos/{owner}/{repo}/pulls/{pull_number}"], + updateBranch: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch", { + mediaType: { + previews: ["lydian"] + } + }], + updateComment: ["PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}", {}, { + renamed: ["pulls", "updateReviewComment"] + }], + updateReview: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"], + updateReviewComment: ["PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}"] + }, + rateLimit: { + get: ["GET /rate_limit"] + }, + reactions: { + createForCommitComment: ["POST /repos/{owner}/{repo}/comments/{comment_id}/reactions", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + createForIssue: ["POST /repos/{owner}/{repo}/issues/{issue_number}/reactions", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + createForIssueComment: ["POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + createForPullRequestReviewComment: ["POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + createForTeamDiscussionCommentInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + createForTeamDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + delete: ["DELETE /reactions/{reaction_id}", { + mediaType: { + previews: ["squirrel-girl"] + } + }, { + renamed: ["reactions", "deleteLegacy"] + }], + deleteForCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + deleteForIssue: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + deleteForIssueComment: ["DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + deleteForPullRequestComment: ["DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + deleteForTeamDiscussion: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + deleteForTeamDiscussionComment: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + deleteLegacy: ["DELETE /reactions/{reaction_id}", { + mediaType: { + previews: ["squirrel-girl"] + } + }, { + deprecated: "octokit.reactions.deleteLegacy() is deprecated, see https://developer.github.com/v3/reactions/#delete-a-reaction-legacy" + }], + listForCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}/reactions", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + listForIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/reactions", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + listForIssueComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + listForPullRequestReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + listForTeamDiscussionCommentInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions", { + mediaType: { + previews: ["squirrel-girl"] + } + }], + listForTeamDiscussionInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions", { + mediaType: { + previews: ["squirrel-girl"] + } + }] + }, + repos: { + acceptInvitation: ["PATCH /user/repository_invitations/{invitation_id}"], + addAppAccessRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, { + mapToData: "apps" + }], + addCollaborator: ["PUT /repos/{owner}/{repo}/collaborators/{username}"], + addDeployKey: ["POST /repos/{owner}/{repo}/keys", {}, { + renamed: ["repos", "createDeployKey"] + }], + addProtectedBranchAdminEnforcement: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins", {}, { + renamed: ["repos", "setAdminBranchProtection"] + }], + addProtectedBranchAppRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, { + mapToData: "apps", + renamed: ["repos", "addAppAccessRestrictions"] + }], + addProtectedBranchRequiredSignatures: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures", { + mediaType: { + previews: ["zzzax"] + } + }, { + renamed: ["repos", "createCommitSignatureProtection"] + }], + addProtectedBranchRequiredStatusChecksContexts: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, { + mapToData: "contexts", + renamed: ["repos", "addStatusCheckContexts"] + }], + addProtectedBranchTeamRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, { + mapToData: "teams", + renamed: ["repos", "addTeamAccessRestrictions"] + }], + addProtectedBranchUserRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, { + mapToData: "users", + renamed: ["repos", "addUserAccessRestrictions"] + }], + addStatusCheckContexts: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, { + mapToData: "contexts" + }], + addTeamAccessRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, { + mapToData: "teams" + }], + addUserAccessRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, { + mapToData: "users" + }], + checkCollaborator: ["GET /repos/{owner}/{repo}/collaborators/{username}"], + checkVulnerabilityAlerts: ["GET /repos/{owner}/{repo}/vulnerability-alerts", { + mediaType: { + previews: ["dorian"] + } + }], + compareCommits: ["GET /repos/{owner}/{repo}/compare/{base}...{head}"], + createCommitComment: ["POST /repos/{owner}/{repo}/commits/{commit_sha}/comments"], + createCommitSignatureProtection: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures", { + mediaType: { + previews: ["zzzax"] + } + }], + createCommitStatus: ["POST /repos/{owner}/{repo}/statuses/{sha}"], + createDeployKey: ["POST /repos/{owner}/{repo}/keys"], + createDeployment: ["POST /repos/{owner}/{repo}/deployments"], + createDeploymentStatus: ["POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"], + createDispatchEvent: ["POST /repos/{owner}/{repo}/dispatches"], + createForAuthenticatedUser: ["POST /user/repos"], + createFork: ["POST /repos/{owner}/{repo}/forks"], + createHook: ["POST /repos/{owner}/{repo}/hooks", {}, { + renamed: ["repos", "createWebhook"] + }], + createInOrg: ["POST /orgs/{org}/repos"], + createOrUpdateFile: ["PUT /repos/{owner}/{repo}/contents/{path}", {}, { + renamed: ["repos", "createOrUpdateFileContents"] + }], + createOrUpdateFileContents: ["PUT /repos/{owner}/{repo}/contents/{path}"], + createPagesSite: ["POST /repos/{owner}/{repo}/pages", { + mediaType: { + previews: ["switcheroo"] + } + }], + createRelease: ["POST /repos/{owner}/{repo}/releases"], + createStatus: ["POST /repos/{owner}/{repo}/statuses/{sha}", {}, { + renamed: ["repos", "createCommitStatus"] + }], + createUsingTemplate: ["POST /repos/{template_owner}/{template_repo}/generate", { + mediaType: { + previews: ["baptiste"] + } + }], + createWebhook: ["POST /repos/{owner}/{repo}/hooks"], + declineInvitation: ["DELETE /user/repository_invitations/{invitation_id}"], + delete: ["DELETE /repos/{owner}/{repo}"], + deleteAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions"], + deleteAdminBranchProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"], + deleteBranchProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection"], + deleteCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}"], + deleteCommitSignatureProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures", { + mediaType: { + previews: ["zzzax"] + } + }], + deleteDeployKey: ["DELETE /repos/{owner}/{repo}/keys/{key_id}"], + deleteDeployment: ["DELETE /repos/{owner}/{repo}/deployments/{deployment_id}"], + deleteDownload: ["DELETE /repos/{owner}/{repo}/downloads/{download_id}"], + deleteFile: ["DELETE /repos/{owner}/{repo}/contents/{path}"], + deleteHook: ["DELETE /repos/{owner}/{repo}/hooks/{hook_id}", {}, { + renamed: ["repos", "deleteWebhook"] + }], + deleteInvitation: ["DELETE /repos/{owner}/{repo}/invitations/{invitation_id}"], + deletePagesSite: ["DELETE /repos/{owner}/{repo}/pages", { + mediaType: { + previews: ["switcheroo"] + } + }], + deletePullRequestReviewProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"], + deleteRelease: ["DELETE /repos/{owner}/{repo}/releases/{release_id}"], + deleteReleaseAsset: ["DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}"], + deleteWebhook: ["DELETE /repos/{owner}/{repo}/hooks/{hook_id}"], + disableAutomatedSecurityFixes: ["DELETE /repos/{owner}/{repo}/automated-security-fixes", { + mediaType: { + previews: ["london"] + } + }], + disablePagesSite: ["DELETE /repos/{owner}/{repo}/pages", { + mediaType: { + previews: ["switcheroo"] + } + }, { + renamed: ["repos", "deletePagesSite"] + }], + disableVulnerabilityAlerts: ["DELETE /repos/{owner}/{repo}/vulnerability-alerts", { + mediaType: { + previews: ["dorian"] + } + }], + downloadArchive: ["GET /repos/{owner}/{repo}/{archive_format}/{ref}"], + enableAutomatedSecurityFixes: ["PUT /repos/{owner}/{repo}/automated-security-fixes", { + mediaType: { + previews: ["london"] + } + }], + enablePagesSite: ["POST /repos/{owner}/{repo}/pages", { + mediaType: { + previews: ["switcheroo"] + } + }, { + renamed: ["repos", "createPagesSite"] + }], + enableVulnerabilityAlerts: ["PUT /repos/{owner}/{repo}/vulnerability-alerts", { + mediaType: { + previews: ["dorian"] + } + }], + get: ["GET /repos/{owner}/{repo}"], + getAccessRestrictions: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions"], + getAdminBranchProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"], + getAllStatusCheckContexts: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts"], + getAllTopics: ["GET /repos/{owner}/{repo}/topics", { + mediaType: { + previews: ["mercy"] + } + }], + getAppsWithAccessToProtectedBranch: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps"], + getArchiveLink: ["GET /repos/{owner}/{repo}/{archive_format}/{ref}", {}, { + renamed: ["repos", "downloadArchive"] + }], + getBranch: ["GET /repos/{owner}/{repo}/branches/{branch}"], + getBranchProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection"], + getClones: ["GET /repos/{owner}/{repo}/traffic/clones"], + getCodeFrequencyStats: ["GET /repos/{owner}/{repo}/stats/code_frequency"], + getCollaboratorPermissionLevel: ["GET /repos/{owner}/{repo}/collaborators/{username}/permission"], + getCombinedStatusForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/status"], + getCommit: ["GET /repos/{owner}/{repo}/commits/{ref}"], + getCommitActivityStats: ["GET /repos/{owner}/{repo}/stats/commit_activity"], + getCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}"], + getCommitSignatureProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures", { + mediaType: { + previews: ["zzzax"] + } + }], + getCommunityProfileMetrics: ["GET /repos/{owner}/{repo}/community/profile"], + getContent: ["GET /repos/{owner}/{repo}/contents/{path}"], + getContents: ["GET /repos/{owner}/{repo}/contents/{path}", {}, { + renamed: ["repos", "getContent"] + }], + getContributorsStats: ["GET /repos/{owner}/{repo}/stats/contributors"], + getDeployKey: ["GET /repos/{owner}/{repo}/keys/{key_id}"], + getDeployment: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}"], + getDeploymentStatus: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}"], + getDownload: ["GET /repos/{owner}/{repo}/downloads/{download_id}"], + getHook: ["GET /repos/{owner}/{repo}/hooks/{hook_id}", {}, { + renamed: ["repos", "getWebhook"] + }], + getLatestPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/latest"], + getLatestRelease: ["GET /repos/{owner}/{repo}/releases/latest"], + getPages: ["GET /repos/{owner}/{repo}/pages"], + getPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/{build_id}"], + getParticipationStats: ["GET /repos/{owner}/{repo}/stats/participation"], + getProtectedBranchAdminEnforcement: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins", {}, { + renamed: ["repos", "getAdminBranchProtection"] + }], + getProtectedBranchPullRequestReviewEnforcement: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews", {}, { + renamed: ["repos", "getPullRequestReviewProtection"] + }], + getProtectedBranchRequiredSignatures: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures", { + mediaType: { + previews: ["zzzax"] + } + }, { + renamed: ["repos", "getCommitSignatureProtection"] + }], + getProtectedBranchRequiredStatusChecks: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks", {}, { + renamed: ["repos", "getStatusChecksProtection"] + }], + getProtectedBranchRestrictions: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions", {}, { + renamed: ["repos", "getAccessRestrictions"] + }], + getPullRequestReviewProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"], + getPunchCardStats: ["GET /repos/{owner}/{repo}/stats/punch_card"], + getReadme: ["GET /repos/{owner}/{repo}/readme"], + getRelease: ["GET /repos/{owner}/{repo}/releases/{release_id}"], + getReleaseAsset: ["GET /repos/{owner}/{repo}/releases/assets/{asset_id}"], + getReleaseByTag: ["GET /repos/{owner}/{repo}/releases/tags/{tag}"], + getStatusChecksProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"], + getTeamsWithAccessToProtectedBranch: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams"], + getTopPaths: ["GET /repos/{owner}/{repo}/traffic/popular/paths"], + getTopReferrers: ["GET /repos/{owner}/{repo}/traffic/popular/referrers"], + getUsersWithAccessToProtectedBranch: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users"], + getViews: ["GET /repos/{owner}/{repo}/traffic/views"], + getWebhook: ["GET /repos/{owner}/{repo}/hooks/{hook_id}"], + list: ["GET /user/repos", {}, { + renamed: ["repos", "listForAuthenticatedUser"] + }], + listAssetsForRelease: ["GET /repos/{owner}/{repo}/releases/{release_id}/assets", {}, { + renamed: ["repos", "listReleaseAssets"] + }], + listBranches: ["GET /repos/{owner}/{repo}/branches"], + listBranchesForHeadCommit: ["GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head", { + mediaType: { + previews: ["groot"] + } + }], + listCollaborators: ["GET /repos/{owner}/{repo}/collaborators"], + listCommentsForCommit: ["GET /repos/{owner}/{repo}/commits/{commit_sha}/comments"], + listCommitComments: ["GET /repos/{owner}/{repo}/comments", {}, { + renamed: ["repos", "listCommitCommentsForRepo"] + }], + listCommitCommentsForRepo: ["GET /repos/{owner}/{repo}/comments"], + listCommitStatusesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/statuses"], + listCommits: ["GET /repos/{owner}/{repo}/commits"], + listContributors: ["GET /repos/{owner}/{repo}/contributors"], + listDeployKeys: ["GET /repos/{owner}/{repo}/keys"], + listDeploymentStatuses: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"], + listDeployments: ["GET /repos/{owner}/{repo}/deployments"], + listDownloads: ["GET /repos/{owner}/{repo}/downloads"], + listForAuthenticatedUser: ["GET /user/repos"], + listForOrg: ["GET /orgs/{org}/repos"], + listForUser: ["GET /users/{username}/repos"], + listForks: ["GET /repos/{owner}/{repo}/forks"], + listHooks: ["GET /repos/{owner}/{repo}/hooks", {}, { + renamed: ["repos", "listWebhooks"] + }], + listInvitations: ["GET /repos/{owner}/{repo}/invitations"], + listInvitationsForAuthenticatedUser: ["GET /user/repository_invitations"], + listLanguages: ["GET /repos/{owner}/{repo}/languages"], + listPagesBuilds: ["GET /repos/{owner}/{repo}/pages/builds"], + listProtectedBranchRequiredStatusChecksContexts: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, { + renamed: ["repos", "getAllStatusCheckContexts"] + }], + listPublic: ["GET /repositories"], + listPullRequestsAssociatedWithCommit: ["GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls", { + mediaType: { + previews: ["groot"] + } + }], + listReleaseAssets: ["GET /repos/{owner}/{repo}/releases/{release_id}/assets"], + listReleases: ["GET /repos/{owner}/{repo}/releases"], + listStatusesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/statuses", {}, { + renamed: ["repos", "listCommitStatusesForRef"] + }], + listTags: ["GET /repos/{owner}/{repo}/tags"], + listTeams: ["GET /repos/{owner}/{repo}/teams"], + listTopics: ["GET /repos/{owner}/{repo}/topics", { + mediaType: { + previews: ["mercy"] + } + }, { + renamed: ["repos", "getAllTopics"] + }], + listWebhooks: ["GET /repos/{owner}/{repo}/hooks"], + merge: ["POST /repos/{owner}/{repo}/merges"], + pingHook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/pings", {}, { + renamed: ["repos", "pingWebhook"] + }], + pingWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/pings"], + removeAppAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, { + mapToData: "apps" + }], + removeBranchProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection", {}, { + renamed: ["repos", "deleteBranchProtection"] + }], + removeCollaborator: ["DELETE /repos/{owner}/{repo}/collaborators/{username}"], + removeDeployKey: ["DELETE /repos/{owner}/{repo}/keys/{key_id}", {}, { + renamed: ["repos", "deleteDeployKey"] + }], + removeProtectedBranchAdminEnforcement: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins", {}, { + renamed: ["repos", "deleteAdminBranchProtection"] + }], + removeProtectedBranchAppRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, { + mapToData: "apps", + renamed: ["repos", "removeAppAccessRestrictions"] + }], + removeProtectedBranchPullRequestReviewEnforcement: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews", {}, { + renamed: ["repos", "deletePullRequestReviewProtection"] + }], + removeProtectedBranchRequiredSignatures: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures", { + mediaType: { + previews: ["zzzax"] + } + }, { + renamed: ["repos", "deleteCommitSignatureProtection"] + }], + removeProtectedBranchRequiredStatusChecks: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks", {}, { + renamed: ["repos", "removeStatusChecksProtection"] + }], + removeProtectedBranchRequiredStatusChecksContexts: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, { + mapToData: "contexts", + renamed: ["repos", "removeStatusCheckContexts"] + }], + removeProtectedBranchRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions", {}, { + renamed: ["repos", "deleteAccessRestrictions"] + }], + removeProtectedBranchTeamRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, { + mapToData: "teams", + renamed: ["repos", "removeTeamAccessRestrictions"] + }], + removeProtectedBranchUserRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, { + mapToData: "users", + renamed: ["repos", "removeUserAccessRestrictions"] + }], + removeStatusCheckContexts: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, { + mapToData: "contexts" + }], + removeStatusCheckProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"], + removeTeamAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, { + mapToData: "teams" + }], + removeUserAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, { + mapToData: "users" + }], + replaceAllTopics: ["PUT /repos/{owner}/{repo}/topics", { + mediaType: { + previews: ["mercy"] + } + }], + replaceProtectedBranchAppRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, { + mapToData: "apps", + renamed: ["repos", "setAppAccessRestrictions"] + }], + replaceProtectedBranchRequiredStatusChecksContexts: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, { + mapToData: "contexts", + renamed: ["repos", "setStatusCheckContexts"] + }], + replaceProtectedBranchTeamRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, { + mapToData: "teams", + renamed: ["repos", "setTeamAccessRestrictions"] + }], + replaceProtectedBranchUserRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, { + mapToData: "users", + renamed: ["repos", "setUserAccessRestrictions"] + }], + replaceTopics: ["PUT /repos/{owner}/{repo}/topics", { + mediaType: { + previews: ["mercy"] + } + }, { + renamed: ["repos", "replaceAllTopics"] + }], + requestPageBuild: ["POST /repos/{owner}/{repo}/pages/builds", {}, { + renamed: ["repos", "requestPagesBuild"] + }], + requestPagesBuild: ["POST /repos/{owner}/{repo}/pages/builds"], + retrieveCommunityProfileMetrics: ["GET /repos/{owner}/{repo}/community/profile", {}, { + renamed: ["repos", "getCommunityProfileMetrics"] + }], + setAdminBranchProtection: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"], + setAppAccessRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, { + mapToData: "apps" + }], + setStatusCheckContexts: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, { + mapToData: "contexts" + }], + setTeamAccessRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, { + mapToData: "teams" + }], + setUserAccessRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, { + mapToData: "users" + }], + testPushHook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/tests", {}, { + renamed: ["repos", "testPushWebhook"] + }], + testPushWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/tests"], + transfer: ["POST /repos/{owner}/{repo}/transfer"], + update: ["PATCH /repos/{owner}/{repo}"], + updateBranchProtection: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection"], + updateCommitComment: ["PATCH /repos/{owner}/{repo}/comments/{comment_id}"], + updateHook: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}", {}, { + renamed: ["repos", "updateWebhook"] + }], + updateInformationAboutPagesSite: ["PUT /repos/{owner}/{repo}/pages"], + updateInvitation: ["PATCH /repos/{owner}/{repo}/invitations/{invitation_id}"], + updateProtectedBranchPullRequestReviewEnforcement: ["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews", {}, { + renamed: ["repos", "updatePullRequestReviewProtection"] + }], + updateProtectedBranchRequiredStatusChecks: ["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks", {}, { + renamed: ["repos", "updateStatusChecksProtection"] + }], + updatePullRequestReviewProtection: ["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"], + updateRelease: ["PATCH /repos/{owner}/{repo}/releases/{release_id}"], + updateReleaseAsset: ["PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}"], + updateStatusCheckPotection: ["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"], + updateWebhook: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}"], + uploadReleaseAsset: ["POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}", { + baseUrl: "https://uploads.github.com" + }] + }, + search: { + code: ["GET /search/code"], + commits: ["GET /search/commits", { + mediaType: { + previews: ["cloak"] + } + }], + issuesAndPullRequests: ["GET /search/issues"], + labels: ["GET /search/labels"], + repos: ["GET /search/repositories"], + topics: ["GET /search/topics"], + users: ["GET /search/users"] + }, + teams: { + addOrUpdateMembershipForUserInOrg: ["PUT /orgs/{org}/teams/{team_slug}/memberships/{username}"], + addOrUpdateMembershipInOrg: ["PUT /orgs/{org}/teams/{team_slug}/memberships/{username}", {}, { + renamed: ["teams", "addOrUpdateMembershipForUserInOrg"] + }], + addOrUpdateProjectInOrg: ["PUT /orgs/{org}/teams/{team_slug}/projects/{project_id}", { + mediaType: { + previews: ["inertia"] + } + }, { + renamed: ["teams", "addOrUpdateProjectPermissionsInOrg"] + }], + addOrUpdateProjectPermissionsInOrg: ["PUT /orgs/{org}/teams/{team_slug}/projects/{project_id}", { + mediaType: { + previews: ["inertia"] + } + }], + addOrUpdateRepoInOrg: ["PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}", {}, { + renamed: ["teams", "addOrUpdateRepoPermissionsInOrg"] + }], + addOrUpdateRepoPermissionsInOrg: ["PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"], + checkManagesRepoInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}", {}, { + renamed: ["teams", "checkPermissionsForRepoInOrg"] + }], + checkPermissionsForProjectInOrg: ["GET /orgs/{org}/teams/{team_slug}/projects/{project_id}", { + mediaType: { + previews: ["inertia"] + } + }], + checkPermissionsForRepoInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"], + create: ["POST /orgs/{org}/teams"], + createDiscussionCommentInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments"], + createDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions"], + deleteDiscussionCommentInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"], + deleteDiscussionInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"], + deleteInOrg: ["DELETE /orgs/{org}/teams/{team_slug}"], + getByName: ["GET /orgs/{org}/teams/{team_slug}"], + getDiscussionCommentInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"], + getDiscussionInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"], + getMembershipForUserInOrg: ["GET /orgs/{org}/teams/{team_slug}/memberships/{username}"], + getMembershipInOrg: ["GET /orgs/{org}/teams/{team_slug}/memberships/{username}", {}, { + renamed: ["teams", "getMembershipForUserInOrg"] + }], + list: ["GET /orgs/{org}/teams"], + listChildInOrg: ["GET /orgs/{org}/teams/{team_slug}/teams"], + listDiscussionCommentsInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments"], + listDiscussionsInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions"], + listForAuthenticatedUser: ["GET /user/teams"], + listMembersInOrg: ["GET /orgs/{org}/teams/{team_slug}/members"], + listPendingInvitationsInOrg: ["GET /orgs/{org}/teams/{team_slug}/invitations"], + listProjectsInOrg: ["GET /orgs/{org}/teams/{team_slug}/projects", { + mediaType: { + previews: ["inertia"] + } + }], + listReposInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos"], + removeMembershipForUserInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}"], + removeMembershipInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}", {}, { + renamed: ["teams", "removeMembershipForUserInOrg"] + }], + removeProjectInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/projects/{project_id}"], + removeRepoInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"], + reviewProjectInOrg: ["GET /orgs/{org}/teams/{team_slug}/projects/{project_id}", { + mediaType: { + previews: ["inertia"] + } + }, { + renamed: ["teams", "checkPermissionsForProjectInOrg"] + }], + updateDiscussionCommentInOrg: ["PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"], + updateDiscussionInOrg: ["PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"], + updateInOrg: ["PATCH /orgs/{org}/teams/{team_slug}"] + }, + users: { + addEmailForAuthenticated: ["POST /user/emails"], + addEmails: ["POST /user/emails", {}, { + renamed: ["users", "addEmailsForAuthenticated"] + }], + block: ["PUT /user/blocks/{username}"], + checkBlocked: ["GET /user/blocks/{username}"], + checkFollowing: ["GET /user/following/{username}", {}, { + renamed: ["users", "checkPersonIsFollowedByAuthenticated"] + }], + checkFollowingForUser: ["GET /users/{username}/following/{target_user}"], + checkPersonIsFollowedByAuthenticated: ["GET /user/following/{username}"], + createGpgKey: ["POST /user/gpg_keys", {}, { + renamed: ["users", "createGpgKeyForAuthenticated"] + }], + createGpgKeyForAuthenticated: ["POST /user/gpg_keys"], + createPublicKey: ["POST /user/keys", {}, { + renamed: ["users", "createPublicSshKeyForAuthenticated"] + }], + createPublicSshKeyForAuthenticated: ["POST /user/keys"], + deleteEmailForAuthenticated: ["DELETE /user/emails"], + deleteEmails: ["DELETE /user/emails", {}, { + renamed: ["users", "deleteEmailsForAuthenticated"] + }], + deleteGpgKey: ["DELETE /user/gpg_keys/{gpg_key_id}", {}, { + renamed: ["users", "deleteGpgKeyForAuthenticated"] + }], + deleteGpgKeyForAuthenticated: ["DELETE /user/gpg_keys/{gpg_key_id}"], + deletePublicKey: ["DELETE /user/keys/{key_id}", {}, { + renamed: ["users", "deletePublicSshKeyForAuthenticated"] + }], + deletePublicSshKeyForAuthenticated: ["DELETE /user/keys/{key_id}"], + follow: ["PUT /user/following/{username}"], + getAuthenticated: ["GET /user"], + getByUsername: ["GET /users/{username}"], + getContextForUser: ["GET /users/{username}/hovercard"], + getGpgKey: ["GET /user/gpg_keys/{gpg_key_id}", {}, { + renamed: ["users", "getGpgKeyForAuthenticated"] + }], + getGpgKeyForAuthenticated: ["GET /user/gpg_keys/{gpg_key_id}"], + getPublicKey: ["GET /user/keys/{key_id}", {}, { + renamed: ["users", "getPublicSshKeyForAuthenticated"] + }], + getPublicSshKeyForAuthenticated: ["GET /user/keys/{key_id}"], + list: ["GET /users"], + listBlocked: ["GET /user/blocks", {}, { + renamed: ["users", "listBlockedByAuthenticated"] + }], + listBlockedByAuthenticated: ["GET /user/blocks"], + listEmails: ["GET /user/emails", {}, { + renamed: ["users", "listEmailsForAuthenticated"] + }], + listEmailsForAuthenticated: ["GET /user/emails"], + listFollowedByAuthenticated: ["GET /user/following"], + listFollowersForAuthenticatedUser: ["GET /user/followers"], + listFollowersForUser: ["GET /users/{username}/followers"], + listFollowingForAuthenticatedUser: ["GET /user/following", {}, { + renamed: ["users", "listFollowedByAuthenticated"] + }], + listFollowingForUser: ["GET /users/{username}/following"], + listGpgKeys: ["GET /user/gpg_keys", {}, { + renamed: ["users", "listGpgKeysForAuthenticated"] + }], + listGpgKeysForAuthenticated: ["GET /user/gpg_keys"], + listGpgKeysForUser: ["GET /users/{username}/gpg_keys"], + listPublicEmails: ["GET /user/public_emails", {}, { + renamed: ["users", "listPublicEmailsForAuthenticatedUser"] + }], + listPublicEmailsForAuthenticated: ["GET /user/public_emails"], + listPublicKeys: ["GET /user/keys", {}, { + renamed: ["users", "listPublicSshKeysForAuthenticated"] + }], + listPublicKeysForUser: ["GET /users/{username}/keys"], + listPublicSshKeysForAuthenticated: ["GET /user/keys"], + setPrimaryEmailVisibilityForAuthenticated: ["PATCH /user/email/visibility"], + togglePrimaryEmailVisibility: ["PATCH /user/email/visibility", {}, { + renamed: ["users", "setPrimaryEmailVisibilityForAuthenticated"] + }], + unblock: ["DELETE /user/blocks/{username}"], + unfollow: ["DELETE /user/following/{username}"], + updateAuthenticated: ["PATCH /user"] } - if (msAbs >= m) { - return plural(ms, msAbs, m, 'minute'); +}; + +const VERSION = "3.17.0"; + +function endpointsToMethods(octokit, endpointsMap) { + const newMethods = {}; + + for (const [scope, endpoints] of Object.entries(endpointsMap)) { + for (const [methodName, endpoint] of Object.entries(endpoints)) { + const [route, defaults, decorations] = endpoint; + const [method, url] = route.split(/ /); + const endpointDefaults = Object.assign({ + method, + url + }, defaults); + + if (!newMethods[scope]) { + newMethods[scope] = {}; + } + + const scopeMethods = newMethods[scope]; + + if (decorations) { + scopeMethods[methodName] = decorate(octokit, scope, methodName, endpointDefaults, decorations); + continue; + } + + scopeMethods[methodName] = octokit.request.defaults(endpointDefaults); + } } - if (msAbs >= s) { - return plural(ms, msAbs, s, 'second'); + + return newMethods; +} + +function decorate(octokit, scope, methodName, defaults, decorations) { + const requestWithDefaults = octokit.request.defaults(defaults); + + function withDecorations(...args) { + // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488 + let options = requestWithDefaults.endpoint.merge(...args); // There are currently no other decorations than `.mapToData` + + if (decorations.mapToData) { + options = Object.assign({}, options, { + data: options[decorations.mapToData], + [decorations.mapToData]: undefined + }); + return requestWithDefaults(options); + } // NOTE: there are currently no deprecations. But we keep the code + // below for future reference + + + if (decorations.renamed) { + const [newScope, newMethodName] = decorations.renamed; + octokit.log.warn(`octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()`); + } + + if (decorations.deprecated) { + octokit.log.warn(decorations.deprecated); + } + + if (decorations.renamedParameters) { + // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488 + const options = requestWithDefaults.endpoint.merge(...args); + + for (const [name, alias] of Object.entries(decorations.renamedParameters)) { + // There is currently no deprecated parameter that is optional, + // so we never hit the else branch below at this point. + + /* istanbul ignore else */ + if (name in options) { + octokit.log.warn(`"${name}" parameter is deprecated for "octokit.${scope}.${methodName}()". Use "${alias}" instead`); + + if (!(alias in options)) { + options[alias] = options[name]; + } + + delete options[name]; + } + } + + return requestWithDefaults(options); + } // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488 + + + return requestWithDefaults(...args); } - return ms + ' ms'; + + return Object.assign(withDecorations, requestWithDefaults); } /** - * Pluralization helper. + * This plugin is a 1:1 copy of internal @octokit/rest plugins. The primary + * goal is to rebuild @octokit/rest on top of @octokit/core. Once that is + * done, we will remove the registerEndpoints methods and return the methods + * directly as with the other plugins. At that point we will also remove the + * legacy workarounds and deprecations. + * + * See the plan at + * https://github.com/octokit/plugin-rest-endpoint-methods.js/pull/1 */ -function plural(ms, msAbs, n, name) { - var isPlural = msAbs >= n * 1.5; - return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); +function restEndpointMethods(octokit) { + return endpointsToMethods(octokit, Endpoints); } +restEndpointMethods.VERSION = VERSION; + +exports.restEndpointMethods = restEndpointMethods; +//# sourceMappingURL=index.js.map /***/ }), -/* 318 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { +/* 369 */, +/* 370 */ +/***/ (function(module, __unusedexports, __webpack_require__) { "use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const util_1 = __webpack_require__(104); -const utils_1 = __webpack_require__(200); -const redis_1 = __webpack_require__(837); -const debug = utils_1.Debug("cluster:subscriber"); -const SUBSCRIBER_CONNECTION_NAME = "ioredisClusterSubscriber"; -class ClusterSubscriber { - constructor(connectionPool, emitter) { - this.connectionPool = connectionPool; - this.emitter = emitter; - this.started = false; - this.subscriber = null; - this.connectionPool.on("-node", (_, key) => { - if (!this.started || !this.subscriber) { - return; - } - if (util_1.getNodeKey(this.subscriber.options) === key) { - debug("subscriber has left, selecting a new one..."); - this.selectSubscriber(); - } - }); - this.connectionPool.on("+node", () => { - if (!this.started || this.subscriber) { - return; - } - debug("a new node is discovered and there is no subscriber, selecting a new one..."); - this.selectSubscriber(); - }); - } - getInstance() { - return this.subscriber; - } - selectSubscriber() { - const lastActiveSubscriber = this.lastActiveSubscriber; - // Disconnect the previous subscriber even if there - // will not be a new one. - if (lastActiveSubscriber) { - lastActiveSubscriber.disconnect(); - } - const sampleNode = utils_1.sample(this.connectionPool.getNodes()); - if (!sampleNode) { - debug("selecting subscriber failed since there is no node discovered in the cluster yet"); - this.subscriber = null; - return; - } - const { options } = sampleNode; - debug("selected a subscriber %s:%s", options.host, options.port); - /* - * Create a specialized Redis connection for the subscription. - * Note that auto reconnection is enabled here. - * - * `enableReadyCheck` is also enabled because although subscription is allowed - * while redis is loading data from the disk, we can check if the password - * provided for the subscriber is correct, and if not, the current subscriber - * will be disconnected and a new subscriber will be selected. - */ - this.subscriber = new redis_1.default({ - port: options.port, - host: options.host, - username: options.username, - password: options.password, - enableReadyCheck: true, - connectionName: SUBSCRIBER_CONNECTION_NAME, - lazyConnect: true, - tls: options.tls, - }); - // Ignore the errors since they're handled in the connection pool. - this.subscriber.on("error", utils_1.noop); - // Re-subscribe previous channels - const previousChannels = { subscribe: [], psubscribe: [] }; - if (lastActiveSubscriber) { - const condition = lastActiveSubscriber.condition || lastActiveSubscriber.prevCondition; - if (condition && condition.subscriber) { - previousChannels.subscribe = condition.subscriber.channels("subscribe"); - previousChannels.psubscribe = condition.subscriber.channels("psubscribe"); - } - } - if (previousChannels.subscribe.length || - previousChannels.psubscribe.length) { - let pending = 0; - for (const type of ["subscribe", "psubscribe"]) { - const channels = previousChannels[type]; - if (channels.length) { - pending += 1; - debug("%s %d channels", type, channels.length); - this.subscriber[type](channels) - .then(() => { - if (!--pending) { - this.lastActiveSubscriber = this.subscriber; - } - }) - .catch(utils_1.noop); - } - } - } - else { - this.lastActiveSubscriber = this.subscriber; - } - for (const event of ["message", "messageBuffer"]) { - this.subscriber.on(event, (arg1, arg2) => { - this.emitter.emit(event, arg1, arg2); - }); - } - for (const event of ["pmessage", "pmessageBuffer"]) { - this.subscriber.on(event, (arg1, arg2, arg3) => { - this.emitter.emit(event, arg1, arg2, arg3); - }); - } - } - start() { - this.started = true; - this.selectSubscriber(); - debug("started"); - } - stop() { - this.started = false; - if (this.subscriber) { - this.subscriber.disconnect(); - this.subscriber = null; - } - debug("stopped"); - } -} -exports.default = ClusterSubscriber; +const path = __webpack_require__(622); +const fs = __webpack_require__(598); +const stripBom = __webpack_require__(572); +const parseJson = __webpack_require__(857); +const pify = __webpack_require__(281); + +const parse = (data, filePath, options = {}) => { + data = stripBom(data); + + if (typeof options.beforeParse === 'function') { + data = options.beforeParse(data); + } + + return parseJson(data, options.reviver, path.relative(process.cwd(), filePath)); +}; + +const loadJsonFile = (filePath, options) => pify(fs.readFile)(filePath, 'utf8').then(data => parse(data, filePath, options)); + +module.exports = loadJsonFile; +// TODO: Remove this for the next major release +module.exports.default = loadJsonFile; +module.exports.sync = (filePath, options) => parse(fs.readFileSync(filePath, 'utf8'), filePath, options); /***/ }), -/* 319 */ +/* 371 */ /***/ (function(module) { /** - * Helpers. + * Expose `pathtoRegexp`. */ -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var y = d * 365.25; +module.exports = pathtoRegexp; /** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public + * Match matching groups in a regular expression. */ - -module.exports = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isNaN(val) === false) { - return options.long ? fmtLong(val) : fmtShort(val); - } - throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) - ); -}; +var MATCHING_GROUP_REGEXP = /\((?!\?)/g; /** - * Parse the given `str` and return milliseconds. + * Normalize the given path string, + * returning a regular expression. * - * @param {String} str - * @return {Number} + * An empty array should be passed, + * which will contain the placeholder + * key names. For example "/user/:id" will + * then contain ["id"]. + * + * @param {String|RegExp|Array} path + * @param {Array} keys + * @param {Object} options + * @return {RegExp} * @api private */ -function parse(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; - } -} +function pathtoRegexp(path, keys, options) { + options = options || {}; + keys = keys || []; + var strict = options.strict; + var end = options.end !== false; + var flags = options.sensitive ? '' : 'i'; + var extraOffset = 0; + var keysOffset = keys.length; + var i = 0; + var name = 0; + var m; -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ + if (path instanceof RegExp) { + while (m = MATCHING_GROUP_REGEXP.exec(path.source)) { + keys.push({ + name: name++, + optional: false, + offset: m.index + }); + } -function fmtShort(ms) { - if (ms >= d) { - return Math.round(ms / d) + 'd'; - } - if (ms >= h) { - return Math.round(ms / h) + 'h'; - } - if (ms >= m) { - return Math.round(ms / m) + 'm'; - } - if (ms >= s) { - return Math.round(ms / s) + 's'; + return path; } - return ms + 'ms'; -} -/** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ + if (Array.isArray(path)) { + // Map array parts into regexps and return their source. We also pass + // the same keys and options instance into every generation to get + // consistent matching groups before we join the sources together. + path = path.map(function (value) { + return pathtoRegexp(value, keys, options).source; + }); -function fmtLong(ms) { - return plural(ms, d, 'day') || - plural(ms, h, 'hour') || - plural(ms, m, 'minute') || - plural(ms, s, 'second') || - ms + ' ms'; -} + return new RegExp('(?:' + path.join('|') + ')', flags); + } -/** - * Pluralization helper. - */ + path = ('^' + path + (strict ? '' : path[path.length - 1] === '/' ? '?' : '/?')) + .replace(/\/\(/g, '/(?:') + .replace(/([\/\.])/g, '\\$1') + .replace(/(\\\/)?(\\\.)?:(\w+)(\(.*?\))?(\*)?(\?)?/g, function (match, slash, format, key, capture, star, optional, offset) { + slash = slash || ''; + format = format || ''; + capture = capture || '([^\\/' + format + ']+?)'; + optional = optional || ''; -function plural(ms, n, name) { - if (ms < n) { - return; - } - if (ms < n * 1.5) { - return Math.floor(ms / n) + ' ' + name; - } - return Math.ceil(ms / n) + ' ' + name + 's'; -} + keys.push({ + name: key, + optional: !!optional, + offset: offset + extraOffset + }); + var result = '' + + (optional ? '' : slash) + + '(?:' + + format + (optional ? slash : '') + capture + + (star ? '((?:[\\/' + format + '].+?)?)' : '') + + ')' + + optional; -/***/ }), -/* 320 */, -/* 321 */ -/***/ (function(module) { + extraOffset += result.length - match.length; -/*! - * async - * https://github.com/caolan/async - * - * Copyright 2010-2014 Caolan McMahon - * Released under the MIT license - */ -(function () { + return result; + }) + .replace(/\*/g, function (star, index) { + var len = keys.length - var async = {}; - function noop() {} - function identity(v) { - return v; - } - function toBool(v) { - return !!v; - } - function notId(v) { - return !v; - } + while (len-- > keysOffset && keys[len].offset > index) { + keys[len].offset += 3; // Replacement length minus asterisk length. + } - // global on the server, window in the browser - var previous_async; + return '(.*)'; + }); - // Establish the root object, `window` (`self`) in the browser, `global` - // on the server, or `this` in some virtual machines. We use `self` - // instead of `window` for `WebWorker` support. - var root = typeof self === 'object' && self.self === self && self || - typeof global === 'object' && global.global === global && global || - this; + // This is a workaround for handling unnamed matching groups. + while (m = MATCHING_GROUP_REGEXP.exec(path)) { + var escapeCount = 0; + var index = m.index; - if (root != null) { - previous_async = root.async; + while (path.charAt(--index) === '\\') { + escapeCount++; } - async.noConflict = function () { - root.async = previous_async; - return async; - }; - - function only_once(fn) { - return function() { - if (fn === null) throw new Error("Callback was already called."); - fn.apply(this, arguments); - fn = null; - }; + // It's possible to escape the bracket. + if (escapeCount % 2 === 1) { + continue; } - function _once(fn) { - return function() { - if (fn === null) return; - fn.apply(this, arguments); - fn = null; - }; + if (keysOffset + i === keys.length || keys[keysOffset + i].offset > m.index) { + keys.splice(keysOffset + i, 0, { + name: name++, // Unnamed matching groups must be consistently linear. + optional: false, + offset: m.index + }); } - //// cross-browser compatiblity functions //// + i++; + } - var _toString = Object.prototype.toString; + // If the path is non-ending, match until the end or a slash. + path += (end ? '$' : (path[path.length - 1] === '/' ? '' : '(?=\\/|$)')); - var _isArray = Array.isArray || function (obj) { - return _toString.call(obj) === '[object Array]'; - }; + return new RegExp(path, flags); +}; - // Ported from underscore.js isObject - var _isObject = function(obj) { - var type = typeof obj; - return type === 'function' || type === 'object' && !!obj; - }; - function _isArrayLike(arr) { - return _isArray(arr) || ( - // has a positive integer length property - typeof arr.length === "number" && - arr.length >= 0 && - arr.length % 1 === 0 - ); - } +/***/ }), +/* 372 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { - function _arrayEach(arr, iterator) { - var index = -1, - length = arr.length; +"use strict"; - while (++index < length) { - iterator(arr[index], index, arr); - } +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = __webpack_require__(200); +const net_1 = __webpack_require__(631); +function getNodeKey(node) { + node.port = node.port || 6379; + node.host = node.host || "127.0.0.1"; + return node.host + ":" + node.port; +} +exports.getNodeKey = getNodeKey; +function nodeKeyToRedisOptions(nodeKey) { + const portIndex = nodeKey.lastIndexOf(":"); + if (portIndex === -1) { + throw new Error(`Invalid node key ${nodeKey}`); } - - function _map(arr, iterator) { - var index = -1, - length = arr.length, - result = Array(length); - - while (++index < length) { - result[index] = iterator(arr[index], index, arr); + return { + host: nodeKey.slice(0, portIndex), + port: Number(nodeKey.slice(portIndex + 1)), + }; +} +exports.nodeKeyToRedisOptions = nodeKeyToRedisOptions; +function normalizeNodeOptions(nodes) { + return nodes.map((node) => { + const options = {}; + if (typeof node === "object") { + Object.assign(options, node); } - return result; - } - - function _range(count) { - return _map(Array(count), function (v, i) { return i; }); - } + else if (typeof node === "string") { + Object.assign(options, utils_1.parseURL(node)); + } + else if (typeof node === "number") { + options.port = node; + } + else { + throw new Error("Invalid argument " + node); + } + if (typeof options.port === "string") { + options.port = parseInt(options.port, 10); + } + // Cluster mode only support db 0 + delete options.db; + if (!options.port) { + options.port = 6379; + } + if (!options.host) { + options.host = "127.0.0.1"; + } + return options; + }); +} +exports.normalizeNodeOptions = normalizeNodeOptions; +function getUniqueHostnamesFromOptions(nodes) { + const uniqueHostsMap = {}; + nodes.forEach((node) => { + uniqueHostsMap[node.host] = true; + }); + return Object.keys(uniqueHostsMap).filter((host) => !net_1.isIP(host)); +} +exports.getUniqueHostnamesFromOptions = getUniqueHostnamesFromOptions; - function _reduce(arr, iterator, memo) { - _arrayEach(arr, function (x, i, a) { - memo = iterator(memo, x, i, a); - }); - return memo; - } - function _forEachOf(object, iterator) { - _arrayEach(_keys(object), function (key) { - iterator(object[key], key); - }); - } +/***/ }), +/* 373 */ +/***/ (function(__unusedmodule, exports) { - function _indexOf(arr, item) { - for (var i = 0; i < arr.length; i++) { - if (arr[i] === item) return i; +Object.defineProperty(exports, "__esModule", { value: true }); +/** The status of an event. */ +// eslint-disable-next-line import/export +var Status; +(function (Status) { + /** The status could not be determined. */ + Status["Unknown"] = "unknown"; + /** The event was skipped due to configuration or callbacks. */ + Status["Skipped"] = "skipped"; + /** The event was sent to Sentry successfully. */ + Status["Success"] = "success"; + /** The client is currently rate limited and will try again later. */ + Status["RateLimit"] = "rate_limit"; + /** The event could not be processed. */ + Status["Invalid"] = "invalid"; + /** A server-side error ocurred during submission. */ + Status["Failed"] = "failed"; +})(Status = exports.Status || (exports.Status = {})); +// eslint-disable-next-line @typescript-eslint/no-namespace, import/export +(function (Status) { + /** + * Converts a HTTP status code into a {@link Status}. + * + * @param code The HTTP response status code. + * @returns The send status or {@link Status.Unknown}. + */ + function fromHttpCode(code) { + if (code >= 200 && code < 300) { + return Status.Success; } - return -1; - } - - var _keys = Object.keys || function (obj) { - var keys = []; - for (var k in obj) { - if (obj.hasOwnProperty(k)) { - keys.push(k); - } + if (code === 429) { + return Status.RateLimit; } - return keys; - }; - - function _keyIterator(coll) { - var i = -1; - var len; - var keys; - if (_isArrayLike(coll)) { - len = coll.length; - return function next() { - i++; - return i < len ? i : null; - }; - } else { - keys = _keys(coll); - len = keys.length; - return function next() { - i++; - return i < len ? keys[i] : null; - }; + if (code >= 400 && code < 500) { + return Status.Invalid; } + if (code >= 500) { + return Status.Failed; + } + return Status.Unknown; } + Status.fromHttpCode = fromHttpCode; +})(Status = exports.Status || (exports.Status = {})); +//# sourceMappingURL=status.js.map - // Similar to ES6's rest param (http://ariya.ofilabs.com/2013/03/es6-and-rest-parameter.html) - // This accumulates the arguments passed into an array, after a given index. - // From underscore.js (https://github.com/jashkenas/underscore/pull/2140). - function _restParam(func, startIndex) { - startIndex = startIndex == null ? func.length - 1 : +startIndex; - return function() { - var length = Math.max(arguments.length - startIndex, 0); - var rest = Array(length); - for (var index = 0; index < length; index++) { - rest[index] = arguments[index + startIndex]; - } - switch (startIndex) { - case 0: return func.call(this, rest); - case 1: return func.call(this, arguments[0], rest); - } - // Currently unused but handle cases outside of the switch statement: - // var args = Array(startIndex + 1); - // for (index = 0; index < startIndex; index++) { - // args[index] = arguments[index]; - // } - // args[startIndex] = rest; - // return func.apply(this, args); - }; - } - - function _withoutIndex(iterator) { - return function (value, index, callback) { - return iterator(value, callback); - }; - } +/***/ }), +/* 374 */, +/* 375 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - //// exported async module functions //// +"use strict"; - //// nextTick implementation with browser-compatible fallback //// - // capture the global reference to guard against fakeTimer mocks - var _setImmediate = typeof setImmediate === 'function' && setImmediate; +var Type = __webpack_require__(945); - var _delay = _setImmediate ? function(fn) { - // not a direct alias for IE10 compatibility - _setImmediate(fn); - } : function(fn) { - setTimeout(fn, 0); - }; +var _hasOwnProperty = Object.prototype.hasOwnProperty; +var _toString = Object.prototype.toString; - if (typeof process === 'object' && typeof process.nextTick === 'function') { - async.nextTick = process.nextTick; - } else { - async.nextTick = _delay; - } - async.setImmediate = _setImmediate ? _delay : async.nextTick; +function resolveYamlOmap(data) { + if (data === null) return true; + var objectKeys = [], index, length, pair, pairKey, pairHasKey, + object = data; - async.forEach = - async.each = function (arr, iterator, callback) { - return async.eachOf(arr, _withoutIndex(iterator), callback); - }; + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + pairHasKey = false; - async.forEachSeries = - async.eachSeries = function (arr, iterator, callback) { - return async.eachOfSeries(arr, _withoutIndex(iterator), callback); - }; + if (_toString.call(pair) !== '[object Object]') return false; + for (pairKey in pair) { + if (_hasOwnProperty.call(pair, pairKey)) { + if (!pairHasKey) pairHasKey = true; + else return false; + } + } - async.forEachLimit = - async.eachLimit = function (arr, limit, iterator, callback) { - return _eachOfLimit(limit)(arr, _withoutIndex(iterator), callback); - }; + if (!pairHasKey) return false; - async.forEachOf = - async.eachOf = function (object, iterator, callback) { - callback = _once(callback || noop); - object = object || []; + if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); + else return false; + } - var iter = _keyIterator(object); - var key, completed = 0; + return true; +} - while ((key = iter()) != null) { - completed += 1; - iterator(object[key], key, only_once(done)); - } +function constructYamlOmap(data) { + return data !== null ? data : []; +} - if (completed === 0) callback(null); +module.exports = new Type('tag:yaml.org,2002:omap', { + kind: 'sequence', + resolve: resolveYamlOmap, + construct: constructYamlOmap +}); - function done(err) { - completed--; - if (err) { - callback(err); - } - // Check key is null in case iterator isn't exhausted - // and done resolved synchronously. - else if (key === null && completed <= 0) { - callback(null); - } - } - }; - async.forEachOfSeries = - async.eachOfSeries = function (obj, iterator, callback) { - callback = _once(callback || noop); - obj = obj || []; - var nextKey = _keyIterator(obj); - var key = nextKey(); - function iterate() { - var sync = true; - if (key === null) { - return callback(null); - } - iterator(obj[key], key, only_once(function (err) { - if (err) { - callback(err); - } - else { - key = nextKey(); - if (key === null) { - return callback(null); - } else { - if (sync) { - async.setImmediate(iterate); - } else { - iterate(); - } - } - } - })); - sync = false; - } - iterate(); - }; +/***/ }), +/* 376 */, +/* 377 */, +/* 378 */, +/* 379 */ +/***/ (function(module, __unusedexports, __webpack_require__) { +"use strict"; - async.forEachOfLimit = - async.eachOfLimit = function (obj, limit, iterator, callback) { - _eachOfLimit(limit)(obj, iterator, callback); - }; +var Batcher, Events, parser; +parser = __webpack_require__(850); +Events = __webpack_require__(833); - function _eachOfLimit(limit) { +Batcher = function () { + class Batcher { + constructor(options = {}) { + this.options = options; + parser.load(this.options, this.defaults, this); + this.Events = new Events(this); + this._arr = []; - return function (obj, iterator, callback) { - callback = _once(callback || noop); - obj = obj || []; - var nextKey = _keyIterator(obj); - if (limit <= 0) { - return callback(null); - } - var done = false; - var running = 0; - var errored = false; + this._resetPromise(); - (function replenish () { - if (done && running <= 0) { - return callback(null); - } + this._lastFlush = Date.now(); + } - while (running < limit && !errored) { - var key = nextKey(); - if (key === null) { - done = true; - if (running <= 0) { - callback(null); - } - return; - } - running += 1; - iterator(obj[key], key, only_once(function (err) { - running -= 1; - if (err) { - callback(err); - errored = true; - } - else { - replenish(); - } - })); - } - })(); - }; + _resetPromise() { + return this._promise = new this.Promise((res, rej) => { + return this._resolve = res; + }); } + _flush() { + clearTimeout(this._timeout); + this._lastFlush = Date.now(); - function doParallel(fn) { - return function (obj, iterator, callback) { - return fn(async.eachOf, obj, iterator, callback); - }; - } - function doParallelLimit(fn) { - return function (obj, limit, iterator, callback) { - return fn(_eachOfLimit(limit), obj, iterator, callback); - }; - } - function doSeries(fn) { - return function (obj, iterator, callback) { - return fn(async.eachOfSeries, obj, iterator, callback); - }; - } + this._resolve(); - function _asyncMap(eachfn, arr, iterator, callback) { - callback = _once(callback || noop); - arr = arr || []; - var results = _isArrayLike(arr) ? [] : {}; - eachfn(arr, function (value, index, callback) { - iterator(value, function (err, v) { - results[index] = v; - callback(err); - }); - }, function (err) { - callback(err, results); - }); + this.Events.trigger("batch", this._arr); + this._arr = []; + return this._resetPromise(); } - async.map = doParallel(_asyncMap); - async.mapSeries = doSeries(_asyncMap); - async.mapLimit = doParallelLimit(_asyncMap); - - // reduce only has a series version, as doing reduce in parallel won't - // work in many situations. - async.inject = - async.foldl = - async.reduce = function (arr, memo, iterator, callback) { - async.eachOfSeries(arr, function (x, i, callback) { - iterator(memo, x, function (err, v) { - memo = v; - callback(err); - }); - }, function (err) { - callback(err, memo); - }); - }; + add(data) { + var ret; - async.foldr = - async.reduceRight = function (arr, memo, iterator, callback) { - var reversed = _map(arr, identity).reverse(); - async.reduce(reversed, memo, iterator, callback); - }; + this._arr.push(data); - async.transform = function (arr, memo, iterator, callback) { - if (arguments.length === 3) { - callback = iterator; - iterator = memo; - memo = _isArray(arr) ? [] : {}; - } + ret = this._promise; - async.eachOf(arr, function(v, k, cb) { - iterator(memo, v, k, cb); - }, function(err) { - callback(err, memo); - }); - }; + if (this._arr.length === this.maxSize) { + this._flush(); + } else if (this.maxTime != null && this._arr.length === 1) { + this._timeout = setTimeout(() => { + return this._flush(); + }, this.maxTime); + } - function _filter(eachfn, arr, iterator, callback) { - var results = []; - eachfn(arr, function (x, index, callback) { - iterator(x, function (v) { - if (v) { - results.push({index: index, value: x}); - } - callback(); - }); - }, function () { - callback(_map(results.sort(function (a, b) { - return a.index - b.index; - }), function (x) { - return x.value; - })); - }); + return ret; } - async.select = - async.filter = doParallel(_filter); + } - async.selectLimit = - async.filterLimit = doParallelLimit(_filter); + ; + Batcher.prototype.defaults = { + maxTime: null, + maxSize: null, + Promise: Promise + }; + return Batcher; +}.call(void 0); - async.selectSeries = - async.filterSeries = doSeries(_filter); +module.exports = Batcher; - function _reject(eachfn, arr, iterator, callback) { - _filter(eachfn, arr, function(value, cb) { - iterator(value, function(v) { - cb(!v); - }); - }, callback); - } - async.reject = doParallel(_reject); - async.rejectLimit = doParallelLimit(_reject); - async.rejectSeries = doSeries(_reject); +/***/ }), +/* 380 */, +/* 381 */ +/***/ (function(module, __unusedexports, __webpack_require__) { - function _createTester(eachfn, check, getResult) { - return function(arr, limit, iterator, cb) { - function done() { - if (cb) cb(getResult(false, void 0)); - } - function iteratee(x, _, callback) { - if (!cb) return callback(); - iterator(x, function (v) { - if (cb && check(v)) { - cb(getResult(true, x)); - cb = iterator = false; - } - callback(); - }); - } - if (arguments.length > 3) { - eachfn(arr, limit, iteratee, done); - } else { - cb = iterator; - iterator = limit; - eachfn(arr, iteratee, done); - } - }; - } +"use strict"; +/*! + * send + * Copyright(c) 2012 TJ Holowaychuk + * Copyright(c) 2014-2016 Douglas Christopher Wilson + * MIT Licensed + */ - async.any = - async.some = _createTester(async.eachOf, toBool, identity); - async.someLimit = _createTester(async.eachOfLimit, toBool, identity); - async.all = - async.every = _createTester(async.eachOf, notId, notId); +/** + * Module dependencies. + * @private + */ - async.everyLimit = _createTester(async.eachOfLimit, notId, notId); +var createError = __webpack_require__(846) +var debug = __webpack_require__(25)('send') +var deprecate = __webpack_require__(418)('send') +var destroy = __webpack_require__(298) +var encodeUrl = __webpack_require__(709) +var escapeHtml = __webpack_require__(280) +var etag = __webpack_require__(521) +var fresh = __webpack_require__(115) +var fs = __webpack_require__(747) +var mime = __webpack_require__(316) +var ms = __webpack_require__(589) +var onFinished = __webpack_require__(581) +var parseRange = __webpack_require__(770) +var path = __webpack_require__(622) +var statuses = __webpack_require__(347) +var Stream = __webpack_require__(413) +var util = __webpack_require__(669) - function _findGetResult(v, x) { - return x; - } - async.detect = _createTester(async.eachOf, identity, _findGetResult); - async.detectSeries = _createTester(async.eachOfSeries, identity, _findGetResult); - async.detectLimit = _createTester(async.eachOfLimit, identity, _findGetResult); +/** + * Path function references. + * @private + */ - async.sortBy = function (arr, iterator, callback) { - async.map(arr, function (x, callback) { - iterator(x, function (err, criteria) { - if (err) { - callback(err); - } - else { - callback(null, {value: x, criteria: criteria}); - } - }); - }, function (err, results) { - if (err) { - return callback(err); - } - else { - callback(null, _map(results.sort(comparator), function (x) { - return x.value; - })); - } +var extname = path.extname +var join = path.join +var normalize = path.normalize +var resolve = path.resolve +var sep = path.sep - }); +/** + * Regular expression for identifying a bytes Range header. + * @private + */ - function comparator(left, right) { - var a = left.criteria, b = right.criteria; - return a < b ? -1 : a > b ? 1 : 0; - } - }; +var BYTES_RANGE_REGEXP = /^ *bytes=/ - async.auto = function (tasks, concurrency, callback) { - if (typeof arguments[1] === 'function') { - // concurrency is optional, shift the args. - callback = concurrency; - concurrency = null; - } - callback = _once(callback || noop); - var keys = _keys(tasks); - var remainingTasks = keys.length; - if (!remainingTasks) { - return callback(null); - } - if (!concurrency) { - concurrency = remainingTasks; - } +/** + * Maximum value allowed for the max age. + * @private + */ - var results = {}; - var runningTasks = 0; +var MAX_MAXAGE = 60 * 60 * 24 * 365 * 1000 // 1 year - var hasError = false; +/** + * Regular expression to match a path with a directory up component. + * @private + */ - var listeners = []; - function addListener(fn) { - listeners.unshift(fn); - } - function removeListener(fn) { - var idx = _indexOf(listeners, fn); - if (idx >= 0) listeners.splice(idx, 1); - } - function taskComplete() { - remainingTasks--; - _arrayEach(listeners.slice(0), function (fn) { - fn(); - }); - } +var UP_PATH_REGEXP = /(?:^|[\\/])\.\.(?:[\\/]|$)/ - addListener(function () { - if (!remainingTasks) { - callback(null, results); - } - }); +/** + * Module exports. + * @public + */ - _arrayEach(keys, function (k) { - if (hasError) return; - var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]]; - var taskCallback = _restParam(function(err, args) { - runningTasks--; - if (args.length <= 1) { - args = args[0]; - } - if (err) { - var safeResults = {}; - _forEachOf(results, function(val, rkey) { - safeResults[rkey] = val; - }); - safeResults[k] = args; - hasError = true; - - callback(err, safeResults); - } - else { - results[k] = args; - async.setImmediate(taskComplete); - } - }); - var requires = task.slice(0, task.length - 1); - // prevent dead-locks - var len = requires.length; - var dep; - while (len--) { - if (!(dep = tasks[requires[len]])) { - throw new Error('Has nonexistent dependency in ' + requires.join(', ')); - } - if (_isArray(dep) && _indexOf(dep, k) >= 0) { - throw new Error('Has cyclic dependencies'); - } - } - function ready() { - return runningTasks < concurrency && _reduce(requires, function (a, x) { - return (a && results.hasOwnProperty(x)); - }, true) && !results.hasOwnProperty(k); - } - if (ready()) { - runningTasks++; - task[task.length - 1](taskCallback, results); - } - else { - addListener(listener); - } - function listener() { - if (ready()) { - runningTasks++; - removeListener(listener); - task[task.length - 1](taskCallback, results); - } - } - }); - }; +module.exports = send +module.exports.mime = mime +/** + * Return a `SendStream` for `req` and `path`. + * + * @param {object} req + * @param {string} path + * @param {object} [options] + * @return {SendStream} + * @public + */ +function send (req, path, options) { + return new SendStream(req, path, options) +} - async.retry = function(times, task, callback) { - var DEFAULT_TIMES = 5; - var DEFAULT_INTERVAL = 0; +/** + * Initialize a `SendStream` with the given `path`. + * + * @param {Request} req + * @param {String} path + * @param {object} [options] + * @private + */ - var attempts = []; +function SendStream (req, path, options) { + Stream.call(this) - var opts = { - times: DEFAULT_TIMES, - interval: DEFAULT_INTERVAL - }; + var opts = options || {} - function parseTimes(acc, t){ - if(typeof t === 'number'){ - acc.times = parseInt(t, 10) || DEFAULT_TIMES; - } else if(typeof t === 'object'){ - acc.times = parseInt(t.times, 10) || DEFAULT_TIMES; - acc.interval = parseInt(t.interval, 10) || DEFAULT_INTERVAL; - } else { - throw new Error('Unsupported argument type for \'times\': ' + typeof t); - } - } + this.options = opts + this.path = path + this.req = req - var length = arguments.length; - if (length < 1 || length > 3) { - throw new Error('Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)'); - } else if (length <= 2 && typeof times === 'function') { - callback = task; - task = times; - } - if (typeof times !== 'function') { - parseTimes(opts, times); - } - opts.callback = callback; - opts.task = task; + this._acceptRanges = opts.acceptRanges !== undefined + ? Boolean(opts.acceptRanges) + : true - function wrappedTask(wrappedCallback, wrappedResults) { - function retryAttempt(task, finalAttempt) { - return function(seriesCallback) { - task(function(err, result){ - seriesCallback(!err || finalAttempt, {err: err, result: result}); - }, wrappedResults); - }; - } + this._cacheControl = opts.cacheControl !== undefined + ? Boolean(opts.cacheControl) + : true - function retryInterval(interval){ - return function(seriesCallback){ - setTimeout(function(){ - seriesCallback(null); - }, interval); - }; - } + this._etag = opts.etag !== undefined + ? Boolean(opts.etag) + : true - while (opts.times) { + this._dotfiles = opts.dotfiles !== undefined + ? opts.dotfiles + : 'ignore' - var finalAttempt = !(opts.times-=1); - attempts.push(retryAttempt(opts.task, finalAttempt)); - if(!finalAttempt && opts.interval > 0){ - attempts.push(retryInterval(opts.interval)); - } - } + if (this._dotfiles !== 'ignore' && this._dotfiles !== 'allow' && this._dotfiles !== 'deny') { + throw new TypeError('dotfiles option must be "allow", "deny", or "ignore"') + } - async.series(attempts, function(done, data){ - data = data[data.length - 1]; - (wrappedCallback || opts.callback)(data.err, data.result); - }); - } + this._hidden = Boolean(opts.hidden) - // If a callback is passed, run this as a controll flow - return opts.callback ? wrappedTask() : wrappedTask; - }; + if (opts.hidden !== undefined) { + deprecate('hidden: use dotfiles: \'' + (this._hidden ? 'allow' : 'ignore') + '\' instead') + } - async.waterfall = function (tasks, callback) { - callback = _once(callback || noop); - if (!_isArray(tasks)) { - var err = new Error('First argument to waterfall must be an array of functions'); - return callback(err); - } - if (!tasks.length) { - return callback(); - } - function wrapIterator(iterator) { - return _restParam(function (err, args) { - if (err) { - callback.apply(null, [err].concat(args)); - } - else { - var next = iterator.next(); - if (next) { - args.push(wrapIterator(next)); - } - else { - args.push(callback); - } - ensureAsync(iterator).apply(null, args); - } - }); - } - wrapIterator(async.iterator(tasks))(); - }; + // legacy support + if (opts.dotfiles === undefined) { + this._dotfiles = undefined + } - function _parallel(eachfn, tasks, callback) { - callback = callback || noop; - var results = _isArrayLike(tasks) ? [] : {}; + this._extensions = opts.extensions !== undefined + ? normalizeList(opts.extensions, 'extensions option') + : [] - eachfn(tasks, function (task, key, callback) { - task(_restParam(function (err, args) { - if (args.length <= 1) { - args = args[0]; - } - results[key] = args; - callback(err); - })); - }, function (err) { - callback(err, results); - }); - } + this._immutable = opts.immutable !== undefined + ? Boolean(opts.immutable) + : false - async.parallel = function (tasks, callback) { - _parallel(async.eachOf, tasks, callback); - }; + this._index = opts.index !== undefined + ? normalizeList(opts.index, 'index option') + : ['index.html'] - async.parallelLimit = function(tasks, limit, callback) { - _parallel(_eachOfLimit(limit), tasks, callback); - }; + this._lastModified = opts.lastModified !== undefined + ? Boolean(opts.lastModified) + : true - async.series = function(tasks, callback) { - _parallel(async.eachOfSeries, tasks, callback); - }; + this._maxage = opts.maxAge || opts.maxage + this._maxage = typeof this._maxage === 'string' + ? ms(this._maxage) + : Number(this._maxage) + this._maxage = !isNaN(this._maxage) + ? Math.min(Math.max(0, this._maxage), MAX_MAXAGE) + : 0 - async.iterator = function (tasks) { - function makeCallback(index) { - function fn() { - if (tasks.length) { - tasks[index].apply(null, arguments); - } - return fn.next(); - } - fn.next = function () { - return (index < tasks.length - 1) ? makeCallback(index + 1): null; - }; - return fn; - } - return makeCallback(0); - }; + this._root = opts.root + ? resolve(opts.root) + : null - async.apply = _restParam(function (fn, args) { - return _restParam(function (callArgs) { - return fn.apply( - null, args.concat(callArgs) - ); - }); - }); + if (!this._root && opts.from) { + this.from(opts.from) + } +} - function _concat(eachfn, arr, fn, callback) { - var result = []; - eachfn(arr, function (x, index, cb) { - fn(x, function (err, y) { - result = result.concat(y || []); - cb(err); - }); - }, function (err) { - callback(err, result); - }); - } - async.concat = doParallel(_concat); - async.concatSeries = doSeries(_concat); +/** + * Inherits from `Stream`. + */ - async.whilst = function (test, iterator, callback) { - callback = callback || noop; - if (test()) { - var next = _restParam(function(err, args) { - if (err) { - callback(err); - } else if (test.apply(this, args)) { - iterator(next); - } else { - callback.apply(null, [null].concat(args)); - } - }); - iterator(next); - } else { - callback(null); - } - }; +util.inherits(SendStream, Stream) - async.doWhilst = function (iterator, test, callback) { - var calls = 0; - return async.whilst(function() { - return ++calls <= 1 || test.apply(this, arguments); - }, iterator, callback); - }; +/** + * Enable or disable etag generation. + * + * @param {Boolean} val + * @return {SendStream} + * @api public + */ - async.until = function (test, iterator, callback) { - return async.whilst(function() { - return !test.apply(this, arguments); - }, iterator, callback); - }; +SendStream.prototype.etag = deprecate.function(function etag (val) { + this._etag = Boolean(val) + debug('etag %s', this._etag) + return this +}, 'send.etag: pass etag as option') - async.doUntil = function (iterator, test, callback) { - return async.doWhilst(iterator, function() { - return !test.apply(this, arguments); - }, callback); - }; +/** + * Enable or disable "hidden" (dot) files. + * + * @param {Boolean} path + * @return {SendStream} + * @api public + */ - async.during = function (test, iterator, callback) { - callback = callback || noop; +SendStream.prototype.hidden = deprecate.function(function hidden (val) { + this._hidden = Boolean(val) + this._dotfiles = undefined + debug('hidden %s', this._hidden) + return this +}, 'send.hidden: use dotfiles option') - var next = _restParam(function(err, args) { - if (err) { - callback(err); - } else { - args.push(check); - test.apply(this, args); - } - }); +/** + * Set index `paths`, set to a falsy + * value to disable index support. + * + * @param {String|Boolean|Array} paths + * @return {SendStream} + * @api public + */ - var check = function(err, truth) { - if (err) { - callback(err); - } else if (truth) { - iterator(next); - } else { - callback(null); - } - }; +SendStream.prototype.index = deprecate.function(function index (paths) { + var index = !paths ? [] : normalizeList(paths, 'paths argument') + debug('index %o', paths) + this._index = index + return this +}, 'send.index: pass index as option') - test(check); - }; +/** + * Set root `path`. + * + * @param {String} path + * @return {SendStream} + * @api public + */ - async.doDuring = function (iterator, test, callback) { - var calls = 0; - async.during(function(next) { - if (calls++ < 1) { - next(null, true); - } else { - test.apply(this, arguments); - } - }, iterator, callback); - }; +SendStream.prototype.root = function root (path) { + this._root = resolve(String(path)) + debug('root %s', this._root) + return this +} - function _queue(worker, concurrency, payload) { - if (concurrency == null) { - concurrency = 1; - } - else if(concurrency === 0) { - throw new Error('Concurrency must not be zero'); - } - function _insert(q, data, pos, callback) { - if (callback != null && typeof callback !== "function") { - throw new Error("task callback must be a function"); - } - q.started = true; - if (!_isArray(data)) { - data = [data]; - } - if(data.length === 0 && q.idle()) { - // call drain immediately if there are no tasks - return async.setImmediate(function() { - q.drain(); - }); - } - _arrayEach(data, function(task) { - var item = { - data: task, - callback: callback || noop - }; +SendStream.prototype.from = deprecate.function(SendStream.prototype.root, + 'send.from: pass root as option') - if (pos) { - q.tasks.unshift(item); - } else { - q.tasks.push(item); - } +SendStream.prototype.root = deprecate.function(SendStream.prototype.root, + 'send.root: pass root as option') - if (q.tasks.length === q.concurrency) { - q.saturated(); - } - }); - async.setImmediate(q.process); - } - function _next(q, tasks) { - return function(){ - workers -= 1; - - var removed = false; - var args = arguments; - _arrayEach(tasks, function (task) { - _arrayEach(workersList, function (worker, index) { - if (worker === task && !removed) { - workersList.splice(index, 1); - removed = true; - } - }); +/** + * Set max-age to `maxAge`. + * + * @param {Number} maxAge + * @return {SendStream} + * @api public + */ - task.callback.apply(task, args); - }); - if (q.tasks.length + workers === 0) { - q.drain(); - } - q.process(); - }; - } +SendStream.prototype.maxage = deprecate.function(function maxage (maxAge) { + this._maxage = typeof maxAge === 'string' + ? ms(maxAge) + : Number(maxAge) + this._maxage = !isNaN(this._maxage) + ? Math.min(Math.max(0, this._maxage), MAX_MAXAGE) + : 0 + debug('max-age %d', this._maxage) + return this +}, 'send.maxage: pass maxAge as option') - var workers = 0; - var workersList = []; - var q = { - tasks: [], - concurrency: concurrency, - payload: payload, - saturated: noop, - empty: noop, - drain: noop, - started: false, - paused: false, - push: function (data, callback) { - _insert(q, data, false, callback); - }, - kill: function () { - q.drain = noop; - q.tasks = []; - }, - unshift: function (data, callback) { - _insert(q, data, true, callback); - }, - process: function () { - while(!q.paused && workers < q.concurrency && q.tasks.length){ +/** + * Emit error with `status`. + * + * @param {number} status + * @param {Error} [err] + * @private + */ - var tasks = q.payload ? - q.tasks.splice(0, q.payload) : - q.tasks.splice(0, q.tasks.length); +SendStream.prototype.error = function error (status, err) { + // emit if listeners instead of responding + if (hasListeners(this, 'error')) { + return this.emit('error', createError(status, err, { + expose: false + })) + } - var data = _map(tasks, function (task) { - return task.data; - }); + var res = this.res + var msg = statuses[status] || String(status) + var doc = createHtmlDocument('Error', escapeHtml(msg)) - if (q.tasks.length === 0) { - q.empty(); - } - workers += 1; - workersList.push(tasks[0]); - var cb = only_once(_next(q, tasks)); - worker(data, cb); - } - }, - length: function () { - return q.tasks.length; - }, - running: function () { - return workers; - }, - workersList: function () { - return workersList; - }, - idle: function() { - return q.tasks.length + workers === 0; - }, - pause: function () { - q.paused = true; - }, - resume: function () { - if (q.paused === false) { return; } - q.paused = false; - var resumeCount = Math.min(q.concurrency, q.tasks.length); - // Need to call q.process once per concurrent - // worker to preserve full concurrency after pause - for (var w = 1; w <= resumeCount; w++) { - async.setImmediate(q.process); - } - } - }; - return q; - } + // clear existing headers + clearHeaders(res) - async.queue = function (worker, concurrency) { - var q = _queue(function (items, cb) { - worker(items[0], cb); - }, concurrency, 1); + // add error headers + if (err && err.headers) { + setHeaders(res, err.headers) + } - return q; - }; + // send basic response + res.statusCode = status + res.setHeader('Content-Type', 'text/html; charset=UTF-8') + res.setHeader('Content-Length', Buffer.byteLength(doc)) + res.setHeader('Content-Security-Policy', "default-src 'none'") + res.setHeader('X-Content-Type-Options', 'nosniff') + res.end(doc) +} - async.priorityQueue = function (worker, concurrency) { +/** + * Check if the pathname ends with "/". + * + * @return {boolean} + * @private + */ - function _compareTasks(a, b){ - return a.priority - b.priority; - } +SendStream.prototype.hasTrailingSlash = function hasTrailingSlash () { + return this.path[this.path.length - 1] === '/' +} - function _binarySearch(sequence, item, compare) { - var beg = -1, - end = sequence.length - 1; - while (beg < end) { - var mid = beg + ((end - beg + 1) >>> 1); - if (compare(item, sequence[mid]) >= 0) { - beg = mid; - } else { - end = mid - 1; - } - } - return beg; - } +/** + * Check if this is a conditional GET request. + * + * @return {Boolean} + * @api private + */ - function _insert(q, data, priority, callback) { - if (callback != null && typeof callback !== "function") { - throw new Error("task callback must be a function"); - } - q.started = true; - if (!_isArray(data)) { - data = [data]; - } - if(data.length === 0) { - // call drain immediately if there are no tasks - return async.setImmediate(function() { - q.drain(); - }); - } - _arrayEach(data, function(task) { - var item = { - data: task, - priority: priority, - callback: typeof callback === 'function' ? callback : noop - }; +SendStream.prototype.isConditionalGET = function isConditionalGET () { + return this.req.headers['if-match'] || + this.req.headers['if-unmodified-since'] || + this.req.headers['if-none-match'] || + this.req.headers['if-modified-since'] +} - q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item); +/** + * Check if the request preconditions failed. + * + * @return {boolean} + * @private + */ - if (q.tasks.length === q.concurrency) { - q.saturated(); - } - async.setImmediate(q.process); - }); - } +SendStream.prototype.isPreconditionFailure = function isPreconditionFailure () { + var req = this.req + var res = this.res - // Start with a normal queue - var q = async.queue(worker, concurrency); + // if-match + var match = req.headers['if-match'] + if (match) { + var etag = res.getHeader('ETag') + return !etag || (match !== '*' && parseTokenList(match).every(function (match) { + return match !== etag && match !== 'W/' + etag && 'W/' + match !== etag + })) + } - // Override push to accept second parameter representing priority - q.push = function (data, priority, callback) { - _insert(q, data, priority, callback); - }; + // if-unmodified-since + var unmodifiedSince = parseHttpDate(req.headers['if-unmodified-since']) + if (!isNaN(unmodifiedSince)) { + var lastModified = parseHttpDate(res.getHeader('Last-Modified')) + return isNaN(lastModified) || lastModified > unmodifiedSince + } - // Remove unshift function - delete q.unshift; + return false +} - return q; - }; +/** + * Strip content-* header fields. + * + * @private + */ - async.cargo = function (worker, payload) { - return _queue(worker, 1, payload); - }; +SendStream.prototype.removeContentHeaderFields = function removeContentHeaderFields () { + var res = this.res + var headers = getHeaderNames(res) - function _console_fn(name) { - return _restParam(function (fn, args) { - fn.apply(null, args.concat([_restParam(function (err, args) { - if (typeof console === 'object') { - if (err) { - if (console.error) { - console.error(err); - } - } - else if (console[name]) { - _arrayEach(args, function (x) { - console[name](x); - }); - } - } - })])); - }); + for (var i = 0; i < headers.length; i++) { + var header = headers[i] + if (header.substr(0, 8) === 'content-' && header !== 'content-location') { + res.removeHeader(header) } - async.log = _console_fn('log'); - async.dir = _console_fn('dir'); - /*async.info = _console_fn('info'); - async.warn = _console_fn('warn'); - async.error = _console_fn('error');*/ - - async.memoize = function (fn, hasher) { - var memo = {}; - var queues = {}; - var has = Object.prototype.hasOwnProperty; - hasher = hasher || identity; - var memoized = _restParam(function memoized(args) { - var callback = args.pop(); - var key = hasher.apply(null, args); - if (has.call(memo, key)) { - async.setImmediate(function () { - callback.apply(null, memo[key]); - }); - } - else if (has.call(queues, key)) { - queues[key].push(callback); - } - else { - queues[key] = [callback]; - fn.apply(null, args.concat([_restParam(function (args) { - memo[key] = args; - var q = queues[key]; - delete queues[key]; - for (var i = 0, l = q.length; i < l; i++) { - q[i].apply(null, args); - } - })])); - } - }); - memoized.memo = memo; - memoized.unmemoized = fn; - return memoized; - }; + } +} - async.unmemoize = function (fn) { - return function () { - return (fn.unmemoized || fn).apply(null, arguments); - }; - }; +/** + * Respond with 304 not modified. + * + * @api private + */ - function _times(mapper) { - return function (count, iterator, callback) { - mapper(_range(count), iterator, callback); - }; - } +SendStream.prototype.notModified = function notModified () { + var res = this.res + debug('not modified') + this.removeContentHeaderFields() + res.statusCode = 304 + res.end() +} - async.times = _times(async.map); - async.timesSeries = _times(async.mapSeries); - async.timesLimit = function (count, limit, iterator, callback) { - return async.mapLimit(_range(count), limit, iterator, callback); - }; +/** + * Raise error that headers already sent. + * + * @api private + */ - async.seq = function (/* functions... */) { - var fns = arguments; - return _restParam(function (args) { - var that = this; +SendStream.prototype.headersAlreadySent = function headersAlreadySent () { + var err = new Error('Can\'t set headers after they are sent.') + debug('headers already sent') + this.error(500, err) +} - var callback = args[args.length - 1]; - if (typeof callback == 'function') { - args.pop(); - } else { - callback = noop; - } +/** + * Check if the request is cacheable, aka + * responded with 2xx or 304 (see RFC 2616 section 14.2{5,6}). + * + * @return {Boolean} + * @api private + */ - async.reduce(fns, args, function (newargs, fn, cb) { - fn.apply(that, newargs.concat([_restParam(function (err, nextargs) { - cb(err, nextargs); - })])); - }, - function (err, results) { - callback.apply(that, [err].concat(results)); - }); - }); - }; +SendStream.prototype.isCachable = function isCachable () { + var statusCode = this.res.statusCode + return (statusCode >= 200 && statusCode < 300) || + statusCode === 304 +} - async.compose = function (/* functions... */) { - return async.seq.apply(null, Array.prototype.reverse.call(arguments)); - }; +/** + * Handle stat() error. + * + * @param {Error} error + * @private + */ +SendStream.prototype.onStatError = function onStatError (error) { + switch (error.code) { + case 'ENAMETOOLONG': + case 'ENOENT': + case 'ENOTDIR': + this.error(404, error) + break + default: + this.error(500, error) + break + } +} - function _applyEach(eachfn) { - return _restParam(function(fns, args) { - var go = _restParam(function(args) { - var that = this; - var callback = args.pop(); - return eachfn(fns, function (fn, _, cb) { - fn.apply(that, args.concat([cb])); - }, - callback); - }); - if (args.length) { - return go.apply(this, args); - } - else { - return go; - } - }); - } +/** + * Check if the cache is fresh. + * + * @return {Boolean} + * @api private + */ - async.applyEach = _applyEach(async.eachOf); - async.applyEachSeries = _applyEach(async.eachOfSeries); +SendStream.prototype.isFresh = function isFresh () { + return fresh(this.req.headers, { + 'etag': this.res.getHeader('ETag'), + 'last-modified': this.res.getHeader('Last-Modified') + }) +} +/** + * Check if the range is fresh. + * + * @return {Boolean} + * @api private + */ - async.forever = function (fn, callback) { - var done = only_once(callback || noop); - var task = ensureAsync(fn); - function next(err) { - if (err) { - return done(err); - } - task(next); - } - next(); - }; +SendStream.prototype.isRangeFresh = function isRangeFresh () { + var ifRange = this.req.headers['if-range'] - function ensureAsync(fn) { - return _restParam(function (args) { - var callback = args.pop(); - args.push(function () { - var innerArgs = arguments; - if (sync) { - async.setImmediate(function () { - callback.apply(null, innerArgs); - }); - } else { - callback.apply(null, innerArgs); - } - }); - var sync = true; - fn.apply(this, args); - sync = false; - }); - } + if (!ifRange) { + return true + } - async.ensureAsync = ensureAsync; + // if-range as etag + if (ifRange.indexOf('"') !== -1) { + var etag = this.res.getHeader('ETag') + return Boolean(etag && ifRange.indexOf(etag) !== -1) + } - async.constant = _restParam(function(values) { - var args = [null].concat(values); - return function (callback) { - return callback.apply(this, args); - }; - }); + // if-range as modified date + var lastModified = this.res.getHeader('Last-Modified') + return parseHttpDate(lastModified) <= parseHttpDate(ifRange) +} - async.wrapSync = - async.asyncify = function asyncify(func) { - return _restParam(function (args) { - var callback = args.pop(); - var result; - try { - result = func.apply(this, args); - } catch (e) { - return callback(e); - } - // if result is Promise object - if (_isObject(result) && typeof result.then === "function") { - result.then(function(value) { - callback(null, value); - })["catch"](function(err) { - callback(err.message ? err : new Error(err)); - }); - } else { - callback(null, result); - } - }); - }; - - // Node.js - if ( true && module.exports) { - module.exports = async; - } - // AMD / RequireJS - else if (typeof define === 'function' && define.amd) { - define([], function () { - return async; - }); - } - // included directly via