// ==UserScript==
// @name 秒传链接提取
// @version 2.7.8
// @author mengzonefire
// @description 用于提取和生成百度网盘秒传链接
// @homepage <https://greasyfork.org/zh-CN/scripts/424574>
// @supportURL <https://github.com/mengzonefire/rapid-upload-userscript/issues>
// @match *://pan.baidu.com/disk/home*
// @match *://pan.baidu.com/disk/main*
// @match *://pan.baidu.com/disk/synchronization*
// @match *://pan.baidu.com/s/*
// @match *://yun.baidu.com/disk/home*
// @match *://yun.baidu.com/disk/main*
// @match *://yun.baidu.com/disk/synchronization*
// @match *://yun.baidu.com/s/*
// @match *://wangpan.baidu.com/disk/home*
// @match *://wangpan.baidu.com/disk/main*
// @match *://wangpan.baidu.com/disk/synchronization*
// @match *://wangpan.baidu.com/s/*
// @name:en rapidupload-userscript
// @license GPLv3
// @icon data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABBUlEQVR4AZTTJRBUURTH4TtDwXuPdPrgbhHXiksf3CPucRNScHd3d3d3uO9bKeu7b79+fun8Q17CNHyMMUqaiPE4fEyYVjjGNKnNwQ4lpgV8lManEfwfosLHEGPU1N3ZnAv4qlT+NiQ56uPWSjKBrztUSnIaB66sY1vgxgxoMXB5NbsCB9rxcB5fN2M5/16nCFxeS6YTezpzsB1Pu/C2O7/78/99eYBYHXh+gqdHObGIK4GHgevjVIt1AgAnhvE4cGe8euoHbizgYuD2RGgx8O0RpwIPRmsmJDGqcrANd3pLo/qVr03hUlcpfSwf0/vD3JwkPdPK5/zhkOz+/f1FIDv/RcnOAEjywH/DhgADAAAAAElFTkSuQmCC
// @namespace moe.cangku.mengzonefire
// @homepageURL <https://greasyfork.org/zh-CN/scripts/424574>
// @contributionURL <https://afdian.net/@mengzonefire>
// @description:en input bdlink to get files or get bdlink for Baidu™ WebDisk.
// @compatible firefox Violentmonkey
// @compatible firefox Tampermonkey
// @compatible chrome Violentmonkey
// @compatible chrome Tampermonkey
// @compatible edge Violentmonkey
// @compatible edge Tampermonkey
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_deleteValue
// @grant GM_setClipboard
// @grant GM_addStyle
// @grant GM_xmlhttpRequest
// @grant GM_registerMenuCommand
// @grant unsafeWindow
// @run-at document-body
// @connect baidu.com
// @connect baidupcs.com
// @connect cdn.jsdelivr.net
// @connect *
// @downloadURL <https://greasyfork.org/scripts/424574/code/%E7%A7%92%E4%BC%A0%E9%93%BE%E6%8E%A5%E6%8F%90%E5%8F%96.user.js>
// @updateURL <https://greasyfork.org/scripts/424574/code/%E7%A7%92%E4%BC%A0%E9%93%BE%E6%8E%A5%E6%8F%90%E5%8F%96.user.js>
// @antifeature referral-link 23.4.5: 加了一个百度官方的网盘会员推广 (从那里开通可使作者获得佣金), 觉得碍眼可以点 "不再显示" 永久隐藏
// ==/UserScript==
/******/ (() => { // webpackBootstrap
/******/ var __webpack_modules__ = ({
/***/ 322:
/***/ ((module) => {
(function (factory) {
if (true) {
// Node/CommonJS
module.exports = factory();
} else { var glob; }
}(function (undefined) {
'use strict';
/*
* Fastest md5 implementation around (JKM md5).
* Credits: Joseph Myers
*
* @see <http://www.myersdaily.org/joseph/javascript/md5-text.html>
* @see <http://jsperf.com/md5-shootout/7>
*/
/* this function is much faster,
so if possible we use it. Some IEs
are the only ones I know of that
need the idiotic second function,
generated by an if clause. */
var add32 = function (a, b) {
return (a + b) & 0xFFFFFFFF;
},
hex_chr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
function cmn(q, a, b, x, s, t) {
a = add32(add32(a, q), add32(x, t));
return add32((a << s) | (a >>> (32 - s)), b);
}
function md5cycle(x, k) {
var a = x[0],
b = x[1],
c = x[2],
d = x[3];
a += (b & c | ~b & d) + k[0] - 680876936 | 0;
a = (a << 7 | a >>> 25) + b | 0;
d += (a & b | ~a & c) + k[1] - 389564586 | 0;
d = (d << 12 | d >>> 20) + a | 0;
c += (d & a | ~d & b) + k[2] + 606105819 | 0;
c = (c << 17 | c >>> 15) + d | 0;
b += (c & d | ~c & a) + k[3] - 1044525330 | 0;
b = (b << 22 | b >>> 10) + c | 0;
a += (b & c | ~b & d) + k[4] - 176418897 | 0;
a = (a << 7 | a >>> 25) + b | 0;
d += (a & b | ~a & c) + k[5] + 1200080426 | 0;
d = (d << 12 | d >>> 20) + a | 0;
c += (d & a | ~d & b) + k[6] - 1473231341 | 0;
c = (c << 17 | c >>> 15) + d | 0;
b += (c & d | ~c & a) + k[7] - 45705983 | 0;
b = (b << 22 | b >>> 10) + c | 0;
a += (b & c | ~b & d) + k[8] + 1770035416 | 0;
a = (a << 7 | a >>> 25) + b | 0;
d += (a & b | ~a & c) + k[9] - 1958414417 | 0;
d = (d << 12 | d >>> 20) + a | 0;
c += (d & a | ~d & b) + k[10] - 42063 | 0;
c = (c << 17 | c >>> 15) + d | 0;
b += (c & d | ~c & a) + k[11] - 1990404162 | 0;
b = (b << 22 | b >>> 10) + c | 0;
a += (b & c | ~b & d) + k[12] + 1804603682 | 0;
a = (a << 7 | a >>> 25) + b | 0;
d += (a & b | ~a & c) + k[13] - 40341101 | 0;
d = (d << 12 | d >>> 20) + a | 0;
c += (d & a | ~d & b) + k[14] - 1502002290 | 0;
c = (c << 17 | c >>> 15) + d | 0;
b += (c & d | ~c & a) + k[15] + 1236535329 | 0;
b = (b << 22 | b >>> 10) + c | 0;
a += (b & d | c & ~d) + k[1] - 165796510 | 0;
a = (a << 5 | a >>> 27) + b | 0;
d += (a & c | b & ~c) + k[6] - 1069501632 | 0;
d = (d << 9 | d >>> 23) + a | 0;
c += (d & b | a & ~b) + k[11] + 643717713 | 0;
c = (c << 14 | c >>> 18) + d | 0;
b += (c & a | d & ~a) + k[0] - 373897302 | 0;
b = (b << 20 | b >>> 12) + c | 0;
a += (b & d | c & ~d) + k[5] - 701558691 | 0;
a = (a << 5 | a >>> 27) + b | 0;
d += (a & c | b & ~c) + k[10] + 38016083 | 0;
d = (d << 9 | d >>> 23) + a | 0;
c += (d & b | a & ~b) + k[15] - 660478335 | 0;
c = (c << 14 | c >>> 18) + d | 0;
b += (c & a | d & ~a) + k[4] - 405537848 | 0;
b = (b << 20 | b >>> 12) + c | 0;
a += (b & d | c & ~d) + k[9] + 568446438 | 0;
a = (a << 5 | a >>> 27) + b | 0;
d += (a & c | b & ~c) + k[14] - 1019803690 | 0;
d = (d << 9 | d >>> 23) + a | 0;
c += (d & b | a & ~b) + k[3] - 187363961 | 0;
c = (c << 14 | c >>> 18) + d | 0;
b += (c & a | d & ~a) + k[8] + 1163531501 | 0;
b = (b << 20 | b >>> 12) + c | 0;
a += (b & d | c & ~d) + k[13] - 1444681467 | 0;
a = (a << 5 | a >>> 27) + b | 0;
d += (a & c | b & ~c) + k[2] - 51403784 | 0;
d = (d << 9 | d >>> 23) + a | 0;
c += (d & b | a & ~b) + k[7] + 1735328473 | 0;
c = (c << 14 | c >>> 18) + d | 0;
b += (c & a | d & ~a) + k[12] - 1926607734 | 0;
b = (b << 20 | b >>> 12) + c | 0;
a += (b ^ c ^ d) + k[5] - 378558 | 0;
a = (a << 4 | a >>> 28) + b | 0;
d += (a ^ b ^ c) + k[8] - 2022574463 | 0;
d = (d << 11 | d >>> 21) + a | 0;
c += (d ^ a ^ b) + k[11] + 1839030562 | 0;
c = (c << 16 | c >>> 16) + d | 0;
b += (c ^ d ^ a) + k[14] - 35309556 | 0;
b = (b << 23 | b >>> 9) + c | 0;
a += (b ^ c ^ d) + k[1] - 1530992060 | 0;
a = (a << 4 | a >>> 28) + b | 0;
d += (a ^ b ^ c) + k[4] + 1272893353 | 0;
d = (d << 11 | d >>> 21) + a | 0;
c += (d ^ a ^ b) + k[7] - 155497632 | 0;
c = (c << 16 | c >>> 16) + d | 0;
b += (c ^ d ^ a) + k[10] - 1094730640 | 0;
b = (b << 23 | b >>> 9) + c | 0;
a += (b ^ c ^ d) + k[13] + 681279174 | 0;
a = (a << 4 | a >>> 28) + b | 0;
d += (a ^ b ^ c) + k[0] - 358537222 | 0;
d = (d << 11 | d >>> 21) + a | 0;
c += (d ^ a ^ b) + k[3] - 722521979 | 0;
c = (c << 16 | c >>> 16) + d | 0;
b += (c ^ d ^ a) + k[6] + 76029189 | 0;
b = (b << 23 | b >>> 9) + c | 0;
a += (b ^ c ^ d) + k[9] - 640364487 | 0;
a = (a << 4 | a >>> 28) + b | 0;
d += (a ^ b ^ c) + k[12] - 421815835 | 0;
d = (d << 11 | d >>> 21) + a | 0;
c += (d ^ a ^ b) + k[15] + 530742520 | 0;
c = (c << 16 | c >>> 16) + d | 0;
b += (c ^ d ^ a) + k[2] - 995338651 | 0;
b = (b << 23 | b >>> 9) + c | 0;
a += (c ^ (b | ~d)) + k[0] - 198630844 | 0;
a = (a << 6 | a >>> 26) + b | 0;
d += (b ^ (a | ~c)) + k[7] + 1126891415 | 0;
d = (d << 10 | d >>> 22) + a | 0;
c += (a ^ (d | ~b)) + k[14] - 1416354905 | 0;
c = (c << 15 | c >>> 17) + d | 0;
b += (d ^ (c | ~a)) + k[5] - 57434055 | 0;
b = (b << 21 |b >>> 11) + c | 0;
a += (c ^ (b | ~d)) + k[12] + 1700485571 | 0;
a = (a << 6 | a >>> 26) + b | 0;
d += (b ^ (a | ~c)) + k[3] - 1894986606 | 0;
d = (d << 10 | d >>> 22) + a | 0;
c += (a ^ (d | ~b)) + k[10] - 1051523 | 0;
c = (c << 15 | c >>> 17) + d | 0;
b += (d ^ (c | ~a)) + k[1] - 2054922799 | 0;
b = (b << 21 |b >>> 11) + c | 0;
a += (c ^ (b | ~d)) + k[8] + 1873313359 | 0;
a = (a << 6 | a >>> 26) + b | 0;
d += (b ^ (a | ~c)) + k[15] - 30611744 | 0;
d = (d << 10 | d >>> 22) + a | 0;
c += (a ^ (d | ~b)) + k[6] - 1560198380 | 0;
c = (c << 15 | c >>> 17) + d | 0;
b += (d ^ (c | ~a)) + k[13] + 1309151649 | 0;
b = (b << 21 |b >>> 11) + c | 0;
a += (c ^ (b | ~d)) + k[4] - 145523070 | 0;
a = (a << 6 | a >>> 26) + b | 0;
d += (b ^ (a | ~c)) + k[11] - 1120210379 | 0;
d = (d << 10 | d >>> 22) + a | 0;
c += (a ^ (d | ~b)) + k[2] + 718787259 | 0;
c = (c << 15 | c >>> 17) + d | 0;
b += (d ^ (c | ~a)) + k[9] - 343485551 | 0;
b = (b << 21 | b >>> 11) + c | 0;
x[0] = a + x[0] | 0;
x[1] = b + x[1] | 0;
x[2] = c + x[2] | 0;
x[3] = d + x[3] | 0;
}
function md5blk(s) {
var md5blks = [],
i; /* Andy King said do it this way. */
for (i = 0; i < 64; i += 4) {
md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << 24);
}
return md5blks;
}
function md5blk_array(a) {
var md5blks = [],
i; /* Andy King said do it this way. */
for (i = 0; i < 64; i += 4) {
md5blks[i >> 2] = a[i] + (a[i + 1] << 8) + (a[i + 2] << 16) + (a[i + 3] << 24);
}
return md5blks;
}
function md51(s) {
var n = s.length,
state = [1732584193, -271733879, -1732584194, 271733878],
i,
length,
tail,
tmp,
lo,
hi;
for (i = 64; i <= n; i += 64) {
md5cycle(state, md5blk(s.substring(i - 64, i)));
}
s = s.substring(i - 64);
length = s.length;
tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
for (i = 0; i < length; i += 1) {
tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3);
}
tail[i >> 2] |= 0x80 << ((i % 4) << 3);
if (i > 55) {
md5cycle(state, tail);
for (i = 0; i < 16; i += 1) {
tail[i] = 0;
}
}
// Beware that the final length might not fit in 32 bits so we take care of that
tmp = n * 8;
tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
lo = parseInt(tmp[2], 16);
hi = parseInt(tmp[1], 16) || 0;
tail[14] = lo;
tail[15] = hi;
md5cycle(state, tail);
return state;
}
function md51_array(a) {
var n = a.length,
state = [1732584193, -271733879, -1732584194, 271733878],
i,
length,
tail,
tmp,
lo,
hi;
for (i = 64; i <= n; i += 64) {
md5cycle(state, md5blk_array(a.subarray(i - 64, i)));
}
// Not sure if it is a bug, however IE10 will always produce a sub array of length 1
// containing the last element of the parent array if the sub array specified starts
// beyond the length of the parent array - weird.
// <https://connect.microsoft.com/IE/feedback/details/771452/typed-array-subarray-issue>
a = (i - 64) < n ? a.subarray(i - 64) : new Uint8Array(0);
length = a.length;
tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
for (i = 0; i < length; i += 1) {
tail[i >> 2] |= a[i] << ((i % 4) << 3);
}
tail[i >> 2] |= 0x80 << ((i % 4) << 3);
if (i > 55) {
md5cycle(state, tail);
for (i = 0; i < 16; i += 1) {
tail[i] = 0;
}
}
// Beware that the final length might not fit in 32 bits so we take care of that
tmp = n * 8;
tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
lo = parseInt(tmp[2], 16);
hi = parseInt(tmp[1], 16) || 0;
tail[14] = lo;
tail[15] = hi;
md5cycle(state, tail);
return state;
}
function rhex(n) {
var s = '',
j;
for (j = 0; j < 4; j += 1) {
s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F];
}
return s;
}
function hex(x) {
var i;
for (i = 0; i < x.length; i += 1) {
x[i] = rhex(x[i]);
}
return x.join('');
}
// In some cases the fast add32 function cannot be used..
if (hex(md51('hello')) !== '5d41402abc4b2a76b9719d911017c592') {
add32 = function (x, y) {
var lsw = (x & 0xFFFF) + (y & 0xFFFF),
msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
};
}
// ---------------------------------------------------
/**
* ArrayBuffer slice polyfill.
*
* @see <https://github.com/ttaubert/node-arraybuffer-slice>
*/
if (typeof ArrayBuffer !== 'undefined' && !ArrayBuffer.prototype.slice) {
(function () {
function clamp(val, length) {
val = (val | 0) || 0;
if (val < 0) {
return Math.max(val + length, 0);
}
return Math.min(val, length);
}
ArrayBuffer.prototype.slice = function (from, to) {
var length = this.byteLength,
begin = clamp(from, length),
end = length,
num,
target,
targetArray,
sourceArray;
if (to !== undefined) {
end = clamp(to, length);
}
if (begin > end) {
return new ArrayBuffer(0);
}
num = end - begin;
target = new ArrayBuffer(num);
targetArray = new Uint8Array(target);
sourceArray = new Uint8Array(this, begin, num);
targetArray.set(sourceArray);
return target;
};
})();
}
// ---------------------------------------------------
/**
* Helpers.
*/
function toUtf8(str) {
if (/[\\u0080-\\uFFFF]/.test(str)) {
str = unescape(encodeURIComponent(str));
}
return str;
}
function utf8Str2ArrayBuffer(str, returnUInt8Array) {
var length = str.length,
buff = new ArrayBuffer(length),
arr = new Uint8Array(buff),
i;
for (i = 0; i < length; i += 1) {
arr[i] = str.charCodeAt(i);
}
return returnUInt8Array ? arr : buff;
}
function arrayBuffer2Utf8Str(buff) {
return String.fromCharCode.apply(null, new Uint8Array(buff));
}
function concatenateArrayBuffers(first, second, returnUInt8Array) {
var result = new Uint8Array(first.byteLength + second.byteLength);
result.set(new Uint8Array(first));
result.set(new Uint8Array(second), first.byteLength);
return returnUInt8Array ? result : result.buffer;
}
function hexToBinaryString(hex) {
var bytes = [],
length = hex.length,
x;
for (x = 0; x < length - 1; x += 2) {
bytes.push(parseInt(hex.substr(x, 2), 16));
}
return String.fromCharCode.apply(String, bytes);
}
// ---------------------------------------------------
/**
* SparkMD5 OOP implementation.
*
* Use this class to perform an incremental md5, otherwise use the
* static methods instead.
*/
function SparkMD5() {
// call reset to init the instance
this.reset();
}
/**
* Appends a string.
* A conversion will be applied if an utf8 string is detected.
*
* @param {String} str The string to be appended
*
* @return {SparkMD5} The instance itself
*/
SparkMD5.prototype.append = function (str) {
// Converts the string to utf8 bytes if necessary
// Then append as binary
this.appendBinary(toUtf8(str));
return this;
};
/**
* Appends a binary string.
*
* @param {String} contents The binary string to be appended
*
* @return {SparkMD5} The instance itself
*/
SparkMD5.prototype.appendBinary = function (contents) {
this._buff += contents;
this._length += contents.length;
var length = this._buff.length,
i;
for (i = 64; i <= length; i += 64) {
md5cycle(this._hash, md5blk(this._buff.substring(i - 64, i)));
}
this._buff = this._buff.substring(i - 64);
return this;
};
/**
* Finishes the incremental computation, reseting the internal state and
* returning the result.
*
* @param {Boolean} raw True to get the raw string, false to get the hex string
*
* @return {String} The result
*/
SparkMD5.prototype.end = function (raw) {
var buff = this._buff,
length = buff.length,
i,
tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
ret;
for (i = 0; i < length; i += 1) {
tail[i >> 2] |= buff.charCodeAt(i) << ((i % 4) << 3);
}
this._finish(tail, length);
ret = hex(this._hash);
if (raw) {
ret = hexToBinaryString(ret);
}
this.reset();
return ret;
};
/**
* Resets the internal state of the computation.
*
* @return {SparkMD5} The instance itself
*/
SparkMD5.prototype.reset = function () {
this._buff = '';
this._length = 0;
this._hash = [1732584193, -271733879, -1732584194, 271733878];
return this;
};
/**
* Gets the internal state of the computation.
*
* @return {Object} The state
*/
SparkMD5.prototype.getState = function () {
return {
buff: this._buff,
length: this._length,
hash: this._hash.slice()
};
};
/**
* Gets the internal state of the computation.
*
* @param {Object} state The state
*
* @return {SparkMD5} The instance itself
*/
SparkMD5.prototype.setState = function (state) {
this._buff = state.buff;
this._length = state.length;
this._hash = state.hash;
return this;
};
/**
* Releases memory used by the incremental buffer and other additional
* resources. If you plan to use the instance again, use reset instead.
*/
SparkMD5.prototype.destroy = function () {
delete this._hash;
delete this._buff;
delete this._length;
};
/**
* Finish the final calculation based on the tail.
*
* @param {Array} tail The tail (will be modified)
* @param {Number} length The length of the remaining buffer
*/
SparkMD5.prototype._finish = function (tail, length) {
var i = length,
tmp,
lo,
hi;
tail[i >> 2] |= 0x80 << ((i % 4) << 3);
if (i > 55) {
md5cycle(this._hash, tail);
for (i = 0; i < 16; i += 1) {
tail[i] = 0;
}
}
// Do the final computation based on the tail and length
// Beware that the final length may not fit in 32 bits so we take care of that
tmp = this._length * 8;
tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
lo = parseInt(tmp[2], 16);
hi = parseInt(tmp[1], 16) || 0;
tail[14] = lo;
tail[15] = hi;
md5cycle(this._hash, tail);
};
/**
* Performs the md5 hash on a string.
* A conversion will be applied if utf8 string is detected.
*
* @param {String} str The string
* @param {Boolean} [raw] True to get the raw string, false to get the hex string
*
* @return {String} The result
*/
SparkMD5.hash = function (str, raw) {
// Converts the string to utf8 bytes if necessary
// Then compute it using the binary function
return SparkMD5.hashBinary(toUtf8(str), raw);
};
/**
* Performs the md5 hash on a binary string.
*
* @param {String} content The binary string
* @param {Boolean} [raw] True to get the raw string, false to get the hex string
*
* @return {String} The result
*/
SparkMD5.hashBinary = function (content, raw) {
var hash = md51(content),
ret = hex(hash);
return raw ? hexToBinaryString(ret) : ret;
};
// ---------------------------------------------------
/**
* SparkMD5 OOP implementation for array buffers.
*
* Use this class to perform an incremental md5 ONLY for array buffers.
*/
SparkMD5.ArrayBuffer = function () {
// call reset to init the instance
this.reset();
};
/**
* Appends an array buffer.
*
* @param {ArrayBuffer} arr The array to be appended
*
* @return {SparkMD5.ArrayBuffer} The instance itself
*/
SparkMD5.ArrayBuffer.prototype.append = function (arr) {
var buff = concatenateArrayBuffers(this._buff.buffer, arr, true),
length = buff.length,
i;
this._length += arr.byteLength;
for (i = 64; i <= length; i += 64) {
md5cycle(this._hash, md5blk_array(buff.subarray(i - 64, i)));
}
this._buff = (i - 64) < length ? new Uint8Array(buff.buffer.slice(i - 64)) : new Uint8Array(0);
return this;
};
/**
* Finishes the incremental computation, reseting the internal state and
* returning the result.
*
* @param {Boolean} raw True to get the raw string, false to get the hex string
*
* @return {String} The result
*/
SparkMD5.ArrayBuffer.prototype.end = function (raw) {
var buff = this._buff,
length = buff.length,
tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
i,
ret;
for (i = 0; i < length; i += 1) {
tail[i >> 2] |= buff[i] << ((i % 4) << 3);
}
this._finish(tail, length);
ret = hex(this._hash);
if (raw) {
ret = hexToBinaryString(ret);
}
this.reset();
return ret;
};
/**
* Resets the internal state of the computation.
*
* @return {SparkMD5.ArrayBuffer} The instance itself
*/
SparkMD5.ArrayBuffer.prototype.reset = function () {
this._buff = new Uint8Array(0);
this._length = 0;
this._hash = [1732584193, -271733879, -1732584194, 271733878];
return this;
};
/**
* Gets the internal state of the computation.
*
* @return {Object} The state
*/
SparkMD5.ArrayBuffer.prototype.getState = function () {
var state = SparkMD5.prototype.getState.call(this);
// Convert buffer to a string
state.buff = arrayBuffer2Utf8Str(state.buff);
return state;
};
/**
* Gets the internal state of the computation.
*
* @param {Object} state The state
*
* @return {SparkMD5.ArrayBuffer} The instance itself
*/
SparkMD5.ArrayBuffer.prototype.setState = function (state) {
// Convert string to buffer
state.buff = utf8Str2ArrayBuffer(state.buff, true);
return SparkMD5.prototype.setState.call(this, state);
};
SparkMD5.ArrayBuffer.prototype.destroy = SparkMD5.prototype.destroy;
SparkMD5.ArrayBuffer.prototype._finish = SparkMD5.prototype._finish;
/**
* Performs the md5 hash on an array buffer.
*
* @param {ArrayBuffer} arr The array buffer
* @param {Boolean} [raw] True to get the raw string, false to get the hex one
*
* @return {String} The result
*/
SparkMD5.ArrayBuffer.hash = function (arr, raw) {
var hash = md51_array(new Uint8Array(arr)),
ret = hex(hash);
return raw ? hexToBinaryString(ret) : ret;
};
return SparkMD5;
}));
/***/ }),
/***/ 455:
/***/ (function(module) {
/*!
* sweetalert2 v11.7.1
* Released under the MIT License.
*/
(function (global, factory) {
true ? module.exports = factory() :
0;
})(this, (function () { 'use strict';
/**
* This module contains `WeakMap`s for each effectively-"private property" that a `Swal` has.
* For example, to set the private property "foo" of `this` to "bar", you can `privateProps.foo.set(this, 'bar')`
* This is the approach that Babel will probably take to implement private methods/fields
* <https://github.com/tc39/proposal-private-methods>
* <https://github.com/babel/babel/pull/7555>
* Once we have the changes from that PR in Babel, and our core class fits reasonable in *one module*
* then we can use that language feature.
*/
var privateProps = {
awaitingPromise: new WeakMap(),
promise: new WeakMap(),
innerParams: new WeakMap(),
domCache: new WeakMap()
};
const swalPrefix = 'swal2-';
/**
* @param {string[]} items
* @returns {object}
*/
const prefix = items => {
const result = {};
for (const i in items) {
result[items[i]] = swalPrefix + items[i];
}
return result;
};
const swalClasses = prefix(['container', 'shown', 'height-auto', 'iosfix', 'popup', 'modal', 'no-backdrop', 'no-transition', 'toast', 'toast-shown', 'show', 'hide', 'close', 'title', 'html-container', 'actions', 'confirm', 'deny', 'cancel', 'default-outline', 'footer', 'icon', 'icon-content', 'image', 'input', 'file', 'range', 'select', 'radio', 'checkbox', 'label', 'textarea', 'inputerror', 'input-label', 'validation-message', 'progress-steps', 'active-progress-step', 'progress-step', 'progress-step-line', 'loader', 'loading', 'styled', 'top', 'top-start', 'top-end', 'top-left', 'top-right', 'center', 'center-start', 'center-end', 'center-left', 'center-right', 'bottom', 'bottom-start', 'bottom-end', 'bottom-left', 'bottom-right', 'grow-row', 'grow-column', 'grow-fullscreen', 'rtl', 'timer-progress-bar', 'timer-progress-bar-container', 'scrollbar-measure', 'icon-success', 'icon-warning', 'icon-info', 'icon-question', 'icon-error']);
const iconTypes = prefix(['success', 'warning', 'info', 'question', 'error']);
const consolePrefix = 'SweetAlert2:';
/**
* Filter the unique values into a new array
*
* @param {Array} arr
* @returns {Array}
*/
const uniqueArray = arr => {
const result = [];
for (let i = 0; i < arr.length; i++) {
if (result.indexOf(arr[i]) === -1) {
result.push(arr[i]);
}
}
return result;
};
/**
* Capitalize the first letter of a string
*
* @param {string} str
* @returns {string}
*/
const capitalizeFirstLetter = str => str.charAt(0).toUpperCase() + str.slice(1);
/**
* Standardize console warnings
*
* @param {string | Array} message
*/
const warn = message => {
console.warn(`${consolePrefix} ${typeof message === 'object' ? message.join(' ') : message}`);
};
/**
* Standardize console errors
*
* @param {string} message
*/
const error = message => {
console.error(`${consolePrefix} ${message}`);
};
/**
* Private global state for `warnOnce`
*
* @type {Array}
* @private
*/
const previousWarnOnceMessages = [];
/**
* Show a console warning, but only if it hasn't already been shown
*
* @param {string} message
*/
const warnOnce = message => {
if (!previousWarnOnceMessages.includes(message)) {
previousWarnOnceMessages.push(message);
warn(message);
}
};
/**
* Show a one-time console warning about deprecated params/methods
*
* @param {string} deprecatedParam
* @param {string} useInstead
*/
const warnAboutDeprecation = (deprecatedParam, useInstead) => {
warnOnce(`"${deprecatedParam}" is deprecated and will be removed in the next major release. Please use "${useInstead}" instead.`);
};
/**
* If `arg` is a function, call it (with no arguments or context) and return the result.
* Otherwise, just pass the value through
*
* @param {Function | any} arg
* @returns {any}
*/
const callIfFunction = arg => typeof arg === 'function' ? arg() : arg;
/**
* @param {any} arg
* @returns {boolean}
*/
const hasToPromiseFn = arg => arg && typeof arg.toPromise === 'function';
/**
* @param {any} arg
* @returns {Promise}
*/
const asPromise = arg => hasToPromiseFn(arg) ? arg.toPromise() : Promise.resolve(arg);
/**
* @param {any} arg
* @returns {boolean}
*/
const isPromise = arg => arg && Promise.resolve(arg) === arg;
/**
* Gets the popup container which contains the backdrop and the popup itself.
*
* @returns {HTMLElement | null}
*/
const getContainer = () => document.body.querySelector(`.${swalClasses.container}`);
/**
* @param {string} selectorString
* @returns {HTMLElement | null}
*/
const elementBySelector = selectorString => {
const container = getContainer();
return container ? container.querySelector(selectorString) : null;
};
/**
* @param {string} className
* @returns {HTMLElement | null}
*/
const elementByClass = className => {
return elementBySelector(`.${className}`);
};
/**
* @returns {HTMLElement | null}
*/
const getPopup = () => elementByClass(swalClasses.popup);
/**
* @returns {HTMLElement | null}
*/
const getIcon = () => elementByClass(swalClasses.icon);
/**
* @returns {HTMLElement | null}
*/
const getIconContent = () => elementByClass(swalClasses['icon-content']);
/**
* @returns {HTMLElement | null}
*/
const getTitle = () => elementByClass(swalClasses.title);
/**
* @returns {HTMLElement | null}
*/
const getHtmlContainer = () => elementByClass(swalClasses['html-container']);
/**
* @returns {HTMLElement | null}
*/
const getImage = () => elementByClass(swalClasses.image);
/**
* @returns {HTMLElement | null}
*/
const getProgressSteps = () => elementByClass(swalClasses['progress-steps']);
/**
* @returns {HTMLElement | null}
*/
const getValidationMessage = () => elementByClass(swalClasses['validation-message']);
/**
* @returns {HTMLButtonElement | null}
*/
const getConfirmButton = () => /** @type {HTMLButtonElement} */elementBySelector(`.${swalClasses.actions} .${swalClasses.confirm}`);
/**
* @returns {HTMLButtonElement | null}
*/
const getCancelButton = () => /** @type {HTMLButtonElement} */elementBySelector(`.${swalClasses.actions} .${swalClasses.cancel}`);
/**
* @returns {HTMLButtonElement | null}
*/
const getDenyButton = () => /** @type {HTMLButtonElement} */elementBySelector(`.${swalClasses.actions} .${swalClasses.deny}`);
/**
* @returns {HTMLElement | null}
*/
const getInputLabel = () => elementByClass(swalClasses['input-label']);
/**
* @returns {HTMLElement | null}
*/
const getLoader = () => elementBySelector(`.${swalClasses.loader}`);
/**
* @returns {HTMLElement | null}
*/
const getActions = () => elementByClass(swalClasses.actions);
/**
* @returns {HTMLElement | null}
*/
const getFooter = () => elementByClass(swalClasses.footer);
/**
* @returns {HTMLElement | null}
*/
const getTimerProgressBar = () => elementByClass(swalClasses['timer-progress-bar']);
/**
* @returns {HTMLElement | null}
*/
const getCloseButton = () => elementByClass(swalClasses.close);
// <https://github.com/jkup/focusable/blob/master/index.js>
const focusable = `
a[href],
area[href],
input:not([disabled]),
select:not([disabled]),
textarea:not([disabled]),
button:not([disabled]),
iframe,
object,
embed,
[tabindex="0"],
[contenteditable],
audio[controls],
video[controls],
summary
`;
/**
* @returns {HTMLElement[]}
*/
const getFocusableElements = () => {
const focusableElementsWithTabindex = Array.from(getPopup().querySelectorAll('[tabindex]:not([tabindex="-1"]):not([tabindex="0"])'))
// sort according to tabindex
.sort((a, b) => {
const tabindexA = parseInt(a.getAttribute('tabindex'));
const tabindexB = parseInt(b.getAttribute('tabindex'));
if (tabindexA > tabindexB) {
return 1;
} else if (tabindexA < tabindexB) {
return -1;
}
return 0;
});
const otherFocusableElements = Array.from(getPopup().querySelectorAll(focusable)).filter(el => el.getAttribute('tabindex') !== '-1');
return uniqueArray(focusableElementsWithTabindex.concat(otherFocusableElements)).filter(el => isVisible$1(el));
};
/**
* @returns {boolean}
*/
const isModal = () => {
return hasClass(document.body, swalClasses.shown) && !hasClass(document.body, swalClasses['toast-shown']) && !hasClass(document.body, swalClasses['no-backdrop']);
};
/**
* @returns {boolean}
*/
const isToast = () => {
return getPopup() && hasClass(getPopup(), swalClasses.toast);
};
/**
* @returns {boolean}
*/
const isLoading = () => {
return getPopup().hasAttribute('data-loading');
};
// Remember state in cases where opening and handling a modal will fiddle with it.
const states = {
previousBodyPadding: null
};
/**
* Securely set innerHTML of an element
* <https://github.com/sweetalert2/sweetalert2/issues/1926>
*
* @param {HTMLElement} elem
* @param {string} html
*/
const setInnerHtml = (elem, html) => {
elem.textContent = '';
if (html) {
const parser = new DOMParser();
const parsed = parser.parseFromString(html, `text/html`);
Array.from(parsed.querySelector('head').childNodes).forEach(child => {
elem.appendChild(child);
});
Array.from(parsed.querySelector('body').childNodes).forEach(child => {
if (child instanceof HTMLVideoElement || child instanceof HTMLAudioElement) {
elem.appendChild(child.cloneNode(true)); // <https://github.com/sweetalert2/sweetalert2/issues/2507>
} else {
elem.appendChild(child);
}
});
}
};
/**
* @param {HTMLElement} elem
* @param {string} className
* @returns {boolean}
*/
const hasClass = (elem, className) => {
if (!className) {
return false;
}
const classList = className.split(/\\s+/);
for (let i = 0; i < classList.length; i++) {
if (!elem.classList.contains(classList[i])) {
return false;
}
}
return true;
};
/**
* @param {HTMLElement} elem
* @param {SweetAlertOptions} params
*/
const removeCustomClasses = (elem, params) => {
Array.from(elem.classList).forEach(className => {
if (!Object.values(swalClasses).includes(className) && !Object.values(iconTypes).includes(className) && !Object.values(params.showClass).includes(className)) {
elem.classList.remove(className);
}
});
};
/**
* @param {HTMLElement} elem
* @param {SweetAlertOptions} params
* @param {string} className
*/
const applyCustomClass = (elem, params, className) => {
removeCustomClasses(elem, params);
if (params.customClass && params.customClass[className]) {
if (typeof params.customClass[className] !== 'string' && !params.customClass[className].forEach) {
warn(`Invalid type of customClass.${className}! Expected string or iterable object, got "${typeof params.customClass[className]}"`);
return;
}
addClass(elem, params.customClass[className]);
}
};
/**
* @param {HTMLElement} popup
* @param {import('./renderers/renderInput').InputClass} inputClass
* @returns {HTMLInputElement | null}
*/
const getInput$1 = (popup, inputClass) => {
if (!inputClass) {
return null;
}
switch (inputClass) {
case 'select':
case 'textarea':
case 'file':
return popup.querySelector(`.${swalClasses.popup} > .${swalClasses[inputClass]}`);
case 'checkbox':
return popup.querySelector(`.${swalClasses.popup} > .${swalClasses.checkbox} input`);
case 'radio':
return popup.querySelector(`.${swalClasses.popup} > .${swalClasses.radio} input:checked`) || popup.querySelector(`.${swalClasses.popup} > .${swalClasses.radio} input:first-child`);
case 'range':
return popup.querySelector(`.${swalClasses.popup} > .${swalClasses.range} input`);
default:
return popup.querySelector(`.${swalClasses.popup} > .${swalClasses.input}`);
}
};
/**
* @param {HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement} input
*/
const focusInput = input => {
input.focus();
// place cursor at end of text in text input
if (input.type !== 'file') {
// <http://stackoverflow.com/a/2345915>
const val = input.value;
input.value = '';
input.value = val;
}
};
/**
* @param {HTMLElement | HTMLElement[] | null} target
* @param {string | string[] | readonly string[]} classList
* @param {boolean} condition
*/
const toggleClass = (target, classList, condition) => {
if (!target || !classList) {
return;
}
if (typeof classList === 'string') {
classList = classList.split(/\\s+/).filter(Boolean);
}
classList.forEach(className => {
if (Array.isArray(target)) {
target.forEach(elem => {
condition ? elem.classList.add(className) : elem.classList.remove(className);
});
} else {
condition ? target.classList.add(className) : target.classList.remove(className);
}
});
};
/**
* @param {HTMLElement | HTMLElement[] | null} target
* @param {string | string[] | readonly string[]} classList
*/
const addClass = (target, classList) => {
toggleClass(target, classList, true);
};
/**
* @param {HTMLElement | HTMLElement[] | null} target
* @param {string | string[] | readonly string[]} classList
*/
const removeClass = (target, classList) => {
toggleClass(target, classList, false);
};
/**
* Get direct child of an element by class name
*
* @param {HTMLElement} elem
* @param {string} className
* @returns {HTMLElement | undefined}
*/
const getDirectChildByClass = (elem, className) => {
const children = Array.from(elem.children);
for (let i = 0; i < children.length; i++) {
const child = children[i];
if (child instanceof HTMLElement && hasClass(child, className)) {
return child;
}
}
};
/**
* @param {HTMLElement} elem
* @param {string} property
* @param {*} value
*/
const applyNumericalStyle = (elem, property, value) => {
if (value === `${parseInt(value)}`) {
value = parseInt(value);
}
if (value || parseInt(value) === 0) {
elem.style[property] = typeof value === 'number' ? `${value}px` : value;
} else {
elem.style.removeProperty(property);
}
};
/**
* @param {HTMLElement} elem
* @param {string} display
*/
const show = function (elem) {
let display = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'flex';
elem.style.display = display;
};
/**
* @param {HTMLElement} elem
*/
const hide = elem => {
elem.style.display = 'none';
};
/**
* @param {HTMLElement} parent
* @param {string} selector
* @param {string} property
* @param {string} value
*/
const setStyle = (parent, selector, property, value) => {
/** @type {HTMLElement} */
const el = parent.querySelector(selector);
if (el) {
el.style[property] = value;
}
};
/**
* @param {HTMLElement} elem
* @param {any} condition
* @param {string} display
*/
const toggle = function (elem, condition) {
let display = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'flex';
condition ? show(elem, display) : hide(elem);
};
/**
* borrowed from jquery $(elem).is(':visible') implementation
*
* @param {HTMLElement} elem
* @returns {boolean}
*/
const isVisible$1 = elem => !!(elem && (elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length));
/**
* @returns {boolean}
*/
const allButtonsAreHidden = () => !isVisible$1(getConfirmButton()) && !isVisible$1(getDenyButton()) && !isVisible$1(getCancelButton());
/**
* @param {HTMLElement} elem
* @returns {boolean}
*/
const isScrollable = elem => !!(elem.scrollHeight > elem.clientHeight);
/**
* borrowed from <https://stackoverflow.com/a/46352119>
*
* @param {HTMLElement} elem
* @returns {boolean}
*/
const hasCssAnimation = elem => {
const style = window.getComputedStyle(elem);
const animDuration = parseFloat(style.getPropertyValue('animation-duration') || '0');
const transDuration = parseFloat(style.getPropertyValue('transition-duration') || '0');
return animDuration > 0 || transDuration > 0;
};
/**
* @param {number} timer
* @param {boolean} reset
*/
const animateTimerProgressBar = function (timer) {
let reset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
const timerProgressBar = getTimerProgressBar();
if (isVisible$1(timerProgressBar)) {
if (reset) {
timerProgressBar.style.transition = 'none';
timerProgressBar.style.width = '100%';
}
setTimeout(() => {
timerProgressBar.style.transition = `width ${timer / 1000}s linear`;
timerProgressBar.style.width = '0%';
}, 10);
}
};
const stopTimerProgressBar = () => {
const timerProgressBar = getTimerProgressBar();
const timerProgressBarWidth = parseInt(window.getComputedStyle(timerProgressBar).width);
timerProgressBar.style.removeProperty('transition');
timerProgressBar.style.width = '100%';
const timerProgressBarFullWidth = parseInt(window.getComputedStyle(timerProgressBar).width);
const timerProgressBarPercent = timerProgressBarWidth / timerProgressBarFullWidth * 100;
timerProgressBar.style.width = `${timerProgressBarPercent}%`;
};
const RESTORE_FOCUS_TIMEOUT = 100;
/** @type {GlobalState} */
const globalState = {};
const focusPreviousActiveElement = () => {
if (globalState.previousActiveElement instanceof HTMLElement) {
globalState.previousActiveElement.focus();
globalState.previousActiveElement = null;
} else if (document.body) {
document.body.focus();
}
};
/**
* Restore previous active (focused) element
*
* @param {boolean} returnFocus
* @returns {Promise}
*/
const restoreActiveElement = returnFocus => {
return new Promise(resolve => {
if (!returnFocus) {
return resolve();
}
const x = window.scrollX;
const y = window.scrollY;
globalState.restoreFocusTimeout = setTimeout(() => {
focusPreviousActiveElement();
resolve();
}, RESTORE_FOCUS_TIMEOUT); // issues/900
window.scrollTo(x, y);
});
};
/**
* Detect Node env
*
* @returns {boolean}
*/
const isNodeEnv = () => typeof window === 'undefined' || typeof document === 'undefined';
const sweetHTML = `
<div aria-labelledby="${swalClasses.title}" aria-describedby="${swalClasses['html-container']}" class="${swalClasses.popup}" tabindex="-1">
<button type="button" class="${swalClasses.close}"></button>
<ul class="${swalClasses['progress-steps']}"></ul>
<div class="${swalClasses.icon}"></div>
<img class="${swalClasses.image}" />
<h2 class="${swalClasses.title}" id="${swalClasses.title}"></h2>
<div class="${swalClasses['html-container']}" id="${swalClasses['html-container']}"></div>
<input class="${swalClasses.input}" />
<input type="file" class="${swalClasses.file}" />
<div class="${swalClasses.range}">
<input type="range" />
<output></output>
</div>
<select class="${swalClasses.select}"></select>
<div class="${swalClasses.radio}"></div>
<label for="${swalClasses.checkbox}" class="${swalClasses.checkbox}">
<input type="checkbox" />
<span class="${swalClasses.label}"></span>
</label>
<textarea class="${swalClasses.textarea}"></textarea>
<div class="${swalClasses['validation-message']}" id="${swalClasses['validation-message']}"></div>
<div class="${swalClasses.actions}">
<div class="${swalClasses.loader}"></div>
<button type="button" class="${swalClasses.confirm}"></button>
<button type="button" class="${swalClasses.deny}"></button>
<button type="button" class="${swalClasses.cancel}"></button>
</div>
<div class="${swalClasses.footer}"></div>
<div class="${swalClasses['timer-progress-bar-container']}">
<div class="${swalClasses['timer-progress-bar']}"></div>
</div>
</div>
`.replace(/(^|\\n)\\s*/g, '');
/**
* @returns {boolean}
*/
const resetOldContainer = () => {
const oldContainer = getContainer();
if (!oldContainer) {
return false;
}
oldContainer.remove();
removeClass([document.documentElement, document.body], [swalClasses['no-backdrop'], swalClasses['toast-shown'], swalClasses['has-column']]);
return true;
};
const resetValidationMessage$1 = () => {
globalState.currentInstance.resetValidationMessage();
};
const addInputChangeListeners = () => {
const popup = getPopup();
const input = getDirectChildByClass(popup, swalClasses.input);
const file = getDirectChildByClass(popup, swalClasses.file);
/** @type {HTMLInputElement} */
const range = popup.querySelector(`.${swalClasses.range} input`);
/** @type {HTMLOutputElement} */
const rangeOutput = popup.querySelector(`.${swalClasses.range} output`);
const select = getDirectChildByClass(popup, swalClasses.select);
/** @type {HTMLInputElement} */
const checkbox = popup.querySelector(`.${swalClasses.checkbox} input`);
const textarea = getDirectChildByClass(popup, swalClasses.textarea);
input.oninput = resetValidationMessage$1;
file.onchange = resetValidationMessage$1;
select.onchange = resetValidationMessage$1;
checkbox.onchange = resetValidationMessage$1;
textarea.oninput = resetValidationMessage$1;
range.oninput = () => {
resetValidationMessage$1();
rangeOutput.value = range.value;
};
range.onchange = () => {
resetValidationMessage$1();
rangeOutput.value = range.value;
};
};
/**
* @param {string | HTMLElement} target
* @returns {HTMLElement}
*/
const getTarget = target => typeof target === 'string' ? document.querySelector(target) : target;
/**
* @param {SweetAlertOptions} params
*/
const setupAccessibility = params => {
const popup = getPopup();
popup.setAttribute('role', params.toast ? 'alert' : 'dialog');
popup.setAttribute('aria-live', params.toast ? 'polite' : 'assertive');
if (!params.toast) {
popup.setAttribute('aria-modal', 'true');
}
};
/**
* @param {HTMLElement} targetElement
*/
const setupRTL = targetElement => {
if (window.getComputedStyle(targetElement).direction === 'rtl') {
addClass(getContainer(), swalClasses.rtl);
}
};
/**
* @param {SweetAlertOptions} params
*/
const init = params => {
// Clean up the old popup container if it exists
const oldContainerExisted = resetOldContainer();
/* istanbul ignore if */
if (isNodeEnv()) {
error('SweetAlert2 requires document to initialize');
return;
}
const container = document.createElement('div');
container.className = swalClasses.container;
if (oldContainerExisted) {
addClass(container, swalClasses['no-transition']);
}
setInnerHtml(container, sweetHTML);
const targetElement = getTarget(params.target);
targetElement.appendChild(container);
setupAccessibility(params);
setupRTL(targetElement);
addInputChangeListeners();
};
/**
* @param {HTMLElement | object | string} param
* @param {HTMLElement} target
*/
const parseHtmlToContainer = (param, target) => {
// DOM element
if (param instanceof HTMLElement) {
target.appendChild(param);
}
// Object
else if (typeof param === 'object') {
handleObject(param, target);
}
// Plain string
else if (param) {
setInnerHtml(target, param);
}
};
/**
* @param {object} param
* @param {HTMLElement} target
*/
const handleObject = (param, target) => {
// JQuery element(s)
if (param.jquery) {
handleJqueryElem(target, param);
}
// For other objects use their string representation
else {
setInnerHtml(target, param.toString());
}
};
/**
* @param {HTMLElement} target
* @param {HTMLElement} elem
*/
const handleJqueryElem = (target, elem) => {
target.textContent = '';
if (0 in elem) {
for (let i = 0; (i in elem); i++) {
target.appendChild(elem[i].cloneNode(true));
}
} else {
target.appendChild(elem.cloneNode(true));
}
};
/**
* @returns {'webkitAnimationEnd' | 'animationend' | false}
*/
const animationEndEvent = (() => {
// Prevent run in Node env
/* istanbul ignore if */
if (isNodeEnv()) {
return false;
}
const testEl = document.createElement('div');
const transEndEventNames = {
WebkitAnimation: 'webkitAnimationEnd',
// Chrome, Safari and Opera
animation: 'animationend' // Standard syntax
};
for (const i in transEndEventNames) {
if (Object.prototype.hasOwnProperty.call(transEndEventNames, i) && typeof testEl.style[i] !== 'undefined') {
return transEndEventNames[i];
}
}
return false;
})();
/**
* Measure scrollbar width for padding body during modal show/hide
* <https://github.com/twbs/bootstrap/blob/master/js/src/modal.js>
*
* @returns {number}
*/
const measureScrollbar = () => {
const scrollDiv = document.createElement('div');
scrollDiv.className = swalClasses['scrollbar-measure'];
document.body.appendChild(scrollDiv);
const scrollbarWidth = scrollDiv.getBoundingClientRect().width - scrollDiv.clientWidth;
document.body.removeChild(scrollDiv);
return scrollbarWidth;
};
/**
* @param {SweetAlert2} instance
* @param {SweetAlertOptions} params
*/
const renderActions = (instance, params) => {
const actions = getActions();
const loader = getLoader();
// Actions (buttons) wrapper
if (!params.showConfirmButton && !params.showDenyButton && !params.showCancelButton) {
hide(actions);
} else {
show(actions);
}
// Custom class
applyCustomClass(actions, params, 'actions');
// Render all the buttons
renderButtons(actions, loader, params);
// Loader
setInnerHtml(loader, params.loaderHtml);
applyCustomClass(loader, params, 'loader');
};
/**
* @param {HTMLElement} actions
* @param {HTMLElement} loader
* @param {SweetAlertOptions} params
*/
function renderButtons(actions, loader, params) {
const confirmButton = getConfirmButton();
const denyButton = getDenyButton();
const cancelButton = getCancelButton();
// Render buttons
renderButton(confirmButton, 'confirm', params);
renderButton(denyButton, 'deny', params);
renderButton(cancelButton, 'cancel', params);
handleButtonsStyling(confirmButton, denyButton, cancelButton, params);
if (params.reverseButtons) {
if (params.toast) {
actions.insertBefore(cancelButton, confirmButton);
actions.insertBefore(denyButton, confirmButton);
} else {
actions.insertBefore(cancelButton, loader);
actions.insertBefore(denyButton, loader);
actions.insertBefore(confirmButton, loader);
}
}
}
/**
* @param {HTMLElement} confirmButton
* @param {HTMLElement} denyButton
* @param {HTMLElement} cancelButton
* @param {SweetAlertOptions} params
*/
function handleButtonsStyling(confirmButton, denyButton, cancelButton, params) {
if (!params.buttonsStyling) {
removeClass([confirmButton, denyButton, cancelButton], swalClasses.styled);
return;
}
addClass([confirmButton, denyButton, cancelButton], swalClasses.styled);
// Buttons background colors
if (params.confirmButtonColor) {
confirmButton.style.backgroundColor = params.confirmButtonColor;
addClass(confirmButton, swalClasses['default-outline']);
}
if (params.denyButtonColor) {
denyButton.style.backgroundColor = params.denyButtonColor;
addClass(denyButton, swalClasses['default-outline']);
}
if (params.cancelButtonColor) {
cancelButton.style.backgroundColor = params.cancelButtonColor;
addClass(cancelButton, swalClasses['default-outline']);
}
}
/**
* @param {HTMLElement} button
* @param {'confirm' | 'deny' | 'cancel'} buttonType
* @param {SweetAlertOptions} params
*/
function renderButton(button, buttonType, params) {
toggle(button, params[`show${capitalizeFirstLetter(buttonType)}Button`], 'inline-block');
setInnerHtml(button, params[`${buttonType}ButtonText`]); // Set caption text
button.setAttribute('aria-label', params[`${buttonType}ButtonAriaLabel`]); // ARIA label
// Add buttons custom classes
button.className = swalClasses[buttonType];
applyCustomClass(button, params, `${buttonType}Button`);
addClass(button, params[`${buttonType}ButtonClass`]);
}
/**
* @param {SweetAlert2} instance
* @param {SweetAlertOptions} params
*/
const renderCloseButton = (instance, params) => {
const closeButton = getCloseButton();
setInnerHtml(closeButton, params.closeButtonHtml);
// Custom class
applyCustomClass(closeButton, params, 'closeButton');
toggle(closeButton, params.showCloseButton);
closeButton.setAttribute('aria-label', params.closeButtonAriaLabel);
};
/**
* @param {SweetAlert2} instance
* @param {SweetAlertOptions} params
*/
const renderContainer = (instance, params) => {
const container = getContainer();
if (!container) {
return;
}
handleBackdropParam(container, params.backdrop);
handlePositionParam(container, params.position);
handleGrowParam(container, params.grow);
// Custom class
applyCustomClass(container, params, 'container');
};
/**
* @param {HTMLElement} container
* @param {SweetAlertOptions['backdrop']} backdrop
*/
function handleBackdropParam(container, backdrop) {
if (typeof backdrop === 'string') {
container.style.background = backdrop;
} else if (!backdrop) {
addClass([document.documentElement, document.body], swalClasses['no-backdrop']);
}
}
/**
* @param {HTMLElement} container
* @param {SweetAlertOptions['position']} position
*/
function handlePositionParam(container, position) {
if (position in swalClasses) {
addClass(container, swalClasses[position]);
} else {
warn('The "position" parameter is not valid, defaulting to "center"');
addClass(container, swalClasses.center);
}
}
/**
* @param {HTMLElement} container
* @param {SweetAlertOptions['grow']} grow
*/
function handleGrowParam(container, grow) {
if (grow && typeof grow === 'string') {
const growClass = `grow-${grow}`;
if (growClass in swalClasses) {
addClass(container, swalClasses[growClass]);
}
}
}
/// <reference path="../../../../sweetalert2.d.ts"/>
/** @type {InputClass[]} */
const inputClasses = ['input', 'file', 'range', 'select', 'radio', 'checkbox', 'textarea'];
/**
* @param {SweetAlert2} instance
* @param {SweetAlertOptions} params
*/
const renderInput = (instance, params) => {
const popup = getPopup();
const innerParams = privateProps.innerParams.get(instance);
const rerender = !innerParams || params.input !== innerParams.input;
inputClasses.forEach(inputClass => {
const inputContainer = getDirectChildByClass(popup, swalClasses[inputClass]);
// set attributes
setAttributes(inputClass, params.inputAttributes);
// set class
inputContainer.className = swalClasses[inputClass];
if (rerender) {
hide(inputContainer);
}
});
if (params.input) {
if (rerender) {
showInput(params);
}
// set custom class
setCustomClass(params);
}
};
/**
* @param {SweetAlertOptions} params
*/
const showInput = params => {
if (!renderInputType[params.input]) {
error(`Unexpected type of input! Expected "text", "email", "password", "number", "tel", "select", "radio", "checkbox", "textarea", "file" or "url", got "${params.input}"`);
return;
}
const inputContainer = getInputContainer(params.input);
const input = renderInputType[params.input](inputContainer, params);
show(inputContainer);
// input autofocus
if (params.inputAutoFocus) {
setTimeout(() => {
focusInput(input);
});
}
};
/**
* @param {HTMLInputElement} input
*/
const removeAttributes = input => {
for (let i = 0; i < input.attributes.length; i++) {
const attrName = input.attributes[i].name;
if (!['type', 'value', 'style'].includes(attrName)) {
input.removeAttribute(attrName);
}
}
};
/**
* @param {InputClass} inputClass
* @param {SweetAlertOptions['inputAttributes']} inputAttributes
*/
const setAttributes = (inputClass, inputAttributes) => {
const input = getInput$1(getPopup(), inputClass);
if (!input) {
return;
}
removeAttributes(input);
for (const attr in inputAttributes) {
input.setAttribute(attr, inputAttributes[attr]);
}
};
/**
* @param {SweetAlertOptions} params
*/
const setCustomClass = params => {
const inputContainer = getInputContainer(params.input);
if (typeof params.customClass === 'object') {
addClass(inputContainer, params.customClass.input);
}
};
/**
* @param {HTMLInputElement | HTMLTextAreaElement} input
* @param {SweetAlertOptions} params
*/
const setInputPlaceholder = (input, params) => {
if (!input.placeholder || params.inputPlaceholder) {
input.placeholder = params.inputPlaceholder;
}
};
/**
* @param {Input} input
* @param {Input} prependTo
* @param {SweetAlertOptions} params
*/
const setInputLabel = (input, prependTo, params) => {
if (params.inputLabel) {
input.id = swalClasses.input;
const label = document.createElement('label');
const labelClass = swalClasses['input-label'];
label.setAttribute('for', input.id);
label.className = labelClass;
if (typeof params.customClass === 'object') {
addClass(label, params.customClass.inputLabel);
}
label.innerText = params.inputLabel;
prependTo.insertAdjacentElement('beforebegin', label);
}
};
/**
* @param {SweetAlertOptions['input']} inputType
* @returns {HTMLElement}
*/
const getInputContainer = inputType => {
return getDirectChildByClass(getPopup(), swalClasses[inputType] || swalClasses.input);
};
/**
* @param {HTMLInputElement | HTMLOutputElement | HTMLTextAreaElement} input
* @param {SweetAlertOptions['inputValue']} inputValue
*/
const checkAndSetInputValue = (input, inputValue) => {
if (['string', 'number'].includes(typeof inputValue)) {
input.value = `${inputValue}`;
} else if (!isPromise(inputValue)) {
warn(`Unexpected type of inputValue! Expected "string", "number" or "Promise", got "${typeof inputValue}"`);
}
};
/** @type {Record<string, (input: Input | HTMLElement, params: SweetAlertOptions) => Input>} */
const renderInputType = {};
/**
* @param {HTMLInputElement} input
* @param {SweetAlertOptions} params
* @returns {HTMLInputElement}
*/
renderInputType.text = renderInputType.email = renderInputType.password = renderInputType.number = renderInputType.tel = renderInputType.url = (input, params) => {
checkAndSetInputValue(input, params.inputValue);
setInputLabel(input, input, params);
setInputPlaceholder(input, params);
input.type = params.input;
return input;
};
/**
* @param {HTMLInputElement} input
* @param {SweetAlertOptions} params
* @returns {HTMLInputElement}
*/
renderInputType.file = (input, params) => {
setInputLabel(input, input, params);
setInputPlaceholder(input, params);
return input;
};
/**
* @param {HTMLInputElement} range
* @param {SweetAlertOptions} params
* @returns {HTMLInputElement}
*/
renderInputType.range = (range, params) => {
const rangeInput = range.querySelector('input');
const rangeOutput = range.querySelector('output');
checkAndSetInputValue(rangeInput, params.inputValue);
rangeInput.type = params.input;
checkAndSetInputValue(rangeOutput, params.inputValue);
setInputLabel(rangeInput, range, params);
return range;
};
/**
* @param {HTMLSelectElement} select
* @param {SweetAlertOptions} params
* @returns {HTMLSelectElement}
*/
renderInputType.select = (select, params) => {
select.textContent = '';
if (params.inputPlaceholder) {
const placeholder = document.createElement('option');
setInnerHtml(placeholder, params.inputPlaceholder);
placeholder.value = '';
placeholder.disabled = true;
placeholder.selected = true;
select.appendChild(placeholder);
}
setInputLabel(select, select, params);
return select;
};
/**
* @param {HTMLInputElement} radio
* @returns {HTMLInputElement}
*/
renderInputType.radio = radio => {
radio.textContent = '';
return radio;
};
/**
* @param {HTMLLabelElement} checkboxContainer
* @param {SweetAlertOptions} params
* @returns {HTMLInputElement}
*/
renderInputType.checkbox = (checkboxContainer, params) => {
const checkbox = getInput$1(getPopup(), 'checkbox');
checkbox.value = '1';
checkbox.id = swalClasses.checkbox;
checkbox.checked = Boolean(params.inputValue);
const label = checkboxContainer.querySelector('span');
setInnerHtml(label, params.inputPlaceholder);
return checkbox;
};
/**
* @param {HTMLTextAreaElement} textarea
* @param {SweetAlertOptions} params
* @returns {HTMLTextAreaElement}
*/
renderInputType.textarea = (textarea, params) => {
checkAndSetInputValue(textarea, params.inputValue);
setInputPlaceholder(textarea, params);
setInputLabel(textarea, textarea, params);
/**
* @param {HTMLElement} el
* @returns {number}
*/
const getMargin = el => parseInt(window.getComputedStyle(el).marginLeft) + parseInt(window.getComputedStyle(el).marginRight);
// <https://github.com/sweetalert2/sweetalert2/issues/2291>
setTimeout(() => {
// <https://github.com/sweetalert2/sweetalert2/issues/1699>
if ('MutationObserver' in window) {
const initialPopupWidth = parseInt(window.getComputedStyle(getPopup()).width);
const textareaResizeHandler = () => {
const textareaWidth = textarea.offsetWidth + getMargin(textarea);
if (textareaWidth > initialPopupWidth) {
getPopup().style.width = `${textareaWidth}px`;
} else {
getPopup().style.width = null;
}
};
new MutationObserver(textareaResizeHandler).observe(textarea, {
attributes: true,
attributeFilter: ['style']
});
}
});
return textarea;
};
/**
* @param {SweetAlert2} instance
* @param {SweetAlertOptions} params
*/
const renderContent = (instance, params) => {
const htmlContainer = getHtmlContainer();
applyCustomClass(htmlContainer, params, 'htmlContainer');
// Content as HTML
if (params.html) {
parseHtmlToContainer(params.html, htmlContainer);
show(htmlContainer, 'block');
}
// Content as plain text
else if (params.text) {
htmlContainer.textContent = params.text;
show(htmlContainer, 'block');
}
// No content
else {
hide(htmlContainer);
}
renderInput(instance, params);
};
/**
* @param {SweetAlert2} instance
* @param {SweetAlertOptions} params
*/
const renderFooter = (instance, params) => {
const footer = getFooter();
toggle(footer, params.footer);
if (params.footer) {
parseHtmlToContainer(params.footer, footer);
}
// Custom class
applyCustomClass(footer, params, 'footer');
};
/**
* @param {SweetAlert2} instance
* @param {SweetAlertOptions} params
*/
const renderIcon = (instance, params) => {
const innerParams = privateProps.innerParams.get(instance);
const icon = getIcon();
// if the given icon already rendered, apply the styling without re-rendering the icon
if (innerParams && params.icon === innerParams.icon) {
// Custom or default content
setContent(icon, params);
applyStyles(icon, params);
return;
}
if (!params.icon && !params.iconHtml) {
hide(icon);
return;
}
if (params.icon && Object.keys(iconTypes).indexOf(params.icon) === -1) {
error(`Unknown icon! Expected "success", "error", "warning", "info" or "question", got "${params.icon}"`);
hide(icon);
return;
}
show(icon);
// Custom or default content
setContent(icon, params);
applyStyles(icon, params);
// Animate icon
addClass(icon, params.showClass.icon);
};
/**
* @param {HTMLElement} icon
* @param {SweetAlertOptions} params
*/
const applyStyles = (icon, params) => {
for (const iconType in iconTypes) {
if (params.icon !== iconType) {
removeClass(icon, iconTypes[iconType]);
}
}
addClass(icon, iconTypes[params.icon]);
// Icon color
setColor(icon, params);
// Success icon background color
adjustSuccessIconBackgroundColor();
// Custom class
applyCustomClass(icon, params, 'icon');
};
// Adjust success icon background color to match the popup background color
const adjustSuccessIconBackgroundColor = () => {
const popup = getPopup();
const popupBackgroundColor = window.getComputedStyle(popup).getPropertyValue('background-color');
/** @type {NodeListOf<HTMLElement>} */
const successIconParts = popup.querySelectorAll('[class^=swal2-success-circular-line], .swal2-success-fix');
for (let i = 0; i < successIconParts.length; i++) {
successIconParts[i].style.backgroundColor = popupBackgroundColor;
}
};
const successIconHtml = `
<div class="swal2-success-circular-line-left"></div>
<span class="swal2-success-line-tip"></span> <span class="swal2-success-line-long"></span>
<div class="swal2-success-ring"></div> <div class="swal2-success-fix"></div>
<div class="swal2-success-circular-line-right"></div>
`;
const errorIconHtml = `
<span class="swal2-x-mark">
<span class="swal2-x-mark-line-left"></span>
<span class="swal2-x-mark-line-right"></span>
</span>
`;
/**
* @param {HTMLElement} icon
* @param {SweetAlertOptions} params
*/
const setContent = (icon, params) => {
let oldContent = icon.innerHTML;
let newContent;
if (params.iconHtml) {
newContent = iconContent(params.iconHtml);
} else if (params.icon === 'success') {
newContent = successIconHtml;
oldContent = oldContent.replace(/ style=".*?"/g, ''); // undo adjustSuccessIconBackgroundColor()
} else if (params.icon === 'error') {
newContent = errorIconHtml;
} else {
const defaultIconHtml = {
question: '?',
warning: '!',
info: 'i'
};
newContent = iconContent(defaultIconHtml[params.icon]);
}
if (oldContent.trim() !== newContent.trim()) {
setInnerHtml(icon, newContent);
}
};
/**
* @param {HTMLElement} icon
* @param {SweetAlertOptions} params
*/
const setColor = (icon, params) => {
if (!params.iconColor) {
return;
}
icon.style.color = params.iconColor;
icon.style.borderColor = params.iconColor;
for (const sel of ['.swal2-success-line-tip', '.swal2-success-line-long', '.swal2-x-mark-line-left', '.swal2-x-mark-line-right']) {
setStyle(icon, sel, 'backgroundColor', params.iconColor);
}
setStyle(icon, '.swal2-success-ring', 'borderColor', params.iconColor);
};
/**
* @param {string} content
* @returns {string}
*/
const iconContent = content => `<div class="${swalClasses['icon-content']}">${content}</div>`;
/**
* @param {SweetAlert2} instance
* @param {SweetAlertOptions} params
*/
const renderImage = (instance, params) => {
const image = getImage();
if (!params.imageUrl) {
hide(image);
return;
}
show(image, '');
// Src, alt
image.setAttribute('src', params.imageUrl);
image.setAttribute('alt', params.imageAlt);
// Width, height
applyNumericalStyle(image, 'width', params.imageWidth);
applyNumericalStyle(image, 'height', params.imageHeight);
// Class
image.className = swalClasses.image;
applyCustomClass(image, params, 'image');
};
/**
* @param {SweetAlert2} instance
* @param {SweetAlertOptions} params
*/
const renderPopup = (instance, params) => {
const container = getContainer();
const popup = getPopup();
// Width
// <https://github.com/sweetalert2/sweetalert2/issues/2170>
if (params.toast) {
applyNumericalStyle(container, 'width', params.width);
popup.style.width = '100%';
popup.insertBefore(getLoader(), getIcon());
} else {
applyNumericalStyle(popup, 'width', params.width);
}
// Padding
applyNumericalStyle(popup, 'padding', params.padding);
// Color
if (params.color) {
popup.style.color = params.color;
}
// Background
if (params.background) {
popup.style.background = params.background;
}
hide(getValidationMessage());
// Classes
addClasses$1(popup, params);
};
/**
* @param {HTMLElement} popup
* @param {SweetAlertOptions} params
*/
const addClasses$1 = (popup, params) => {
// Default Class + showClass when updating Swal.update({})
popup.className = `${swalClasses.popup} ${isVisible$1(popup) ? params.showClass.popup : ''}`;
if (params.toast) {
addClass([document.documentElement, document.body], swalClasses['toast-shown']);
addClass(popup, swalClasses.toast);
} else {
addClass(popup, swalClasses.modal);
}
// Custom class
applyCustomClass(popup, params, 'popup');
if (typeof params.customClass === 'string') {
addClass(popup, params.customClass);
}
// Icon class (#1842)
if (params.icon) {
addClass(popup, swalClasses[`icon-${params.icon}`]);
}
};
/**
* @param {SweetAlert2} instance
* @param {SweetAlertOptions} params
*/
const renderProgressSteps = (instance, params) => {
const progressStepsContainer = getProgressSteps();
if (!params.progressSteps || params.progressSteps.length === 0) {
hide(progressStepsContainer);
return;
}
show(progressStepsContainer);
progressStepsContainer.textContent = '';
if (params.currentProgressStep >= params.progressSteps.length) {
warn('Invalid currentProgressStep parameter, it should be less than progressSteps.length ' + '(currentProgressStep like JS arrays starts from 0)');
}
params.progressSteps.forEach((step, index) => {
const stepEl = createStepElement(step);
progressStepsContainer.appendChild(stepEl);
if (index === params.currentProgressStep) {
addClass(stepEl, swalClasses['active-progress-step']);
}
if (index !== params.progressSteps.length - 1) {
const lineEl = createLineElement(params);
progressStepsContainer.appendChild(lineEl);
}
});
};
/**
* @param {string} step
* @returns {HTMLLIElement}
*/
const createStepElement = step => {
const stepEl = document.createElement('li');
addClass(stepEl, swalClasses['progress-step']);
setInnerHtml(stepEl, step);
return stepEl;
};
/**
* @param {SweetAlertOptions} params
* @returns {HTMLLIElement}
*/
const createLineElement = params => {
const lineEl = document.createElement('li');
addClass(lineEl, swalClasses['progress-step-line']);
if (params.progressStepsDistance) {
applyNumericalStyle(lineEl, 'width', params.progressStepsDistance);
}
return lineEl;
};
/**
* @param {SweetAlert2} instance
* @param {SweetAlertOptions} params
*/
const renderTitle = (instance, params) => {
const title = getTitle();
toggle(title, params.title || params.titleText, 'block');
if (params.title) {
parseHtmlToContainer(params.title, title);
}
if (params.titleText) {
title.innerText = params.titleText;
}
// Custom class
applyCustomClass(title, params, 'title');
};
/**
* @param {SweetAlert2} instance
* @param {SweetAlertOptions} params
*/
const render = (instance, params) => {
renderPopup(instance, params);
renderContainer(instance, params);
renderProgressSteps(instance, params);
renderIcon(instance, params);
renderImage(instance, params);
renderTitle(instance, params);
renderCloseButton(instance, params);
renderContent(instance, params);
renderActions(instance, params);
renderFooter(instance, params);
if (typeof params.didRender === 'function') {
params.didRender(getPopup());
}
};
/**
* Hides loader and shows back the button which was hidden by .showLoading()
*/
function hideLoading() {
// do nothing if popup is closed
const innerParams = privateProps.innerParams.get(this);
if (!innerParams) {
return;
}
const domCache = privateProps.domCache.get(this);
hide(domCache.loader);
if (isToast()) {
if (innerParams.icon) {
show(getIcon());
}
} else {
showRelatedButton(domCache);
}
removeClass([domCache.popup, domCache.actions], swalClasses.loading);
domCache.popup.removeAttribute('aria-busy');
domCache.popup.removeAttribute('data-loading');
domCache.confirmButton.disabled = false;
domCache.denyButton.disabled = false;
domCache.cancelButton.disabled = false;
}
const showRelatedButton = domCache => {
const buttonToReplace = domCache.popup.getElementsByClassName(domCache.loader.getAttribute('data-button-to-replace'));
if (buttonToReplace.length) {
show(buttonToReplace[0], 'inline-block');
} else if (allButtonsAreHidden()) {
hide(domCache.actions);
}
};
/**
* Gets the input DOM node, this method works with input parameter.
*
* @param {SweetAlert2} instance
* @returns {HTMLElement | null}
*/
function getInput(instance) {
const innerParams = privateProps.innerParams.get(instance || this);
const domCache = privateProps.domCache.get(instance || this);
if (!domCache) {
return null;
}
return getInput$1(domCache.popup, innerParams.input);
}
/*
* Global function to determine if SweetAlert2 popup is shown
*/
const isVisible = () => {
return isVisible$1(getPopup());
};
/*
* Global function to click 'Confirm' button
*/
const clickConfirm = () => getConfirmButton() && getConfirmButton().click();
/*
* Global function to click 'Deny' button
*/
const clickDeny = () => getDenyButton() && getDenyButton().click();
/*
* Global function to click 'Cancel' button
*/
const clickCancel = () => getCancelButton() && getCancelButton().click();
const DismissReason = Object.freeze({
cancel: 'cancel',
backdrop: 'backdrop',
close: 'close',
esc: 'esc',
timer: 'timer'
});
/**
* @param {GlobalState} globalState
*/
const removeKeydownHandler = globalState => {
if (globalState.keydownTarget && globalState.keydownHandlerAdded) {
globalState.keydownTarget.removeEventListener('keydown', globalState.keydownHandler, {
capture: globalState.keydownListenerCapture
});
globalState.keydownHandlerAdded = false;
}
};
/**
* @param {SweetAlert2} instance
* @param {GlobalState} globalState
* @param {SweetAlertOptions} innerParams
* @param {*} dismissWith
*/
const addKeydownHandler = (instance, globalState, innerParams, dismissWith) => {
removeKeydownHandler(globalState);
if (!innerParams.toast) {
globalState.keydownHandler = e => keydownHandler(instance, e, dismissWith);
globalState.keydownTarget = innerParams.keydownListenerCapture ? window : getPopup();
globalState.keydownListenerCapture = innerParams.keydownListenerCapture;
globalState.keydownTarget.addEventListener('keydown', globalState.keydownHandler, {
capture: globalState.keydownListenerCapture
});
globalState.keydownHandlerAdded = true;
}
};
/**
* @param {number} index
* @param {number} increment
*/
const setFocus = (index, increment) => {
const focusableElements = getFocusableElements();
// search for visible elements and select the next possible match
if (focusableElements.length) {
index = index + increment;
// rollover to first item
if (index === focusableElements.length) {
index = 0;
// go to last item
} else if (index === -1) {
index = focusableElements.length - 1;
}
focusableElements[index].focus();
return;
}
// no visible focusable elements, focus the popup
getPopup().focus();
};
const arrowKeysNextButton = ['ArrowRight', 'ArrowDown'];
const arrowKeysPreviousButton = ['ArrowLeft', 'ArrowUp'];
/**
* @param {SweetAlert2} instance
* @param {KeyboardEvent} event
* @param {Function} dismissWith
*/
const keydownHandler = (instance, event, dismissWith) => {
const innerParams = privateProps.innerParams.get(instance);
if (!innerParams) {
return; // This instance has already been destroyed
}
// Ignore keydown during IME composition
// <https://developer.mozilla.org/en-US/docs/Web/API/Document/keydown_event#ignoring_keydown_during_ime_composition>
// <https://github.com/sweetalert2/sweetalert2/issues/720>
// <https://github.com/sweetalert2/sweetalert2/issues/2406>
if (event.isComposing || event.keyCode === 229) {
return;
}
if (innerParams.stopKeydownPropagation) {
event.stopPropagation();
}
// ENTER
if (event.key === 'Enter') {
handleEnter(instance, event, innerParams);
}
// TAB
else if (event.key === 'Tab') {
handleTab(event);
}
// ARROWS - switch focus between buttons
else if ([...arrowKeysNextButton, ...arrowKeysPreviousButton].includes(event.key)) {
handleArrows(event.key);
}
// ESC
else if (event.key === 'Escape') {
handleEsc(event, innerParams, dismissWith);
}
};
/**
* @param {SweetAlert2} instance
* @param {KeyboardEvent} event
* @param {SweetAlertOptions} innerParams
*/
const handleEnter = (instance, event, innerParams) => {
// <https://github.com/sweetalert2/sweetalert2/issues/2386>
if (!callIfFunction(innerParams.allowEnterKey)) {
return;
}
if (event.target && instance.getInput() && event.target instanceof HTMLElement && event.target.outerHTML === instance.getInput().outerHTML) {
if (['textarea', 'file'].includes(innerParams.input)) {
return; // do not submit
}
clickConfirm();
event.preventDefault();
}
};
/**
* @param {KeyboardEvent} event
*/
const handleTab = event => {
const targetElement = event.target;
const focusableElements = getFocusableElements();
let btnIndex = -1;
for (let i = 0; i < focusableElements.length; i++) {
if (targetElement === focusableElements[i]) {
btnIndex = i;
break;
}
}
// Cycle to the next button
if (!event.shiftKey) {
setFocus(btnIndex, 1);
}
// Cycle to the prev button
else {
setFocus(btnIndex, -1);
}
event.stopPropagation();
event.preventDefault();
};
/**
* @param {string} key
*/
const handleArrows = key => {
const confirmButton = getConfirmButton();
const denyButton = getDenyButton();
const cancelButton = getCancelButton();
/** @type HTMLElement[] */
const buttons = [confirmButton, denyButton, cancelButton];
if (document.activeElement instanceof HTMLElement && !buttons.includes(document.activeElement)) {
return;
}
const sibling = arrowKeysNextButton.includes(key) ? 'nextElementSibling' : 'previousElementSibling';
let buttonToFocus = document.activeElement;
for (let i = 0; i < getActions().children.length; i++) {
buttonToFocus = buttonToFocus[sibling];
if (!buttonToFocus) {
return;
}
if (buttonToFocus instanceof HTMLButtonElement && isVisible$1(buttonToFocus)) {
break;
}
}
if (buttonToFocus instanceof HTMLButtonElement) {
buttonToFocus.focus();
}
};
/**
* @param {KeyboardEvent} event
* @param {SweetAlertOptions} innerParams
* @param {Function} dismissWith
*/
const handleEsc = (event, innerParams, dismissWith) => {
if (callIfFunction(innerParams.allowEscapeKey)) {
event.preventDefault();
dismissWith(DismissReason.esc);
}
};
/**
* This module contains `WeakMap`s for each effectively-"private property" that a `Swal` has.
* For example, to set the private property "foo" of `this` to "bar", you can `privateProps.foo.set(this, 'bar')`
* This is the approach that Babel will probably take to implement private methods/fields
* <https://github.com/tc39/proposal-private-methods>
* <https://github.com/babel/babel/pull/7555>
* Once we have the changes from that PR in Babel, and our core class fits reasonable in *one module*
* then we can use that language feature.
*/
var privateMethods = {
swalPromiseResolve: new WeakMap(),
swalPromiseReject: new WeakMap()
};
// From <https://developer.paciellogroup.com/blog/2018/06/the-current-state-of-modal-dialog-accessibility/>
// Adding aria-hidden="true" to elements outside of the active modal dialog ensures that
// elements not within the active modal dialog will not be surfaced if a user opens a screen
// reader’s list of elements (headings, form controls, landmarks, etc.) in the document.
const setAriaHidden = () => {
const bodyChildren = Array.from(document.body.children);
bodyChildren.forEach(el => {
if (el === getContainer() || el.contains(getContainer())) {
return;
}
if (el.hasAttribute('aria-hidden')) {
el.setAttribute('data-previous-aria-hidden', el.getAttribute('aria-hidden'));
}
el.setAttribute('aria-hidden', 'true');
});
};
const unsetAriaHidden = () => {
const bodyChildren = Array.from(document.body.children);
bodyChildren.forEach(el => {
if (el.hasAttribute('data-previous-aria-hidden')) {
el.setAttribute('aria-hidden', el.getAttribute('data-previous-aria-hidden'));
el.removeAttribute('data-previous-aria-hidden');
} else {
el.removeAttribute('aria-hidden');
}
});
};
/* istanbul ignore file */
// Fix iOS scrolling <http://stackoverflow.com/q/39626302>
const iOSfix = () => {
const iOS =
// @ts-ignore
/iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream || navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1;
if (iOS && !hasClass(document.body, swalClasses.iosfix)) {
const offset = document.body.scrollTop;
document.body.style.top = `${offset * -1}px`;
addClass(document.body, swalClasses.iosfix);
lockBodyScroll();
addBottomPaddingForTallPopups();
}
};
/**
* <https://github.com/sweetalert2/sweetalert2/issues/1948>
*/
const addBottomPaddingForTallPopups = () => {
const ua = navigator.userAgent;
const iOS = !!ua.match(/iPad/i) || !!ua.match(/iPhone/i);
const webkit = !!ua.match(/WebKit/i);
const iOSSafari = iOS && webkit && !ua.match(/CriOS/i);
if (iOSSafari) {
const bottomPanelHeight = 44;
if (getPopup().scrollHeight > window.innerHeight - bottomPanelHeight) {
getContainer().style.paddingBottom = `${bottomPanelHeight}px`;
}
}
};
/**
* <https://github.com/sweetalert2/sweetalert2/issues/1246>
*/
const lockBodyScroll = () => {
const container = getContainer();
let preventTouchMove;
/**
* @param {TouchEvent} event
*/
container.ontouchstart = event => {
preventTouchMove = shouldPreventTouchMove(event);
};
/**
* @param {TouchEvent} event
*/
container.ontouchmove = event => {
if (preventTouchMove) {
event.preventDefault();
event.stopPropagation();
}
};
};
/**
* @param {TouchEvent} event
* @returns {boolean}
*/
const shouldPreventTouchMove = event => {
const target = event.target;
const container = getContainer();
if (isStylus(event) || isZoom(event)) {
return false;
}
if (target === container) {
return true;
}
if (!isScrollable(container) && target instanceof HTMLElement && target.tagName !== 'INPUT' &&
// #1603
target.tagName !== 'TEXTAREA' &&
// #2266
!(isScrollable(getHtmlContainer()) &&
// #1944
getHtmlContainer().contains(target))) {
return true;
}
return false;
};
/**
* <https://github.com/sweetalert2/sweetalert2/issues/1786>
*
* @param {*} event
* @returns {boolean}
*/
const isStylus = event => {
return event.touches && event.touches.length && event.touches[0].touchType === 'stylus';
};
/**
* <https://github.com/sweetalert2/sweetalert2/issues/1891>
*
* @param {TouchEvent} event
* @returns {boolean}
*/
const isZoom = event => {
return event.touches && event.touches.length > 1;
};
const undoIOSfix = () => {
if (hasClass(document.body, swalClasses.iosfix)) {
const offset = parseInt(document.body.style.top, 10);
removeClass(document.body, swalClasses.iosfix);
document.body.style.top = '';
document.body.scrollTop = offset * -1;
}
};
const fixScrollbar = () => {
// for queues, do not do this more than once
if (states.previousBodyPadding !== null) {
return;
}
// if the body has overflow
if (document.body.scrollHeight > window.innerHeight) {
// add padding so the content doesn't shift after removal of scrollbar
states.previousBodyPadding = parseInt(window.getComputedStyle(document.body).getPropertyValue('padding-right'));
document.body.style.paddingRight = `${states.previousBodyPadding + measureScrollbar()}px`;
}
};
const undoScrollbar = () => {
if (states.previousBodyPadding !== null) {
document.body.style.paddingRight = `${states.previousBodyPadding}px`;
states.previousBodyPadding = null;
}
};
/*
* Instance method to close sweetAlert
*/
function removePopupAndResetState(instance, container, returnFocus, didClose) {
if (isToast()) {
triggerDidCloseAndDispose(instance, didClose);
} else {
restoreActiveElement(returnFocus).then(() => triggerDidCloseAndDispose(instance, didClose));
removeKeydownHandler(globalState);
}
const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
// workaround for #2088
// for some reason removing the container in Safari will scroll the document to bottom
if (isSafari) {
container.setAttribute('style', 'display:none !important');
container.removeAttribute('class');
container.innerHTML = '';
} else {
container.remove();
}
if (isModal()) {
undoScrollbar();
undoIOSfix();
unsetAriaHidden();
}
removeBodyClasses();
}
function removeBodyClasses() {
removeClass([document.documentElement, document.body], [swalClasses.shown, swalClasses['height-auto'], swalClasses['no-backdrop'], swalClasses['toast-shown']]);
}
function close(resolveValue) {
resolveValue = prepareResolveValue(resolveValue);
const swalPromiseResolve = privateMethods.swalPromiseResolve.get(this);
const didClose = triggerClosePopup(this);
if (this.isAwaitingPromise()) {
// A swal awaiting for a promise (after a click on Confirm or Deny) cannot be dismissed anymore #2335
if (!resolveValue.isDismissed) {
handleAwaitingPromise(this);
swalPromiseResolve(resolveValue);
}
} else if (didClose) {
// Resolve Swal promise
swalPromiseResolve(resolveValue);
}
}
function isAwaitingPromise() {
return !!privateProps.awaitingPromise.get(this);
}
const triggerClosePopup = instance => {
const popup = getPopup();
if (!popup) {
return false;
}
const innerParams = privateProps.innerParams.get(instance);
if (!innerParams || hasClass(popup, innerParams.hideClass.popup)) {
return false;
}
removeClass(popup, innerParams.showClass.popup);
addClass(popup, innerParams.hideClass.popup);
const backdrop = getContainer();
removeClass(backdrop, innerParams.showClass.backdrop);
addClass(backdrop, innerParams.hideClass.backdrop);
handlePopupAnimation(instance, popup, innerParams);
return true;
};
function rejectPromise(error) {
const rejectPromise = privateMethods.swalPromiseReject.get(this);
handleAwaitingPromise(this);
if (rejectPromise) {
// Reject Swal promise
rejectPromise(error);
}
}
const handleAwaitingPromise = instance => {
if (instance.isAwaitingPromise()) {
privateProps.awaitingPromise.delete(instance);
// The instance might have been previously partly destroyed, we must resume the destroy process in this case #2335
if (!privateProps.innerParams.get(instance)) {
instance._destroy();
}
}
};
const prepareResolveValue = resolveValue => {
// When user calls Swal.close()
if (typeof resolveValue === 'undefined') {
return {
isConfirmed: false,
isDenied: false,
isDismissed: true
};
}
return Object.assign({
isConfirmed: false,
isDenied: false,
isDismissed: false
}, resolveValue);
};
const handlePopupAnimation = (instance, popup, innerParams) => {
const container = getContainer();
// If animation is supported, animate
const animationIsSupported = animationEndEvent && hasCssAnimation(popup);
if (typeof innerParams.willClose === 'function') {
innerParams.willClose(popup);
}
if (animationIsSupported) {
animatePopup(instance, popup, container, innerParams.returnFocus, innerParams.didClose);
} else {
// Otherwise, remove immediately
removePopupAndResetState(instance, container, innerParams.returnFocus, innerParams.didClose);
}
};
const animatePopup = (instance, popup, container, returnFocus, didClose) => {
globalState.swalCloseEventFinishedCallback = removePopupAndResetState.bind(null, instance, container, returnFocus, didClose);
popup.addEventListener(animationEndEvent, function (e) {
if (e.target === popup) {
globalState.swalCloseEventFinishedCallback();
delete globalState.swalCloseEventFinishedCallback;
}
});
};
const triggerDidCloseAndDispose = (instance, didClose) => {
setTimeout(() => {
if (typeof didClose === 'function') {
didClose.bind(instance.params)();
}
instance._destroy();
});
};
/**
* @param {SweetAlert2} instance
* @param {string[]} buttons
* @param {boolean} disabled
*/
function setButtonsDisabled(instance, buttons, disabled) {
const domCache = privateProps.domCache.get(instance);
buttons.forEach(button => {
domCache[button].disabled = disabled;
});
}
/**
* @param {HTMLInputElement} input
* @param {boolean} disabled
*/
function setInputDisabled(input, disabled) {
if (!input) {
return;
}
if (input.type === 'radio') {
const radiosContainer = input.parentNode.parentNode;
const radios = radiosContainer.querySelectorAll('input');
for (let i = 0; i < radios.length; i++) {
radios[i].disabled = disabled;
}
} else {
input.disabled = disabled;
}
}
function enableButtons() {
setButtonsDisabled(this, ['confirmButton', 'denyButton', 'cancelButton'], false);
}
function disableButtons() {
setButtonsDisabled(this, ['confirmButton', 'denyButton', 'cancelButton'], true);
}
function enableInput() {
setInputDisabled(this.getInput(), false);
}
function disableInput() {
setInputDisabled(this.getInput(), true);
}
/**
* Show block with validation message
*
* @param {string} error
*/
function showValidationMessage(error) {
const domCache = privateProps.domCache.get(this);
const params = privateProps.innerParams.get(this);
setInnerHtml(domCache.validationMessage, error);
domCache.validationMessage.className = swalClasses['validation-message'];
if (params.customClass && params.customClass.validationMessage) {
addClass(domCache.validationMessage, params.customClass.validationMessage);
}
show(domCache.validationMessage);
const input = this.getInput();
if (input) {
input.setAttribute('aria-invalid', true);
input.setAttribute('aria-describedby', swalClasses['validation-message']);
focusInput(input);
addClass(input, swalClasses.inputerror);
}
}
/**
* Hide block with validation message
*/
function resetValidationMessage() {
const domCache = privateProps.domCache.get(this);
if (domCache.validationMessage) {
hide(domCache.validationMessage);
}
const input = this.getInput();
if (input) {
input.removeAttribute('aria-invalid');
input.removeAttribute('aria-describedby');
removeClass(input, swalClasses.inputerror);
}
}
const defaultParams = {
title: '',
titleText: '',
text: '',
html: '',
footer: '',
icon: undefined,
iconColor: undefined,
iconHtml: undefined,
template: undefined,
toast: false,
showClass: {
popup: 'swal2-show',
backdrop: 'swal2-backdrop-show',
icon: 'swal2-icon-show'
},
hideClass: {
popup: 'swal2-hide',
backdrop: 'swal2-backdrop-hide',
icon: 'swal2-icon-hide'
},
customClass: {},
target: 'body',
color: undefined,
backdrop: true,
heightAuto: true,
allowOutsideClick: true,
allowEscapeKey: true,
allowEnterKey: true,
stopKeydownPropagation: true,
keydownListenerCapture: false,
showConfirmButton: true,
showDenyButton: false,
showCancelButton: false,
preConfirm: undefined,
preDeny: undefined,
confirmButtonText: 'OK',
confirmButtonAriaLabel: '',
confirmButtonColor: undefined,
denyButtonText: 'No',
denyButtonAriaLabel: '',
denyButtonColor: undefined,
cancelButtonText: 'Cancel',
cancelButtonAriaLabel: '',
cancelButtonColor: undefined,
buttonsStyling: true,
reverseButtons: false,
focusConfirm: true,
focusDeny: false,
focusCancel: false,
returnFocus: true,
showCloseButton: false,
closeButtonHtml: '×',
closeButtonAriaLabel: 'Close this dialog',
loaderHtml: '',
showLoaderOnConfirm: false,
showLoaderOnDeny: false,
imageUrl: undefined,
imageWidth: undefined,
imageHeight: undefined,
imageAlt: '',
timer: undefined,
timerProgressBar: false,
width: undefined,
padding: undefined,
background: undefined,
input: undefined,
inputPlaceholder: '',
inputLabel: '',
inputValue: '',
inputOptions: {},
inputAutoFocus: true,
inputAutoTrim: true,
inputAttributes: {},
inputValidator: undefined,
returnInputValueOnDeny: false,
validationMessage: undefined,
grow: false,
position: 'center',
progressSteps: [],
currentProgressStep: undefined,
progressStepsDistance: undefined,
willOpen: undefined,
didOpen: undefined,
didRender: undefined,
willClose: undefined,
didClose: undefined,
didDestroy: undefined,
scrollbarPadding: true
};
const updatableParams = ['allowEscapeKey', 'allowOutsideClick', 'background', 'buttonsStyling', 'cancelButtonAriaLabel', 'cancelButtonColor', 'cancelButtonText', 'closeButtonAriaLabel', 'closeButtonHtml', 'color', 'confirmButtonAriaLabel', 'confirmButtonColor', 'confirmButtonText', 'currentProgressStep', 'customClass', 'denyButtonAriaLabel', 'denyButtonColor', 'denyButtonText', 'didClose', 'didDestroy', 'footer', 'hideClass', 'html', 'icon', 'iconColor', 'iconHtml', 'imageAlt', 'imageHeight', 'imageUrl', 'imageWidth', 'preConfirm', 'preDeny', 'progressSteps', 'returnFocus', 'reverseButtons', 'showCancelButton', 'showCloseButton', 'showConfirmButton', 'showDenyButton', 'text', 'title', 'titleText', 'willClose'];
const deprecatedParams = {};
const toastIncompatibleParams = ['allowOutsideClick', 'allowEnterKey', 'backdrop', 'focusConfirm', 'focusDeny', 'focusCancel', 'returnFocus', 'heightAuto', 'keydownListenerCapture'];
/**
* Is valid parameter
*
* @param {string} paramName
* @returns {boolean}
*/
const isValidParameter = paramName => {
return Object.prototype.hasOwnProperty.call(defaultParams, paramName);
};
/**
* Is valid parameter for Swal.update() method
*
* @param {string} paramName
* @returns {boolean}
*/
const isUpdatableParameter = paramName => {
return updatableParams.indexOf(paramName) !== -1;
};
/**
* Is deprecated parameter
*
* @param {string} paramName
* @returns {string | undefined}
*/
const isDeprecatedParameter = paramName => {
return deprecatedParams[paramName];
};
/**
* @param {string} param
*/
const checkIfParamIsValid = param => {
if (!isValidParameter(param)) {
warn(`Unknown parameter "${param}"`);
}
};
/**
* @param {string} param
*/
const checkIfToastParamIsValid = param => {
if (toastIncompatibleParams.includes(param)) {
warn(`The parameter "${param}" is incompatible with toasts`);
}
};
/**
* @param {string} param
*/
const checkIfParamIsDeprecated = param => {
if (isDeprecatedParameter(param)) {
warnAboutDeprecation(param, isDeprecatedParameter(param));
}
};
/**
* Show relevant warnings for given params
*
* @param {SweetAlertOptions} params
*/
const showWarningsForParams = params => {
if (params.backdrop === false && params.allowOutsideClick) {
warn('"allowOutsideClick" parameter requires `backdrop` parameter to be set to `true`');
}
for (const param in params) {
checkIfParamIsValid(param);
if (params.toast) {
checkIfToastParamIsValid(param);
}
checkIfParamIsDeprecated(param);
}
};
/**
* Updates popup parameters.
*
* @param {SweetAlertOptions} params
*/
function update(params) {
const popup = getPopup();
const innerParams = privateProps.innerParams.get(this);
if (!popup || hasClass(popup, innerParams.hideClass.popup)) {
warn(`You're trying to update the closed or closing popup, that won't work. Use the update() method in preConfirm parameter or show a new popup.`);
return;
}
const validUpdatableParams = filterValidParams(params);
const updatedParams = Object.assign({}, innerParams, validUpdatableParams);
render(this, updatedParams);
privateProps.innerParams.set(this, updatedParams);
Object.defineProperties(this, {
params: {
value: Object.assign({}, this.params, params),
writable: false,
enumerable: true
}
});
}
/**
* @param {SweetAlertOptions} params
* @returns {SweetAlertOptions}
*/
const filterValidParams = params => {
const validUpdatableParams = {};
Object.keys(params).forEach(param => {
if (isUpdatableParameter(param)) {
validUpdatableParams[param] = params[param];
} else {
warn(`Invalid parameter to update: ${param}`);
}
});
return validUpdatableParams;
};
/**
* Dispose the current SweetAlert2 instance
*/
function _destroy() {
const domCache = privateProps.domCache.get(this);
const innerParams = privateProps.innerParams.get(this);
if (!innerParams) {
disposeWeakMaps(this); // The WeakMaps might have been partly destroyed, we must recall it to dispose any remaining WeakMaps #2335
return; // This instance has already been destroyed
}
// Check if there is another Swal closing
if (domCache.popup && globalState.swalCloseEventFinishedCallback) {
globalState.swalCloseEventFinishedCallback();
delete globalState.swalCloseEventFinishedCallback;
}
if (typeof innerParams.didDestroy === 'function') {
innerParams.didDestroy();
}
disposeSwal(this);
}
/**
* @param {SweetAlert2} instance
*/
const disposeSwal = instance => {
disposeWeakMaps(instance);
// Unset this.params so GC will dispose it (#1569)
// @ts-ignore
delete instance.params;
// Unset globalState props so GC will dispose globalState (#1569)
delete globalState.keydownHandler;
delete globalState.keydownTarget;
// Unset currentInstance
delete globalState.currentInstance;
};
/**
* @param {SweetAlert2} instance
*/
const disposeWeakMaps = instance => {
// If the current instance is awaiting a promise result, we keep the privateMethods to call them once the promise result is retrieved #2335
// @ts-ignore
if (instance.isAwaitingPromise()) {
unsetWeakMaps(privateProps, instance);
privateProps.awaitingPromise.set(instance, true);
} else {
unsetWeakMaps(privateMethods, instance);
unsetWeakMaps(privateProps, instance);
}
};
/**
* @param {object} obj
* @param {SweetAlert2} instance
*/
const unsetWeakMaps = (obj, instance) => {
for (const i in obj) {
obj[i].delete(instance);
}
};
var instanceMethods = /*#__PURE__*/Object.freeze({
__proto__: null,
hideLoading: hideLoading,
disableLoading: hideLoading,
getInput: getInput,
close: close,
isAwaitingPromise: isAwaitingPromise,
rejectPromise: rejectPromise,
handleAwaitingPromise: handleAwaitingPromise,
closePopup: close,
closeModal: close,
closeToast: close,
enableButtons: enableButtons,
disableButtons: disableButtons,
enableInput: enableInput,
disableInput: disableInput,
showValidationMessage: showValidationMessage,
resetValidationMessage: resetValidationMessage,
update: update,
_destroy: _destroy
});
/**
* Shows loader (spinner), this is useful with AJAX requests.
* By default the loader be shown instead of the "Confirm" button.
*
* @param {HTMLButtonElement} [buttonToReplace]
*/
const showLoading = buttonToReplace => {
let popup = getPopup();
if (!popup) {
new Swal(); // eslint-disable-line no-new
}
popup = getPopup();
const loader = getLoader();
if (isToast()) {
hide(getIcon());
} else {
replaceButton(popup, buttonToReplace);
}
show(loader);
popup.setAttribute('data-loading', 'true');
popup.setAttribute('aria-busy', 'true');
popup.focus();
};
/**
* @param {HTMLElement} popup
* @param {HTMLButtonElement} [buttonToReplace]
*/
const replaceButton = (popup, buttonToReplace) => {
const actions = getActions();
const loader = getLoader();
if (!buttonToReplace && isVisible$1(getConfirmButton())) {
buttonToReplace = getConfirmButton();
}
show(actions);
if (buttonToReplace) {
hide(buttonToReplace);
loader.setAttribute('data-button-to-replace', buttonToReplace.className);
}
loader.parentNode.insertBefore(loader, buttonToReplace);
addClass([popup, actions], swalClasses.loading);
};
/**
* @typedef { string | number | boolean } InputValue
*/
/**
* @param {SweetAlert2} instance
* @param {SweetAlertOptions} params
*/
const handleInputOptionsAndValue = (instance, params) => {
if (params.input === 'select' || params.input === 'radio') {
handleInputOptions(instance, params);
} else if (['text', 'email', 'number', 'tel', 'textarea'].includes(params.input) && (hasToPromiseFn(params.inputValue) || isPromise(params.inputValue))) {
showLoading(getConfirmButton());
handleInputValue(instance, params);
}
};
/**
* @param {SweetAlert2} instance
* @param {SweetAlertOptions} innerParams
* @returns {string | number | File | FileList | null}
*/
const getInputValue = (instance, innerParams) => {
const input = instance.getInput();
if (!input) {
return null;
}
switch (innerParams.input) {
case 'checkbox':
return getCheckboxValue(input);
case 'radio':
return getRadioValue(input);
case 'file':
return getFileValue(input);
default:
return innerParams.inputAutoTrim ? input.value.trim() : input.value;
}
};
/**
* @param {HTMLInputElement} input
* @returns {number}
*/
const getCheckboxValue = input => input.checked ? 1 : 0;
/**
* @param {HTMLInputElement} input
* @returns {string | null}
*/
const getRadioValue = input => input.checked ? input.value : null;
/**
* @param {HTMLInputElement} input
* @returns {FileList | File | null}
*/
const getFileValue = input => input.files.length ? input.getAttribute('multiple') !== null ? input.files : input.files[0] : null;
/**
* @param {SweetAlert2} instance
* @param {SweetAlertOptions} params
*/
const handleInputOptions = (instance, params) => {
const popup = getPopup();
/**
* @param {Record<string, any>} inputOptions
*/
const processInputOptions = inputOptions => {
populateInputOptions[params.input](popup, formatInputOptions(inputOptions), params);
};
if (hasToPromiseFn(params.inputOptions) || isPromise(params.inputOptions)) {
showLoading(getConfirmButton());
asPromise(params.inputOptions).then(inputOptions => {
instance.hideLoading();
processInputOptions(inputOptions);
});
} else if (typeof params.inputOptions === 'object') {
processInputOptions(params.inputOptions);
} else {
error(`Unexpected type of inputOptions! Expected object, Map or Promise, got ${typeof params.inputOptions}`);
}
};
/**
* @param {SweetAlert2} instance
* @param {SweetAlertOptions} params
*/
const handleInputValue = (instance, params) => {
const input = instance.getInput();
hide(input);
asPromise(params.inputValue).then(inputValue => {
input.value = params.input === 'number' ? `${parseFloat(inputValue) || 0}` : `${inputValue}`;
show(input);
input.focus();
instance.hideLoading();
}).catch(err => {
error(`Error in inputValue promise: ${err}`);
input.value = '';
show(input);
input.focus();
instance.hideLoading();
});
};
const populateInputOptions = {
/**
* @param {HTMLElement} popup
* @param {Record<string, any>} inputOptions
* @param {SweetAlertOptions} params
*/
select: (popup, inputOptions, params) => {
const select = getDirectChildByClass(popup, swalClasses.select);
/**
* @param {HTMLElement} parent
* @param {string} optionLabel
* @param {string} optionValue
*/
const renderOption = (parent, optionLabel, optionValue) => {
const option = document.createElement('option');
option.value = optionValue;
setInnerHtml(option, optionLabel);
option.selected = isSelected(optionValue, params.inputValue);
parent.appendChild(option);
};
inputOptions.forEach(inputOption => {
const optionValue = inputOption[0];
const optionLabel = inputOption[1];
// <optgroup> spec:
// <https://www.w3.org/TR/html401/interact/forms.html#h-17.6>
// "...all OPTGROUP elements must be specified directly within a SELECT element (i.e., groups may not be nested)..."
// check whether this is a <optgroup>
if (Array.isArray(optionLabel)) {
// if it is an array, then it is an <optgroup>
const optgroup = document.createElement('optgroup');
optgroup.label = optionValue;
optgroup.disabled = false; // not configurable for now
select.appendChild(optgroup);
optionLabel.forEach(o => renderOption(optgroup, o[1], o[0]));
} else {
// case of <option>
renderOption(select, optionLabel, optionValue);
}
});
select.focus();
},
/**
* @param {HTMLElement} popup
* @param {Record<string, any>} inputOptions
* @param {SweetAlertOptions} params
*/
radio: (popup, inputOptions, params) => {
const radio = getDirectChildByClass(popup, swalClasses.radio);
inputOptions.forEach(inputOption => {
const radioValue = inputOption[0];
const radioLabel = inputOption[1];
const radioInput = document.createElement('input');
const radioLabelElement = document.createElement('label');
radioInput.type = 'radio';
radioInput.name = swalClasses.radio;
radioInput.value = radioValue;
if (isSelected(radioValue, params.inputValue)) {
radioInput.checked = true;
}
const label = document.createElement('span');
setInnerHtml(label, radioLabel);
label.className = swalClasses.label;
radioLabelElement.appendChild(radioInput);
radioLabelElement.appendChild(label);
radio.appendChild(radioLabelElement);
});
const radios = radio.querySelectorAll('input');
if (radios.length) {
radios[0].focus();
}
}
};
/**
* Converts `inputOptions` into an array of `[value, label]`s
*
* @param {Record<string, any>} inputOptions
* @returns {Array<Array<string>>}
*/
const formatInputOptions = inputOptions => {
const result = [];
if (typeof Map !== 'undefined' && inputOptions instanceof Map) {
inputOptions.forEach((value, key) => {
let valueFormatted = value;
if (typeof valueFormatted === 'object') {
// case of <optgroup>
valueFormatted = formatInputOptions(valueFormatted);
}
result.push([key, valueFormatted]);
});
} else {
Object.keys(inputOptions).forEach(key => {
let valueFormatted = inputOptions[key];
if (typeof valueFormatted === 'object') {
// case of <optgroup>
valueFormatted = formatInputOptions(valueFormatted);
}
result.push([key, valueFormatted]);
});
}
return result;
};
/**
* @param {string} optionValue
* @param {InputValue | Promise<InputValue> | { toPromise: () => InputValue }} inputValue
* @returns {boolean}
*/
const isSelected = (optionValue, inputValue) => {
return inputValue && inputValue.toString() === optionValue.toString();
};
/**
* @param {SweetAlert2} instance
*/
const handleConfirmButtonClick = instance => {
const innerParams = privateProps.innerParams.get(instance);
instance.disableButtons();
if (innerParams.input) {
handleConfirmOrDenyWithInput(instance, 'confirm');
} else {
confirm(instance, true);
}
};
/**
* @param {SweetAlert2} instance
*/
const handleDenyButtonClick = instance => {
const innerParams = privateProps.innerParams.get(instance);
instance.disableButtons();
if (innerParams.returnInputValueOnDeny) {
handleConfirmOrDenyWithInput(instance, 'deny');
} else {
deny(instance, false);
}
};
/**
* @param {SweetAlert2} instance
* @param {Function} dismissWith
*/
const handleCancelButtonClick = (instance, dismissWith) => {
instance.disableButtons();
dismissWith(DismissReason.cancel);
};
/**
* @param {SweetAlert2} instance
* @param {'confirm' | 'deny'} type
*/
const handleConfirmOrDenyWithInput = (instance, type) => {
const innerParams = privateProps.innerParams.get(instance);
if (!innerParams.input) {
error(`The "input" parameter is needed to be set when using returnInputValueOn${capitalizeFirstLetter(type)}`);
return;
}
const inputValue = getInputValue(instance, innerParams);
if (innerParams.inputValidator) {
handleInputValidator(instance, inputValue, type);
} else if (!instance.getInput().checkValidity()) {
instance.enableButtons();
instance.showValidationMessage(innerParams.validationMessage);
} else if (type === 'deny') {
deny(instance, inputValue);
} else {
confirm(instance, inputValue);
}
};
/**
* @param {SweetAlert2} instance
* @param {string | number | File | FileList | null} inputValue
* @param {'confirm' | 'deny'} type
*/
const handleInputValidator = (instance, inputValue, type) => {
const innerParams = privateProps.innerParams.get(instance);
instance.disableInput();
const validationPromise = Promise.resolve().then(() => asPromise(innerParams.inputValidator(inputValue, innerParams.validationMessage)));
validationPromise.then(validationMessage => {
instance.enableButtons();
instance.enableInput();
if (validationMessage) {
instance.showValidationMessage(validationMessage);
} else if (type === 'deny') {
deny(instance, inputValue);
} else {
confirm(instance, inputValue);
}
});
};
/**
* @param {SweetAlert2} instance
* @param {any} value
*/
const deny = (instance, value) => {
const innerParams = privateProps.innerParams.get(instance || undefined);
if (innerParams.showLoaderOnDeny) {
showLoading(getDenyButton());
}
if (innerParams.preDeny) {
privateProps.awaitingPromise.set(instance || undefined, true); // Flagging the instance as awaiting a promise so it's own promise's reject/resolve methods doesn't get destroyed until the result from this preDeny's promise is received
const preDenyPromise = Promise.resolve().then(() => asPromise(innerParams.preDeny(value, innerParams.validationMessage)));
preDenyPromise.then(preDenyValue => {
if (preDenyValue === false) {
instance.hideLoading();
handleAwaitingPromise(instance);
} else {
instance.close({
isDenied: true,
value: typeof preDenyValue === 'undefined' ? value : preDenyValue
});
}
}).catch(error => rejectWith(instance || undefined, error));
} else {
instance.close({
isDenied: true,
value
});
}
};
/**
* @param {SweetAlert2} instance
* @param {any} value
*/
const succeedWith = (instance, value) => {
instance.close({
isConfirmed: true,
value
});
};
/**
*
* @param {SweetAlert2} instance
* @param {string} error
*/
const rejectWith = (instance, error) => {
// @ts-ignore
instance.rejectPromise(error);
};
/**
*
* @param {SweetAlert2} instance
* @param {any} value
*/
const confirm = (instance, value) => {
const innerParams = privateProps.innerParams.get(instance || undefined);
if (innerParams.showLoaderOnConfirm) {
showLoading();
}
if (innerParams.preConfirm) {
instance.resetValidationMessage();
privateProps.awaitingPromise.set(instance || undefined, true); // Flagging the instance as awaiting a promise so it's own promise's reject/resolve methods doesn't get destroyed until the result from this preConfirm's promise is received
const preConfirmPromise = Promise.resolve().then(() => asPromise(innerParams.preConfirm(value, innerParams.validationMessage)));
preConfirmPromise.then(preConfirmValue => {
if (isVisible$1(getValidationMessage()) || preConfirmValue === false) {
instance.hideLoading();
handleAwaitingPromise(instance);
} else {
succeedWith(instance, typeof preConfirmValue === 'undefined' ? value : preConfirmValue);
}
}).catch(error => rejectWith(instance || undefined, error));
} else {
succeedWith(instance, value);
}
};
const handlePopupClick = (instance, domCache, dismissWith) => {
const innerParams = privateProps.innerParams.get(instance);
if (innerParams.toast) {
handleToastClick(instance, domCache, dismissWith);
} else {
// Ignore click events that had mousedown on the popup but mouseup on the container
// This can happen when the user drags a slider
handleModalMousedown(domCache);
// Ignore click events that had mousedown on the container but mouseup on the popup
handleContainerMousedown(domCache);
handleModalClick(instance, domCache, dismissWith);
}
};
const handleToastClick = (instance, domCache, dismissWith) => {
// Closing toast by internal click
domCache.popup.onclick = () => {
const innerParams = privateProps.innerParams.get(instance);
if (innerParams && (isAnyButtonShown(innerParams) || innerParams.timer || innerParams.input)) {
return;
}
dismissWith(DismissReason.close);
};
};
/**
* @param {*} innerParams
* @returns {boolean}
*/
const isAnyButtonShown = innerParams => {
return innerParams.showConfirmButton || innerParams.showDenyButton || innerParams.showCancelButton || innerParams.showCloseButton;
};
let ignoreOutsideClick = false;
const handleModalMousedown = domCache => {
domCache.popup.onmousedown = () => {
domCache.container.onmouseup = function (e) {
domCache.container.onmouseup = undefined;
// We only check if the mouseup target is the container because usually it doesn't
// have any other direct children aside of the popup
if (e.target === domCache.container) {
ignoreOutsideClick = true;
}
};
};
};
const handleContainerMousedown = domCache => {
domCache.container.onmousedown = () => {
domCache.popup.onmouseup = function (e) {
domCache.popup.onmouseup = undefined;
// We also need to check if the mouseup target is a child of the popup
if (e.target === domCache.popup || domCache.popup.contains(e.target)) {
ignoreOutsideClick = true;
}
};
};
};
const handleModalClick = (instance, domCache, dismissWith) => {
domCache.container.onclick = e => {
const innerParams = privateProps.innerParams.get(instance);
if (ignoreOutsideClick) {
ignoreOutsideClick = false;
return;
}
if (e.target === domCache.container && callIfFunction(innerParams.allowOutsideClick)) {
dismissWith(DismissReason.backdrop);
}
};
};
const isJqueryElement = elem => typeof elem === 'object' && elem.jquery;
const isElement = elem => elem instanceof Element || isJqueryElement(elem);
const argsToParams = args => {
const params = {};
if (typeof args[0] === 'object' && !isElement(args[0])) {
Object.assign(params, args[0]);
} else {
['title', 'html', 'icon'].forEach((name, index) => {
const arg = args[index];
if (typeof arg === 'string' || isElement(arg)) {
params[name] = arg;
} else if (arg !== undefined) {
error(`Unexpected type of ${name}! Expected "string" or "Element", got ${typeof arg}`);
}
});
}
return params;
};
function fire() {
const Swal = this; // eslint-disable-line @typescript-eslint/no-this-alias
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return new Swal(...args);
}
/**
* Returns an extended version of `Swal` containing `params` as defaults.
* Useful for reusing Swal configuration.
*
* For example:
*
* Before:
* const textPromptOptions = { input: 'text', showCancelButton: true }
* const {value: firstName} = await Swal.fire({ ...textPromptOptions, title: 'What is your first name?' })
* const {value: lastName} = await Swal.fire({ ...textPromptOptions, title: 'What is your last name?' })
*
* After:
* const TextPrompt = Swal.mixin({ input: 'text', showCancelButton: true })
* const {value: firstName} = await TextPrompt('What is your first name?')
* const {value: lastName} = await TextPrompt('What is your last name?')
*
* @param mixinParams
*/
function mixin(mixinParams) {
class MixinSwal extends this {
_main(params, priorityMixinParams) {
return super._main(params, Object.assign({}, mixinParams, priorityMixinParams));
}
}
return MixinSwal;
}
/**
* If `timer` parameter is set, returns number of milliseconds of timer remained.
* Otherwise, returns undefined.
*
* @returns {number | undefined}
*/
const getTimerLeft = () => {
return globalState.timeout && globalState.timeout.getTimerLeft();
};
/**
* Stop timer. Returns number of milliseconds of timer remained.
* If `timer` parameter isn't set, returns undefined.
*
* @returns {number | undefined}
*/
const stopTimer = () => {
if (globalState.timeout) {
stopTimerProgressBar();
return globalState.timeout.stop();
}
};
/**
* Resume timer. Returns number of milliseconds of timer remained.
* If `timer` parameter isn't set, returns undefined.
*
* @returns {number | undefined}
*/
const resumeTimer = () => {
if (globalState.timeout) {
const remaining = globalState.timeout.start();
animateTimerProgressBar(remaining);
return remaining;
}
};
/**
* Resume timer. Returns number of milliseconds of timer remained.
* If `timer` parameter isn't set, returns undefined.
*
* @returns {number | undefined}
*/
const toggleTimer = () => {
const timer = globalState.timeout;
return timer && (timer.running ? stopTimer() : resumeTimer());
};
/**
* Increase timer. Returns number of milliseconds of an updated timer.
* If `timer` parameter isn't set, returns undefined.
*
* @param {number} n
* @returns {number | undefined}
*/
const increaseTimer = n => {
if (globalState.timeout) {
const remaining = globalState.timeout.increase(n);
animateTimerProgressBar(remaining, true);
return remaining;
}
};
/**
* Check if timer is running. Returns true if timer is running
* or false if timer is paused or stopped.
* If `timer` parameter isn't set, returns undefined
*
* @returns {boolean}
*/
const isTimerRunning = () => {
return globalState.timeout && globalState.timeout.isRunning();
};
let bodyClickListenerAdded = false;
const clickHandlers = {};
/**
* @param {string} attr
*/
function bindClickHandler() {
let attr = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'data-swal-template';
clickHandlers[attr] = this;
if (!bodyClickListenerAdded) {
document.body.addEventListener('click', bodyClickListener);
bodyClickListenerAdded = true;
}
}
const bodyClickListener = event => {
for (let el = event.target; el && el !== document; el = el.parentNode) {
for (const attr in clickHandlers) {
const template = el.getAttribute(attr);
if (template) {
clickHandlers[attr].fire({
template
});
return;
}
}
}
};
var staticMethods = /*#__PURE__*/Object.freeze({
__proto__: null,
isValidParameter: isValidParameter,
isUpdatableParameter: isUpdatableParameter,
isDeprecatedParameter: isDeprecatedParameter,
argsToParams: argsToParams,
getContainer: getContainer,
getPopup: getPopup,
getTitle: getTitle,
getHtmlContainer: getHtmlContainer,
getImage: getImage,
getIcon: getIcon,
getIconContent: getIconContent,
getInputLabel: getInputLabel,
getCloseButton: getCloseButton,
getActions: getActions,
getConfirmButton: getConfirmButton,
getDenyButton: getDenyButton,
getCancelButton: getCancelButton,
getLoader: getLoader,
getFooter: getFooter,
getTimerProgressBar: getTimerProgressBar,
getFocusableElements: getFocusableElements,
getValidationMessage: getValidationMessage,
getProgressSteps: getProgressSteps,
isLoading: isLoading,
isVisible: isVisible,
clickConfirm: clickConfirm,
clickDeny: clickDeny,
clickCancel: clickCancel,
fire: fire,
mixin: mixin,
showLoading: showLoading,
enableLoading: showLoading,
getTimerLeft: getTimerLeft,
stopTimer: stopTimer,
resumeTimer: resumeTimer,
toggleTimer: toggleTimer,
increaseTimer: increaseTimer,
isTimerRunning: isTimerRunning,
bindClickHandler: bindClickHandler
});
class Timer {
/**
* @param {Function} callback
* @param {number} delay
*/
constructor(callback, delay) {
this.callback = callback;
this.remaining = delay;
this.running = false;
this.start();
}
start() {
if (!this.running) {
this.running = true;
this.started = new Date();
this.id = setTimeout(this.callback, this.remaining);
}
return this.remaining;
}
stop() {
if (this.running) {
this.running = false;
clearTimeout(this.id);
this.remaining -= new Date().getTime() - this.started.getTime();
}
return this.remaining;
}
increase(n) {
const running = this.running;
if (running) {
this.stop();
}
this.remaining += n;
if (running) {
this.start();
}
return this.remaining;
}
getTimerLeft() {
if (this.running) {
this.stop();
this.start();
}
return this.remaining;
}
isRunning() {
return this.running;
}
}
const swalStringParams = ['swal-title', 'swal-html', 'swal-footer'];
/**
* @param {SweetAlertOptions} params
* @returns {SweetAlertOptions}
*/
const getTemplateParams = params => {
/** @type {HTMLTemplateElement} */
const template = typeof params.template === 'string' ? document.querySelector(params.template) : params.template;
if (!template) {
return {};
}
/** @type {DocumentFragment} */
const templateContent = template.content;
showWarningsForElements(templateContent);
const result = Object.assign(getSwalParams(templateContent), getSwalFunctionParams(templateContent), getSwalButtons(templateContent), getSwalImage(templateContent), getSwalIcon(templateContent), getSwalInput(templateContent), getSwalStringParams(templateContent, swalStringParams));
return result;
};
/**
* @param {DocumentFragment} templateContent
* @returns {SweetAlertOptions}
*/
const getSwalParams = templateContent => {
const result = {};
/** @type {HTMLElement[]} */
const swalParams = Array.from(templateContent.querySelectorAll('swal-param'));
swalParams.forEach(param => {
showWarningsForAttributes(param, ['name', 'value']);
const paramName = param.getAttribute('name');
const value = param.getAttribute('value');
if (typeof defaultParams[paramName] === 'boolean') {
result[paramName] = value !== 'false';
} else if (typeof defaultParams[paramName] === 'object') {
result[paramName] = JSON.parse(value);
} else {
result[paramName] = value;
}
});
return result;
};
/**
* @param {DocumentFragment} templateContent
* @returns {SweetAlertOptions}
*/
const getSwalFunctionParams = templateContent => {
const result = {};
/** @type {HTMLElement[]} */
const swalFunctions = Array.from(templateContent.querySelectorAll('swal-function-param'));
swalFunctions.forEach(param => {
const paramName = param.getAttribute('name');
const value = param.getAttribute('value');
result[paramName] = new Function(`return ${value}`)();
});
return result;
};
/**
* @param {DocumentFragment} templateContent
* @returns {SweetAlertOptions}
*/
const getSwalButtons = templateContent => {
const result = {};
/** @type {HTMLElement[]} */
const swalButtons = Array.from(templateContent.querySelectorAll('swal-button'));
swalButtons.forEach(button => {
showWarningsForAttributes(button, ['type', 'color', 'aria-label']);
const type = button.getAttribute('type');
result[`${type}ButtonText`] = button.innerHTML;
result[`show${capitalizeFirstLetter(type)}Button`] = true;
if (button.hasAttribute('color')) {
result[`${type}ButtonColor`] = button.getAttribute('color');
}
if (button.hasAttribute('aria-label')) {
result[`${type}ButtonAriaLabel`] = button.getAttribute('aria-label');
}
});
return result;
};
/**
* @param {DocumentFragment} templateContent
* @returns {SweetAlertOptions}
*/
const getSwalImage = templateContent => {
const result = {};
/** @type {HTMLElement} */
const image = templateContent.querySelector('swal-image');
if (image) {
showWarningsForAttributes(image, ['src', 'width', 'height', 'alt']);
if (image.hasAttribute('src')) {
result.imageUrl = image.getAttribute('src');
}
if (image.hasAttribute('width')) {
result.imageWidth = image.getAttribute('width');
}
if (image.hasAttribute('height')) {
result.imageHeight = image.getAttribute('height');
}
if (image.hasAttribute('alt')) {
result.imageAlt = image.getAttribute('alt');
}
}
return result;
};
/**
* @param {DocumentFragment} templateContent
* @returns {SweetAlertOptions}
*/
const getSwalIcon = templateContent => {
const result = {};
/** @type {HTMLElement} */
const icon = templateContent.querySelector('swal-icon');
if (icon) {
showWarningsForAttributes(icon, ['type', 'color']);
if (icon.hasAttribute('type')) {
/** @type {SweetAlertIcon} */
// @ts-ignore
result.icon = icon.getAttribute('type');
}
if (icon.hasAttribute('color')) {
result.iconColor = icon.getAttribute('color');
}
result.iconHtml = icon.innerHTML;
}
return result;
};
/**
* @param {DocumentFragment} templateContent
* @returns {SweetAlertOptions}
*/
const getSwalInput = templateContent => {
const result = {};
/** @type {HTMLElement} */
const input = templateContent.querySelector('swal-input');
if (input) {
showWarningsForAttributes(input, ['type', 'label', 'placeholder', 'value']);
/** @type {SweetAlertInput} */
// @ts-ignore
result.input = input.getAttribute('type') || 'text';
if (input.hasAttribute('label')) {
result.inputLabel = input.getAttribute('label');
}
if (input.hasAttribute('placeholder')) {
result.inputPlaceholder = input.getAttribute('placeholder');
}
if (input.hasAttribute('value')) {
result.inputValue = input.getAttribute('value');
}
}
/** @type {HTMLElement[]} */
const inputOptions = Array.from(templateContent.querySelectorAll('swal-input-option'));
if (inputOptions.length) {
result.inputOptions = {};
inputOptions.forEach(option => {
showWarningsForAttributes(option, ['value']);
const optionValue = option.getAttribute('value');
const optionName = option.innerHTML;
result.inputOptions[optionValue] = optionName;
});
}
return result;
};
/**
* @param {DocumentFragment} templateContent
* @param {string[]} paramNames
* @returns {SweetAlertOptions}
*/
const getSwalStringParams = (templateContent, paramNames) => {
const result = {};
for (const i in paramNames) {
const paramName = paramNames[i];
/** @type {HTMLElement} */
const tag = templateContent.querySelector(paramName);
if (tag) {
showWarningsForAttributes(tag, []);
result[paramName.replace(/^swal-/, '')] = tag.innerHTML.trim();
}
}
return result;
};
/**
* @param {DocumentFragment} templateContent
*/
const showWarningsForElements = templateContent => {
const allowedElements = swalStringParams.concat(['swal-param', 'swal-function-param', 'swal-button', 'swal-image', 'swal-icon', 'swal-input', 'swal-input-option']);
Array.from(templateContent.children).forEach(el => {
const tagName = el.tagName.toLowerCase();
if (!allowedElements.includes(tagName)) {
warn(`Unrecognized element <${tagName}>`);
}
});
};
/**
* @param {HTMLElement} el
* @param {string[]} allowedAttributes
*/
const showWarningsForAttributes = (el, allowedAttributes) => {
Array.from(el.attributes).forEach(attribute => {
if (allowedAttributes.indexOf(attribute.name) === -1) {
warn([`Unrecognized attribute "${attribute.name}" on <${el.tagName.toLowerCase()}>.`, `${allowedAttributes.length ? `Allowed attributes are: ${allowedAttributes.join(', ')}` : 'To set the value, use HTML within the element.'}`]);
}
});
};
const SHOW_CLASS_TIMEOUT = 10;
/**
* Open popup, add necessary classes and styles, fix scrollbar
*
* @param {SweetAlertOptions} params
*/
const openPopup = params => {
const container = getContainer();
const popup = getPopup();
if (typeof params.willOpen === 'function') {
params.willOpen(popup);
}
const bodyStyles = window.getComputedStyle(document.body);
const initialBodyOverflow = bodyStyles.overflowY;
addClasses(container, popup, params);
// scrolling is 'hidden' until animation is done, after that 'auto'
setTimeout(() => {
setScrollingVisibility(container, popup);
}, SHOW_CLASS_TIMEOUT);
if (isModal()) {
fixScrollContainer(container, params.scrollbarPadding, initialBodyOverflow);
setAriaHidden();
}
if (!isToast() && !globalState.previousActiveElement) {
globalState.previousActiveElement = document.activeElement;
}
if (typeof params.didOpen === 'function') {
setTimeout(() => params.didOpen(popup));
}
removeClass(container, swalClasses['no-transition']);
};
/**
* @param {AnimationEvent} event
*/
const swalOpenAnimationFinished = event => {
const popup = getPopup();
if (event.target !== popup) {
return;
}
const container = getContainer();
popup.removeEventListener(animationEndEvent, swalOpenAnimationFinished);
container.style.overflowY = 'auto';
};
/**
* @param {HTMLElement} container
* @param {HTMLElement} popup
*/
const setScrollingVisibility = (container, popup) => {
if (animationEndEvent && hasCssAnimation(popup)) {
container.style.overflowY = 'hidden';
popup.addEventListener(animationEndEvent, swalOpenAnimationFinished);
} else {
container.style.overflowY = 'auto';
}
};
/**
* @param {HTMLElement} container
* @param {boolean} scrollbarPadding
* @param {string} initialBodyOverflow
*/
const fixScrollContainer = (container, scrollbarPadding, initialBodyOverflow) => {
iOSfix();
if (scrollbarPadding && initialBodyOverflow !== 'hidden') {
fixScrollbar();
}
// sweetalert2/issues/1247
setTimeout(() => {
container.scrollTop = 0;
});
};
/**
* @param {HTMLElement} container
* @param {HTMLElement} popup
* @param {SweetAlertOptions} params
*/
const addClasses = (container, popup, params) => {
addClass(container, params.showClass.backdrop);
// this workaround with opacity is needed for <https://github.com/sweetalert2/sweetalert2/issues/2059>
popup.style.setProperty('opacity', '0', 'important');
show(popup, 'grid');
setTimeout(() => {
// Animate popup right after showing it
addClass(popup, params.showClass.popup);
// and remove the opacity workaround
popup.style.removeProperty('opacity');
}, SHOW_CLASS_TIMEOUT); // 10ms in order to fix #2062
addClass([document.documentElement, document.body], swalClasses.shown);
if (params.heightAuto && params.backdrop && !params.toast) {
addClass([document.documentElement, document.body], swalClasses['height-auto']);
}
};
var defaultInputValidators = {
/**
* @param {string} string
* @param {string} validationMessage
* @returns {Promise<void | string>}
*/
email: (string, validationMessage) => {
return /^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z0-9-]{2,24}$/.test(string) ? Promise.resolve() : Promise.resolve(validationMessage || 'Invalid email address');
},
/**
* @param {string} string
* @param {string} validationMessage
* @returns {Promise<void | string>}
*/
url: (string, validationMessage) => {
// taken from <https://stackoverflow.com/a/3809435> with a small change from #1306 and #2013
return /^https?:\\/\\/(www\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\.[a-z]{2,63}\\b([-a-zA-Z0-9@:%_+.~#?&/=]*)$/.test(string) ? Promise.resolve() : Promise.resolve(validationMessage || 'Invalid URL');
}
};
/**
* @param {SweetAlertOptions} params
*/
function setDefaultInputValidators(params) {
// Use default `inputValidator` for supported input types if not provided
if (!params.inputValidator) {
Object.keys(defaultInputValidators).forEach(key => {
if (params.input === key) {
params.inputValidator = defaultInputValidators[key];
}
});
}
}
/**
* @param {SweetAlertOptions} params
*/
function validateCustomTargetElement(params) {
// Determine if the custom target element is valid
if (!params.target || typeof params.target === 'string' && !document.querySelector(params.target) || typeof params.target !== 'string' && !params.target.appendChild) {
warn('Target parameter is not valid, defaulting to "body"');
params.target = 'body';
}
}
/**
* Set type, text and actions on popup
*
* @param {SweetAlertOptions} params
*/
function setParameters(params) {
setDefaultInputValidators(params);
// showLoaderOnConfirm && preConfirm
if (params.showLoaderOnConfirm && !params.preConfirm) {
warn('showLoaderOnConfirm is set to true, but preConfirm is not defined.\\n' + 'showLoaderOnConfirm should be used together with preConfirm, see usage example:\\n' + '<https://sweetalert2.github.io/#ajax-request>');
}
validateCustomTargetElement(params);
// Replace newlines with <br> in title
if (typeof params.title === 'string') {
params.title = params.title.split('\\n').join('<br />');
}
init(params);
}
let currentInstance;
class SweetAlert {
constructor() {
// Prevent run in Node env
if (typeof window === 'undefined') {
return;
}
currentInstance = this;
// @ts-ignore
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
const outerParams = Object.freeze(this.constructor.argsToParams(args));
Object.defineProperties(this, {
params: {
value: outerParams,
writable: false,
enumerable: true,
configurable: true
}
});
// @ts-ignore
const promise = currentInstance._main(currentInstance.params);
privateProps.promise.set(this, promise);
}
_main(userParams) {
let mixinParams = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
showWarningsForParams(Object.assign({}, mixinParams, userParams));
if (globalState.currentInstance) {
// @ts-ignore
globalState.currentInstance._destroy();
if (isModal()) {
unsetAriaHidden();
}
}
globalState.currentInstance = currentInstance;
const innerParams = prepareParams(userParams, mixinParams);
setParameters(innerParams);
Object.freeze(innerParams);
// clear the previous timer
if (globalState.timeout) {
globalState.timeout.stop();
delete globalState.timeout;
}
// clear the restore focus timeout
clearTimeout(globalState.restoreFocusTimeout);
const domCache = populateDomCache(currentInstance);
render(currentInstance, innerParams);
privateProps.innerParams.set(currentInstance, innerParams);
return swalPromise(currentInstance, domCache, innerParams);
}
// `catch` cannot be the name of a module export, so we define our thenable methods here instead
then(onFulfilled) {
const promise = privateProps.promise.get(this);
return promise.then(onFulfilled);
}
finally(onFinally) {
const promise = privateProps.promise.get(this);
return promise.finally(onFinally);
}
}
/**
* @param {SweetAlert2} instance
* @param {DomCache} domCache
* @param {SweetAlertOptions} innerParams
* @returns {Promise}
*/
const swalPromise = (instance, domCache, innerParams) => {
return new Promise((resolve, reject) => {
// functions to handle all closings/dismissals
/**
* @param {DismissReason} dismiss
*/
const dismissWith = dismiss => {
// @ts-ignore
instance.close({
isDismissed: true,
dismiss
});
};
privateMethods.swalPromiseResolve.set(instance, resolve);
privateMethods.swalPromiseReject.set(instance, reject);
domCache.confirmButton.onclick = () => {
handleConfirmButtonClick(instance);
};
domCache.denyButton.onclick = () => {
handleDenyButtonClick(instance);
};
domCache.cancelButton.onclick = () => {
handleCancelButtonClick(instance, dismissWith);
};
domCache.closeButton.onclick = () => {
// @ts-ignore
dismissWith(DismissReason.close);
};
handlePopupClick(instance, domCache, dismissWith);
addKeydownHandler(instance, globalState, innerParams, dismissWith);
handleInputOptionsAndValue(instance, innerParams);
openPopup(innerParams);
setupTimer(globalState, innerParams, dismissWith);
initFocus(domCache, innerParams);
// Scroll container to top on open (#1247, #1946)
setTimeout(() => {
domCache.container.scrollTop = 0;
});
});
};
/**
* @param {SweetAlertOptions} userParams
* @param {SweetAlertOptions} mixinParams
* @returns {SweetAlertOptions}
*/
const prepareParams = (userParams, mixinParams) => {
const templateParams = getTemplateParams(userParams);
const params = Object.assign({}, defaultParams, mixinParams, templateParams, userParams); // precedence is described in #2131
params.showClass = Object.assign({}, defaultParams.showClass, params.showClass);
params.hideClass = Object.assign({}, defaultParams.hideClass, params.hideClass);
return params;
};
/**
* @param {SweetAlert2} instance
* @returns {DomCache}
*/
const populateDomCache = instance => {
const domCache = {
popup: getPopup(),
container: getContainer(),
actions: getActions(),
confirmButton: getConfirmButton(),
denyButton: getDenyButton(),
cancelButton: getCancelButton(),
loader: getLoader(),
closeButton: getCloseButton(),
validationMessage: getValidationMessage(),
progressSteps: getProgressSteps()
};
privateProps.domCache.set(instance, domCache);
return domCache;
};
/**
* @param {GlobalState} globalState
* @param {SweetAlertOptions} innerParams
* @param {Function} dismissWith
*/
const setupTimer = (globalState, innerParams, dismissWith) => {
const timerProgressBar = getTimerProgressBar();
hide(timerProgressBar);
if (innerParams.timer) {
globalState.timeout = new Timer(() => {
dismissWith('timer');
delete globalState.timeout;
}, innerParams.timer);
if (innerParams.timerProgressBar) {
show(timerProgressBar);
applyCustomClass(timerProgressBar, innerParams, 'timerProgressBar');
setTimeout(() => {
if (globalState.timeout && globalState.timeout.running) {
// timer can be already stopped or unset at this point
animateTimerProgressBar(innerParams.timer);
}
});
}
}
};
/**
* @param {DomCache} domCache
* @param {SweetAlertOptions} innerParams
*/
const initFocus = (domCache, innerParams) => {
if (innerParams.toast) {
return;
}
if (!callIfFunction(innerParams.allowEnterKey)) {
blurActiveElement();
return;
}
if (!focusButton(domCache, innerParams)) {
setFocus(-1, 1);
}
};
/**
* @param {DomCache} domCache
* @param {SweetAlertOptions} innerParams
* @returns {boolean}
*/
const focusButton = (domCache, innerParams) => {
if (innerParams.focusDeny && isVisible$1(domCache.denyButton)) {
domCache.denyButton.focus();
return true;
}
if (innerParams.focusCancel && isVisible$1(domCache.cancelButton)) {
domCache.cancelButton.focus();
return true;
}
if (innerParams.focusConfirm && isVisible$1(domCache.confirmButton)) {
domCache.confirmButton.focus();
return true;
}
return false;
};
const blurActiveElement = () => {
if (document.activeElement instanceof HTMLElement && typeof document.activeElement.blur === 'function') {
document.activeElement.blur();
}
};
// Assign instance methods from src/instanceMethods/*.js to prototype
Object.assign(SweetAlert.prototype, instanceMethods);
// Assign static methods from src/staticMethods/*.js to constructor
Object.assign(SweetAlert, staticMethods);
// Proxy to instance methods to constructor, for now, for backwards compatibility
Object.keys(instanceMethods).forEach(key => {
/**
* @param {...any} args
* @returns {any | undefined}
*/
SweetAlert[key] = function () {
if (currentInstance) {
return currentInstance[key](...arguments);
}
};
});
SweetAlert.DismissReason = DismissReason;
SweetAlert.version = '11.7.1';
const Swal = SweetAlert;
// @ts-ignore
Swal.default = Swal;
return Swal;
}));
if (typeof this !== 'undefined' && this.Sweetalert2){this.swal = this.sweetAlert = this.Swal = this.SweetAlert = this.Sweetalert2}
"undefined"!=typeof document&&function(e,t){var n=e.createElement("style");if(e.getElementsByTagName("head")[0].appendChild(n),n.styleSheet)n.styleSheet.disabled||(n.styleSheet.cssText=t);else try{n.innerHTML=t}catch(e){n.innerText=t}}(document,".swal2-popup.swal2-toast{box-sizing:border-box;grid-column:1/4 !important;grid-row:1/4 !important;grid-template-columns:min-content auto min-content;padding:1em;overflow-y:hidden;background:#fff;box-shadow:0 0 1px rgba(0,0,0,.075),0 1px 2px rgba(0,0,0,.075),1px 2px 4px rgba(0,0,0,.075),1px 3px 8px rgba(0,0,0,.075),2px 4px 16px rgba(0,0,0,.075);pointer-events:all}.swal2-popup.swal2-toast>*{grid-column:2}.swal2-popup.swal2-toast .swal2-title{margin:.5em 1em;padding:0;font-size:1em;text-align:initial}.swal2-popup.swal2-toast .swal2-loading{justify-content:center}.swal2-popup.swal2-toast .swal2-input{height:2em;margin:.5em;font-size:1em}.swal2-popup.swal2-toast .swal2-validation-message{font-size:1em}.swal2-popup.swal2-toast .swal2-footer{margin:.5em 0 0;padding:.5em 0 0;font-size:.8em}.swal2-popup.swal2-toast .swal2-close{grid-column:3/3;grid-row:1/99;align-self:center;width:.8em;height:.8em;margin:0;font-size:2em}.swal2-popup.swal2-toast .swal2-html-container{margin:.5em 1em;padding:0;overflow:initial;font-size:1em;text-align:initial}.swal2-popup.swal2-toast .swal2-html-container:empty{padding:0}.swal2-popup.swal2-toast .swal2-loader{grid-column:1;grid-row:1/99;align-self:center;width:2em;height:2em;margin:.25em}.swal2-popup.swal2-toast .swal2-icon{grid-column:1;grid-row:1/99;align-self:center;width:2em;min-width:2em;height:2em;margin:0 .5em 0 0}.swal2-popup.swal2-toast .swal2-icon .swal2-icon-content{display:flex;align-items:center;font-size:1.8em;font-weight:bold}.swal2-popup.swal2-toast .swal2-icon.swal2-success .swal2-success-ring{width:2em;height:2em}.swal2-popup.swal2-toast .swal2-icon.swal2-error [class^=swal2-x-mark-line]{top:.875em;width:1.375em}.swal2-popup.swal2-toast .swal2-icon.swal2-error [class^=swal2-x-mark-line][class$=left]{left:.3125em}.swal2-popup.swal2-toast .swal2-icon.swal2-error [class^=swal2-x-mark-line][class$=right]{right:.3125em}.swal2-popup.swal2-toast .swal2-actions{justify-content:flex-start;height:auto;margin:0;margin-top:.5em;padding:0 .5em}.swal2-popup.swal2-toast .swal2-styled{margin:.25em .5em;padding:.4em .6em;font-size:1em}.swal2-popup.swal2-toast .swal2-success{border-color:#a5dc86}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-circular-line]{position:absolute;width:1.6em;height:3em;transform:rotate(45deg);border-radius:50%}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-circular-line][class$=left]{top:-0.8em;left:-0.5em;transform:rotate(-45deg);transform-origin:2em 2em;border-radius:4em 0 0 4em}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-circular-line][class$=right]{top:-0.25em;left:.9375em;transform-origin:0 1.5em;border-radius:0 4em 4em 0}.swal2-popup.swal2-toast .swal2-success .swal2-success-ring{width:2em;height:2em}.swal2-popup.swal2-toast .swal2-success .swal2-success-fix{top:0;left:.4375em;width:.4375em;height:2.6875em}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-line]{height:.3125em}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-line][class$=tip]{top:1.125em;left:.1875em;width:.75em}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-line][class$=long]{top:.9375em;right:.1875em;width:1.375em}.swal2-popup.swal2-toast .swal2-success.swal2-icon-show .swal2-success-line-tip{animation:swal2-toast-animate-success-line-tip .75s}.swal2-popup.swal2-toast .swal2-success.swal2-icon-show .swal2-success-line-long{animation:swal2-toast-animate-success-line-long .75s}.swal2-popup.swal2-toast.swal2-show{animation:swal2-toast-show .5s}.swal2-popup.swal2-toast.swal2-hide{animation:swal2-toast-hide .1s forwards}.swal2-container{display:grid;position:fixed;z-index:1060;top:0;right:0;bottom:0;left:0;box-sizing:border-box;grid-template-areas:\\"top-start top top-end\\" \\"center-start center center-end\\" \\"bottom-start bottom-center bottom-end\\";grid-template-rows:minmax(min-content, auto) minmax(min-content, auto) minmax(min-content, auto);height:100%;padding:.625em;overflow-x:hidden;transition:background-color .1s;-webkit-overflow-scrolling:touch}.swal2-container.swal2-backdrop-show,.swal2-container.swal2-noanimation{background:rgba(0,0,0,.4)}.swal2-container.swal2-backdrop-hide{background:rgba(0,0,0,0) !important}.swal2-container.swal2-top-start,.swal2-container.swal2-center-start,.swal2-container.swal2-bottom-start{grid-template-columns:minmax(0, 1fr) auto auto}.swal2-container.swal2-top,.swal2-container.swal2-center,.swal2-container.swal2-bottom{grid-template-columns:auto minmax(0, 1fr) auto}.swal2-container.swal2-top-end,.swal2-container.swal2-center-end,.swal2-container.swal2-bottom-end{grid-template-columns:auto auto minmax(0, 1fr)}.swal2-container.swal2-top-start>.swal2-popup{align-self:start}.swal2-container.swal2-top>.swal2-popup{grid-column:2;align-self:start;justify-self:center}.swal2-container.swal2-top-end>.swal2-popup,.swal2-container.swal2-top-right>.swal2-popup{grid-column:3;align-self:start;justify-self:end}.swal2-container.swal2-center-start>.swal2-popup,.swal2-container.swal2-center-left>.swal2-popup{grid-row:2;align-self:center}.swal2-container.swal2-center>.swal2-popup{grid-column:2;grid-row:2;align-self:center;justify-self:center}.swal2-container.swal2-center-end>.swal2-popup,.swal2-container.swal2-center-right>.swal2-popup{grid-column:3;grid-row:2;align-self:center;justify-self:end}.swal2-container.swal2-bottom-start>.swal2-popup,.swal2-container.swal2-bottom-left>.swal2-popup{grid-column:1;grid-row:3;align-self:end}.swal2-container.swal2-bottom>.swal2-popup{grid-column:2;grid-row:3;justify-self:center;align-self:end}.swal2-container.swal2-bottom-end>.swal2-popup,.swal2-container.swal2-bottom-right>.swal2-popup{grid-column:3;grid-row:3;align-self:end;justify-self:end}.swal2-container.swal2-grow-row>.swal2-popup,.swal2-container.swal2-grow-fullscreen>.swal2-popup{grid-column:1/4;width:100%}.swal2-container.swal2-grow-column>.swal2-popup,.swal2-container.swal2-grow-fullscreen>.swal2-popup{grid-row:1/4;align-self:stretch}.swal2-container.swal2-no-transition{transition:none !important}.swal2-popup{display:none;position:relative;box-sizing:border-box;grid-template-columns:minmax(0, 100%);width:32em;max-width:100%;padding:0 0 1.25em;border:none;border-radius:5px;background:#fff;color:#545454;font-family:inherit;font-size:1rem}.swal2-popup:focus{outline:none}.swal2-popup.swal2-loading{overflow-y:hidden}.swal2-title{position:relative;max-width:100%;margin:0;padding:.8em 1em 0;color:inherit;font-size:1.875em;font-weight:600;text-align:center;text-transform:none;word-wrap:break-word}.swal2-actions{display:flex;z-index:1;box-sizing:border-box;flex-wrap:wrap;align-items:center;justify-content:center;width:auto;margin:1.25em auto 0;padding:0}.swal2-actions:not(.swal2-loading) .swal2-styled[disabled]{opacity:.4}.swal2-actions:not(.swal2-loading) .swal2-styled:hover{background-image:linear-gradient(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.1))}.swal2-actions:not(.swal2-loading) .swal2-styled:active{background-image:linear-gradient(rgba(0, 0, 0, 0.2), rgba(0, 0, 0, 0.2))}.swal2-loader{display:none;align-items:center;justify-content:center;width:2.2em;height:2.2em;margin:0 1.875em;animation:swal2-rotate-loading 1.5s linear 0s infinite normal;border-width:.25em;border-style:solid;border-radius:100%;border-color:#2778c4 rgba(0,0,0,0) #2778c4 rgba(0,0,0,0)}.swal2-styled{margin:.3125em;padding:.625em 1.1em;transition:box-shadow .1s;box-shadow:0 0 0 3px rgba(0,0,0,0);font-weight:500}.swal2-styled:not([disabled]){cursor:pointer}.swal2-styled.swal2-confirm{border:0;border-radius:.25em;background:initial;background-color:#7066e0;color:#fff;font-size:1em}.swal2-styled.swal2-confirm:focus{box-shadow:0 0 0 3px rgba(112,102,224,.5)}.swal2-styled.swal2-deny{border:0;border-radius:.25em;background:initial;background-color:#dc3741;color:#fff;font-size:1em}.swal2-styled.swal2-deny:focus{box-shadow:0 0 0 3px rgba(220,55,65,.5)}.swal2-styled.swal2-cancel{border:0;border-radius:.25em;background:initial;background-color:#6e7881;color:#fff;font-size:1em}.swal2-styled.swal2-cancel:focus{box-shadow:0 0 0 3px rgba(110,120,129,.5)}.swal2-styled.swal2-default-outline:focus{box-shadow:0 0 0 3px rgba(100,150,200,.5)}.swal2-styled:focus{outline:none}.swal2-styled::-moz-focus-inner{border:0}.swal2-footer{justify-content:center;margin:1em 0 0;padding:1em 1em 0;border-top:1px solid #eee;color:inherit;font-size:1em}.swal2-timer-progress-bar-container{position:absolute;right:0;bottom:0;left:0;grid-column:auto !important;overflow:hidden;border-bottom-right-radius:5px;border-bottom-left-radius:5px}.swal2-timer-progress-bar{width:100%;height:.25em;background:rgba(0,0,0,.2)}.swal2-image{max-width:100%;margin:2em auto 1em}.swal2-close{z-index:2;align-items:center;justify-content:center;width:1.2em;height:1.2em;margin-top:0;margin-right:0;margin-bottom:-1.2em;padding:0;overflow:hidden;transition:color .1s,box-shadow .1s;border:none;border-radius:5px;background:rgba(0,0,0,0);color:#ccc;font-family:serif;font-family:monospace;font-size:2.5em;cursor:pointer;justify-self:end}.swal2-close:hover{transform:none;background:rgba(0,0,0,0);color:#f27474}.swal2-close:focus{outline:none;box-shadow:inset 0 0 0 3px rgba(100,150,200,.5)}.swal2-close::-moz-focus-inner{border:0}.swal2-html-container{z-index:1;justify-content:center;margin:1em 1.6em .3em;padding:0;overflow:auto;color:inherit;font-size:1.125em;font-weight:normal;line-height:normal;text-align:center;word-wrap:break-word;word-break:break-word}.swal2-input,.swal2-file,.swal2-textarea,.swal2-select,.swal2-radio,.swal2-checkbox{margin:1em 2em 3px}.swal2-input,.swal2-file,.swal2-textarea{box-sizing:border-box;width:auto;transition:border-color .1s,box-shadow .1s;border:1px solid #d9d9d9;border-radius:.1875em;background:rgba(0,0,0,0);box-shadow:inset 0 1px 1px rgba(0,0,0,.06),0 0 0 3px rgba(0,0,0,0);color:inherit;font-size:1.125em}.swal2-input.swal2-inputerror,.swal2-file.swal2-inputerror,.swal2-textarea.swal2-inputerror{border-color:#f27474 !important;box-shadow:0 0 2px #f27474 !important}.swal2-input:focus,.swal2-file:focus,.swal2-textarea:focus{border:1px solid #b4dbed;outline:none;box-shadow:inset 0 1px 1px rgba(0,0,0,.06),0 0 0 3px rgba(100,150,200,.5)}.swal2-input::placeholder,.swal2-file::placeholder,.swal2-textarea::placeholder{color:#ccc}.swal2-range{margin:1em 2em 3px;background:#fff}.swal2-range input{width:80%}.swal2-range output{width:20%;color:inherit;font-weight:600;text-align:center}.swal2-range input,.swal2-range output{height:2.625em;padding:0;font-size:1.125em;line-height:2.625em}.swal2-input{height:2.625em;padding:0 .75em}.swal2-file{width:75%;margin-right:auto;margin-left:auto;background:rgba(0,0,0,0);font-size:1.125em}.swal2-textarea{height:6.75em;padding:.75em}.swal2-select{min-width:50%;max-width:100%;padding:.375em .625em;background:rgba(0,0,0,0);color:inherit;font-size:1.125em}.swal2-radio,.swal2-checkbox{align-items:center;justify-content:center;background:#fff;color:inherit}.swal2-radio label,.swal2-checkbox label{margin:0 .6em;font-size:1.125em}.swal2-radio input,.swal2-checkbox input{flex-shrink:0;margin:0 .4em}.swal2-input-label{display:flex;justify-content:center;margin:1em auto 0}.swal2-validation-message{align-items:center;justify-content:center;margin:1em 0 0;padding:.625em;overflow:hidden;background:#f0f0f0;color:#666;font-size:1em;font-weight:300}.swal2-validation-message::before{content:\\"!\\";display:inline-block;width:1.5em;min-width:1.5em;height:1.5em;margin:0 .625em;border-radius:50%;background-color:#f27474;color:#fff;font-weight:600;line-height:1.5em;text-align:center}.swal2-icon{position:relative;box-sizing:content-box;justify-content:center;width:5em;height:5em;margin:2.5em auto .6em;border:0.25em solid rgba(0,0,0,0);border-radius:50%;border-color:#000;font-family:inherit;line-height:5em;cursor:default;user-select:none}.swal2-icon .swal2-icon-content{display:flex;align-items:center;font-size:3.75em}.swal2-icon.swal2-error{border-color:#f27474;color:#f27474}.swal2-icon.swal2-error .swal2-x-mark{position:relative;flex-grow:1}.swal2-icon.swal2-error [class^=swal2-x-mark-line]{display:block;position:absolute;top:2.3125em;width:2.9375em;height:.3125em;border-radius:.125em;background-color:#f27474}.swal2-icon.swal2-error [class^=swal2-x-mark-line][class$=left]{left:1.0625em;transform:rotate(45deg)}.swal2-icon.swal2-error [class^=swal2-x-mark-line][class$=right]{right:1em;transform:rotate(-45deg)}.swal2-icon.swal2-error.swal2-icon-show{animation:swal2-animate-error-icon .5s}.swal2-icon.swal2-error.swal2-icon-show .swal2-x-mark{animation:swal2-animate-error-x-mark .5s}.swal2-icon.swal2-warning{border-color:#facea8;color:#f8bb86}.swal2-icon.swal2-warning.swal2-icon-show{animation:swal2-animate-error-icon .5s}.swal2-icon.swal2-warning.swal2-icon-show .swal2-icon-content{animation:swal2-animate-i-mark .5s}.swal2-icon.swal2-info{border-color:#9de0f6;color:#3fc3ee}.swal2-icon.swal2-info.swal2-icon-show{animation:swal2-animate-error-icon .5s}.swal2-icon.swal2-info.swal2-icon-show .swal2-icon-content{animation:swal2-animate-i-mark .8s}.swal2-icon.swal2-question{border-color:#c9dae1;color:#87adbd}.swal2-icon.swal2-question.swal2-icon-show{animation:swal2-animate-error-icon .5s}.swal2-icon.swal2-question.swal2-icon-show .swal2-icon-content{animation:swal2-animate-question-mark .8s}.swal2-icon.swal2-success{border-color:#a5dc86;color:#a5dc86}.swal2-icon.swal2-success [class^=swal2-success-circular-line]{position:absolute;width:3.75em;height:7.5em;transform:rotate(45deg);border-radius:50%}.swal2-icon.swal2-success [class^=swal2-success-circular-line][class$=left]{top:-0.4375em;left:-2.0635em;transform:rotate(-45deg);transform-origin:3.75em 3.75em;border-radius:7.5em 0 0 7.5em}.swal2-icon.swal2-success [class^=swal2-success-circular-line][class$=right]{top:-0.6875em;left:1.875em;transform:rotate(-45deg);transform-origin:0 3.75em;border-radius:0 7.5em 7.5em 0}.swal2-icon.swal2-success .swal2-success-ring{position:absolute;z-index:2;top:-0.25em;left:-0.25em;box-sizing:content-box;width:100%;height:100%;border:.25em solid rgba(165,220,134,.3);border-radius:50%}.swal2-icon.swal2-success .swal2-success-fix{position:absolute;z-index:1;top:.5em;left:1.625em;width:.4375em;height:5.625em;transform:rotate(-45deg)}.swal2-icon.swal2-success [class^=swal2-success-line]{display:block;position:absolute;z-index:2;height:.3125em;border-radius:.125em;background-color:#a5dc86}.swal2-icon.swal2-success [class^=swal2-success-line][class$=tip]{top:2.875em;left:.8125em;width:1.5625em;transform:rotate(45deg)}.swal2-icon.swal2-success [class^=swal2-success-line][class$=long]{top:2.375em;right:.5em;width:2.9375em;transform:rotate(-45deg)}.swal2-icon.swal2-success.swal2-icon-show .swal2-success-line-tip{animation:swal2-animate-success-line-tip .75s}.swal2-icon.swal2-success.swal2-icon-show .swal2-success-line-long{animation:swal2-animate-success-line-long .75s}.swal2-icon.swal2-success.swal2-icon-show .swal2-success-circular-line-right{animation:swal2-rotate-success-circular-line 4.25s ease-in}.swal2-progress-steps{flex-wrap:wrap;align-items:center;max-width:100%;margin:1.25em auto;padding:0;background:rgba(0,0,0,0);font-weight:600}.swal2-progress-steps li{display:inline-block;position:relative}.swal2-progress-steps .swal2-progress-step{z-index:20;flex-shrink:0;width:2em;height:2em;border-radius:2em;background:#2778c4;color:#fff;line-height:2em;text-align:center}.swal2-progress-steps .swal2-progress-step.swal2-active-progress-step{background:#2778c4}.swal2-progress-steps .swal2-progress-step.swal2-active-progress-step~.swal2-progress-step{background:#add8e6;color:#fff}.swal2-progress-steps .swal2-progress-step.swal2-active-progress-step~.swal2-progress-step-line{background:#add8e6}.swal2-progress-steps .swal2-progress-step-line{z-index:10;flex-shrink:0;width:2.5em;height:.4em;margin:0 -1px;background:#2778c4}[class^=swal2]{-webkit-tap-highlight-color:rgba(0,0,0,0)}.swal2-show{animation:swal2-show .3s}.swal2-hide{animation:swal2-hide .15s forwards}.swal2-noanimation{transition:none}.swal2-scrollbar-measure{position:absolute;top:-9999px;width:50px;height:50px;overflow:scroll}.swal2-rtl .swal2-close{margin-right:initial;margin-left:0}.swal2-rtl .swal2-timer-progress-bar{right:0;left:auto}@keyframes swal2-toast-show{0%{transform:translateY(-0.625em) rotateZ(2deg)}33%{transform:translateY(0) rotateZ(-2deg)}66%{transform:translateY(0.3125em) rotateZ(2deg)}100%{transform:translateY(0) rotateZ(0deg)}}@keyframes swal2-toast-hide{100%{transform:rotateZ(1deg);opacity:0}}@keyframes swal2-toast-animate-success-line-tip{0%{top:.5625em;left:.0625em;width:0}54%{top:.125em;left:.125em;width:0}70%{top:.625em;left:-0.25em;width:1.625em}84%{top:1.0625em;left:.75em;width:.5em}100%{top:1.125em;left:.1875em;width:.75em}}@keyframes swal2-toast-animate-success-line-long{0%{top:1.625em;right:1.375em;width:0}65%{top:1.25em;right:.9375em;width:0}84%{top:.9375em;right:0;width:1.125em}100%{top:.9375em;right:.1875em;width:1.375em}}@keyframes swal2-show{0%{transform:scale(0.7)}45%{transform:scale(1.05)}80%{transform:scale(0.95)}100%{transform:scale(1)}}@keyframes swal2-hide{0%{transform:scale(1);opacity:1}100%{transform:scale(0.5);opacity:0}}@keyframes swal2-animate-success-line-tip{0%{top:1.1875em;left:.0625em;width:0}54%{top:1.0625em;left:.125em;width:0}70%{top:2.1875em;left:-0.375em;width:3.125em}84%{top:3em;left:1.3125em;width:1.0625em}100%{top:2.8125em;left:.8125em;width:1.5625em}}@keyframes swal2-animate-success-line-long{0%{top:3.375em;right:2.875em;width:0}65%{top:3.375em;right:2.875em;width:0}84%{top:2.1875em;right:0;width:3.4375em}100%{top:2.375em;right:.5em;width:2.9375em}}@keyframes swal2-rotate-success-circular-line{0%{transform:rotate(-45deg)}5%{transform:rotate(-45deg)}12%{transform:rotate(-405deg)}100%{transform:rotate(-405deg)}}@keyframes swal2-animate-error-x-mark{0%{margin-top:1.625em;transform:scale(0.4);opacity:0}50%{margin-top:1.625em;transform:scale(0.4);opacity:0}80%{margin-top:-0.375em;transform:scale(1.15)}100%{margin-top:0;transform:scale(1);opacity:1}}@keyframes swal2-animate-error-icon{0%{transform:rotateX(100deg);opacity:0}100%{transform:rotateX(0deg);opacity:1}}@keyframes swal2-rotate-loading{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}@keyframes swal2-animate-question-mark{0%{transform:rotateY(-360deg)}100%{transform:rotateY(0)}}@keyframes swal2-animate-i-mark{0%{transform:rotateZ(45deg);opacity:0}25%{transform:rotateZ(-25deg);opacity:.4}50%{transform:rotateZ(15deg);opacity:.8}75%{transform:rotateZ(-5deg);opacity:1}100%{transform:rotateX(0);opacity:1}}body.swal2-shown:not(.swal2-no-backdrop):not(.swal2-toast-shown){overflow:hidden}body.swal2-height-auto{height:auto !important}body.swal2-no-backdrop .swal2-container{background-color:rgba(0,0,0,0) !important;pointer-events:none}body.swal2-no-backdrop .swal2-container .swal2-popup{pointer-events:all}body.swal2-no-backdrop .swal2-container .swal2-modal{box-shadow:0 0 10px rgba(0,0,0,.4)}@media print{body.swal2-shown:not(.swal2-no-backdrop):not(.swal2-toast-shown){overflow-y:scroll !important}body.swal2-shown:not(.swal2-no-backdrop):not(.swal2-toast-shown)>[aria-hidden=true]{display:none}body.swal2-shown:not(.swal2-no-backdrop):not(.swal2-toast-shown) .swal2-container{position:static !important}}body.swal2-toast-shown .swal2-container{box-sizing:border-box;width:360px;max-width:100%;background-color:rgba(0,0,0,0);pointer-events:none}body.swal2-toast-shown .swal2-container.swal2-top{top:0;right:auto;bottom:auto;left:50%;transform:translateX(-50%)}body.swal2-toast-shown .swal2-container.swal2-top-end,body.swal2-toast-shown .swal2-container.swal2-top-right{top:0;right:0;bottom:auto;left:auto}body.swal2-toast-shown .swal2-container.swal2-top-start,body.swal2-toast-shown .swal2-container.swal2-top-left{top:0;right:auto;bottom:auto;left:0}body.swal2-toast-shown .swal2-container.swal2-center-start,body.swal2-toast-shown .swal2-container.swal2-center-left{top:50%;right:auto;bottom:auto;left:0;transform:translateY(-50%)}body.swal2-toast-shown .swal2-container.swal2-center{top:50%;right:auto;bottom:auto;left:50%;transform:translate(-50%, -50%)}body.swal2-toast-shown .swal2-container.swal2-center-end,body.swal2-toast-shown .swal2-container.swal2-center-right{top:50%;right:0;bottom:auto;left:auto;transform:translateY(-50%)}body.swal2-toast-shown .swal2-container.swal2-bottom-start,body.swal2-toast-shown .swal2-container.swal2-bottom-left{top:auto;right:auto;bottom:0;left:0}body.swal2-toast-shown .swal2-container.swal2-bottom{top:auto;right:auto;bottom:0;left:50%;transform:translateX(-50%)}body.swal2-toast-shown .swal2-container.swal2-bottom-end,body.swal2-toast-shown .swal2-container.swal2-bottom-right{top:auto;right:0;bottom:0;left:auto}");
/***/ }),
/***/ 65:
/***/ ((module) => {
module.exports = ".mzf_btn{text-align:center;font-size:.85em;color:#09aaff;border:2px solid #c3eaff;border-radius:4px;margin-left:5px;padding:10px;padding-top:5px;padding-bottom:5px;cursor:pointer}.mzf_btn2{text-align:center;color:#09aaff;margin-left:5px;cursor:pointer}.mzf_link{font-family:inherit;color:#09aaff;text-decoration:none;vertical-align:baseline}.mzf_text{font-feature-settings:\\"lnum\\";-webkit-font-smoothing:antialiased;font-family:inherit;color:#545454;font-weight:400;word-break:break-word;-webkit-tap-highlight-color:transparent;margin:0;padding:0;width:100%;height:34px;display:block;line-height:34px;text-align:center;white-space:nowrap}.mzf_arrow{margin-right:5px;transform:rotate(180deg);transition:transform .2s;fill:none;stroke:gray}.mzf_details{cursor:pointer}.mzf_details summary{white-space:nowrap}.mzf_content{max-height:0;margin:0;transition:max-height .5s;overflow:hidden}.mzf_details[open]>summary>svg{transform:rotate(0deg)}.mzf_details[open]+.mzf_content{max-height:100%}.mzf_html_container{grid-template-columns:minmax(0, 100%);align-self:center;justify-self:center;width:32em;max-width:100%}.mzf_updateInfo{border:1px #000;width:100%;margin:0 auto}.mzf_updateInfo span{vertical-align:baseline}"
/***/ }),
/***/ 184:
/***/ ((module) => {
module.exports = "<div class=\\"panel-body\\" style=\\"height: 220px;\\">\\r\\n <div class=\\"mzf_updateInfo\\">\\r\\n <p>更新日志:</p>\\r\\n <p>修复生成错误秒传的问题: 23.4.25发布的 <span style=\\"color: red;\\">2.7.3, 2.7.4</span> 这两个版本会生成错误的秒传, 错误秒传在<span style=\\"color: red;\\">文件上传者账号</span>正常转存, 但在其他的账号会报错 <span style=\\"color: red;\\">秒传未生效#404</span>, 出现此问题注意使用当前版本重新生成秒传</p>\\r\\n </br>\\r\\n <ul>\\r\\n <li>关联: <a href=\\"<https://afdian.net/@mengzonefire\\>" class=\\"mzf_link\\" rel=\\"noopener noreferrer\\"\\r\\n target=\\"_blank\\">赞助页</a>\\r\\n <a href=\\"<https://greasyfork.org/zh-CN/scripts/424574\\>" class=\\"mzf_link\\" rel=\\"noopener noreferrer\\"\\r\\n target=\\"_blank\\">反馈页</a>\\r\\n </li>\\r\\n <li><a href=\\"<https://greasyfork.org/zh-CN/scripts/459862\\>" class=\\"mzf_link\\" rel=\\"noopener noreferrer\\"\\r\\n target=\\"_blank\\">秒传链接提取Ultra</a>: 快速转存网页上的秒传链接</li>\\r\\n <li>秒传文档: <a href=\\"<https://mengzonefire.code.misakanet.cn/rapid-upload-userscript-doc\\>" class=\\"mzf_link\\"\\r\\n rel=\\"noopener noreferrer\\" target=\\"_blank\\">载点1</a>\\r\\n <a href=\\"<https://xtsat.github.io/rapid-upload-userscript-doc\\>" class=\\"mzf_link\\" rel=\\"noopener noreferrer\\"\\r\\n target=\\"_blank\\">载点2</a>\\r\\n </li>\\r\\n <li>脚本更新历史: <a href=\\"<https://mengzonefire.code.misakanet.cn/rapid-upload-userscript-doc/development/脚本更新日志\\>"\\r\\n class=\\"mzf_link\\" rel=\\"noopener noreferrer\\" target=\\"_blank\\">载点1</a>\\r\\n <a href=\\"<https://xtsat.github.io/rapid-upload-userscript-doc/development/脚本更新日志\\>" class=\\"mzf_link\\"\\r\\n rel=\\"noopener noreferrer\\" target=\\"_blank\\">载点2</a>\\r\\n </li>\\r\\n <li>秒传网页版工具: <a href=\\"<https://rapidacg.gmgard.moe/\\>" class=\\"mzf_link\\" rel=\\"noopener noreferrer\\"\\r\\n target=\\"_blank\\">载点1</a>\\r\\n <a href=\\"<https://mengzonefire.github.io/baidupan-rapidupload\\>" class=\\"mzf_link\\" rel=\\"noopener noreferrer\\"\\r\\n target=\\"_blank\\">载点2</a>\\r\\n <a href=\\"<https://mengzonefire.code.misakanet.cn/baidupan-rapidupload\\>" class=\\"mzf_link\\" rel=\\"noopener noreferrer\\"\\r\\n target=\\"_blank\\">载点3</a>\\r\\n </li>\\r\\n <li>项目源码: <a href=\\"<https://github.com/mengzonefire/rapid-upload-userscript\\>" class=\\"mzf_link\\"\\r\\n rel=\\"noopener noreferrer\\" target=\\"_blank\\">秒传脚本</a>\\r\\n <a href=\\"<https://github.com/XTsat/rapid-upload-userscript-doc\\>" class=\\"mzf_link\\" rel=\\"noopener noreferrer\\"\\r\\n target=\\"_blank\\">秒传文档</a>\\r\\n <a href=\\"<https://github.com/mengzonefire/baidupan-rapidupload\\>" class=\\"mzf_link\\" rel=\\"noopener noreferrer\\"\\r\\n target=\\"_blank\\">秒传网页版工具</a>\\r\\n </li>\\r\\n </ul>\\r\\n </div>\\r\\n</div>"
/***/ }),
/***/ 149:
/***/ ((module) => {
module.exports = "/*自定义单选框样式*/\\r\\n.mzf_check {\\r\\n display: inline-block;\\r\\n background-color: white;\\r\\n border-radius: 5px;\\r\\n border: 1px solid #d3d3d3;\\r\\n width: 20px;\\r\\n height: 20px;\\r\\n text-align: center;\\r\\n vertical-align: middle;\\r\\n line-height: 20px;\\r\\n margin-left: 10px;\\r\\n}\\r\\n.mzf_check_ori:checked + .mzf_check {\\r\\n background-color: #eee;\\r\\n}\\r\\n.mzf_check_ori:checked + .mzf_check::after {\\r\\n content: \\"✓\\";\\r\\n}\\r\\n.mzf_check_ori {\\r\\n display: none;\\r\\n}\\r\\n\\r\\n/*新版度盘页面的按钮样式(直接拷贝)*/\\r\\n.mzf_new_btn {\\r\\n -webkit-text-size-adjust: 100%;\\r\\n -webkit-font-smoothing: antialiased;\\r\\n -webkit-tap-highlight-color: transparent;\\r\\n vertical-align: middle;\\r\\n font: inherit;\\r\\n overflow: visible;\\r\\n text-transform: none;\\r\\n font-family: SFUIText, PingFangSC-Regular, Helvetica Neue, Helvetica, Arial,\\r\\n sans-serif;\\r\\n display: inline-block;\\r\\n line-height: 1;\\r\\n white-space: nowrap;\\r\\n cursor: pointer;\\r\\n background: #fff;\\r\\n text-align: center;\\r\\n box-sizing: border-box;\\r\\n outline: 0;\\r\\n margin: 0;\\r\\n transition: 0.1s;\\r\\n color: #fff;\\r\\n background-color: #06a7ff;\\r\\n font-weight: 700;\\r\\n padding: 8px 24px;\\r\\n height: 32px;\\r\\n font-size: 14px;\\r\\n border-radius: 16px;\\r\\n border: none;\\r\\n margin-left: 8px;\\r\\n}\\r\\n"
/***/ })
/******/ });
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ var cachedModule = __webpack_module_cache__[moduleId];
/******/ if (cachedModule !== undefined) {
/******/ return cachedModule.exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = __webpack_module_cache__[moduleId] = {
/******/ // no module.id needed
/******/ // no module.loaded needed
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/************************************************************************/
/******/ /* webpack/runtime/compat get default export */
/******/ (() => {
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = (module) => {
/******/ var getter = module && module.__esModule ?
/******/ () => (module['default']) :
/******/ () => (module);
/******/ __webpack_require__.d(getter, { a: getter });
/******/ return getter;
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/define property getters */
/******/ (() => {
/******/ // define getter functions for harmony exports
/******/ __webpack_require__.d = (exports, definition) => {
/******/ for(var key in definition) {
/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ }
/******/ }
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/hasOwnProperty shorthand */
/******/ (() => {
/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ })();
/******/
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be in strict mode.
(() => {
"use strict";
// EXTERNAL MODULE: ./src/css/app.css
var app = __webpack_require__(149);
var app_default = /*#__PURE__*/__webpack_require__.n(app);
// EXTERNAL MODULE: ./src/css/app.scss
var css_app = __webpack_require__(65);
var css_app_default = /*#__PURE__*/__webpack_require__.n(css_app);
;// CONCATENATED MODULE: ./src/common/const.tsx
/*
* @Author: mengzonefire
* @Date: 2021-07-23 17:41:28
* @LastEditTime: 2023-05-15 16:53:31
* @LastEditors: mengzonefire
* @Description: 存放各种全局常量对象
*/
var version = "2.7.8"; // 当前版本号
var updateDate = "23.5.15"; // 更新弹窗显示的日期
var updateInfoVer = "2.7.5"; // 更新弹窗的版本, 没必要提示的非功能性更新就不弹窗了
var swalCssVer = "1.7.4"; // 由于其他主题的Css代码会缓存到本地, 故更新主题包版本(url)时, 需要同时更新该字段以刷新缓存
var donateVer = "2.6.4"; // 用于检测可关闭的赞助提示的版本号
var feedbackVer = "2.6.4"; // 用于检测可关闭的反馈提示的版本号
var referralVer = "2.6.4"; // 用于检测可关闭的推广提示的版本号
var locUrl = location.href;
var baiduNewPage = "baidu.com/disk/main"; // 匹配新版度盘界面
var baiduSyncPage = "baidu.com/disk/synchronization"; // 匹配同步空间
var baiduSharePage = "baidu.com/s/"; // 匹配分享页
var TAG = "[秒传链接提取 by mengzonefire]";
var homePage = "<https://greasyfork.org/zh-CN/scripts/424574>";
var donatePage = "<https://afdian.net/@mengzonefire>";
var referralPage = "<https://snsyun.baidu.com/sl/eQlxlz8>";
var ajaxError = 514; // 自定义ajax请求失败时的错误码(不能与http statusCode冲突)
var bdlinkPrefix = "<https://pan.baidu.com/#bdlink=>"; // 一键秒传链接的前缀
var commandList = ["set", "gen", "info"]; // 转存输入框内支持输入的命令
var UA = "netdisk;"; // 自定义User-Agent
var extCssUrl = {
Default: "",
Dark: "<https://cdn.jsdelivr.net/npm/@sweetalert2/theme-dark@5/dark.min.css>",
"WordPress Admin": "<https://cdn.jsdelivr.net/npm/@sweetalert2/theme-wordpress-admin@5/wordpress-admin.min.css>",
"Material UI": "<https://cdn.jsdelivr.net/npm/@sweetalert2/theme-material-ui@5/material-ui.min.css>",
Bulma: "<https://cdn.jsdelivr.net/npm/@sweetalert2/theme-bulma@5/bulma.min.css>",
"Bootstrap 4": "<https://cdn.jsdelivr.net/npm/@sweetalert2/theme-bootstrap-4/bootstrap-4.min.css>",
}; // 各主题包对应的url
var appError = {
SwalCssInvalid: "\\u6837\\u5F0F\\u5305\\u6570\\u636E\\u9519\\u8BEF, \\u81EA\\u52A8\\u4F7F\\u7528\\u5185\\u7F6E\\u6837\\u5F0F (\\u8BF7\\u70B9\\u786E\\u5B9A)",
SwalCssErrReq: "\\u6837\\u5F0F\\u5305\\u52A0\\u8F7D\\u5931\\u8D25, \\u81EA\\u52A8\\u4F7F\\u7528\\u5185\\u7F6E\\u6837\\u5F0F (\\u8BF7\\u70B9\\u786E\\u5B9A), \\u9519\\u8BEF\\u4EE3\\u7801: ",
ClipboardPremissionErr: '使用 "监听剪贴板" 功能需要允许剪贴板权限!\\n该功能只支持Chrome系/Edge/Opera浏览器, 不支持Firefox, 同时注意使用https访问页面 (http访问会导致浏览器直接禁止剪贴板权限)',
}; // 主程序异常
var appWarning = {
fastGenerateWarn: '使用 "极速生成" 功能请注意:\\n优点:\\n1. 极大幅度提高秒传生成速度\\n2. 有效避免 "md5获取失败(#996)" "接口限制访问(#403)"\\n缺点:\\n1. 生成和谐文件秒传时大概率正常生成 (非极速生成则会报错#1919)\\n2. 生成的秒传格式为简化版, 只保证最新版的 秒传脚本 和 秒传网页版 支持转存\\n\\n* 若开启后出现问题请根据设置页内的 "说明文档" 进行反馈',
}; // 主程序各功能警告/提醒
var docPrefix = "<https://mengzonefire.code.misakanet.cn/rapid-upload-userscript-doc/document>";
var docPrefix2 = "<https://xtsat.github.io/rapid-upload-userscript-doc/document>";
var doc = {
shareDoc: docPrefix + "/FAQ/\\u9519\\u8BEF\\u4EE3\\u7801",
linkTypeDoc: docPrefix + "/Info/\\u79D2\\u4F20\\u683C\\u5F0F",
bdlinkDoc: docPrefix + "/\\u79D2\\u4F20\\u94FE\\u63A5\\u751F\\u6210/\\u4E00\\u952E\\u79D2\\u4F20",
fastGenDoc: docPrefix + "/\\u79D2\\u4F20\\u94FE\\u63A5\\u751F\\u6210/\\u6781\\u901F\\u751F\\u6210",
}; // 文档载点1
var doc2 = {
shareDoc: docPrefix2 + "/FAQ/\\u9519\\u8BEF\\u4EE3\\u7801",
linkTypeDoc: docPrefix2 + "/Info/\\u79D2\\u4F20\\u683C\\u5F0F",
bdlinkDoc: docPrefix2 + "/\\u79D2\\u4F20\\u94FE\\u63A5\\u751F\\u6210/\\u4E00\\u952E\\u79D2\\u4F20",
fastGenDoc: docPrefix2 + "/\\u79D2\\u4F20\\u94FE\\u63A5\\u751F\\u6210/\\u6781\\u901F\\u751F\\u6210",
}; // 文档载点2
var linkStyle = 'class="mzf_link" rel="noopener noreferrer" target="_blank"';
var btnStyle = 'class="mzf_btn" rel="noopener noreferrer" target="_blank"';
var bdlinkPattern = /#bdlink=([\\da-zA-Z+/=]+)/; // b64可能出现的字符: 大小写字母a-zA-Z, 数字0-9, +, /, = (=用于末尾补位)
var htmlDocument = "<p class=\\"mzf_text\\">\\u79D2\\u4F20\\u65E0\\u6548,\\u9632\\u548C\\u8C10\\u7B49 \\u53EF\\u53C2\\u8003\\u79D2\\u4F20\\u6587\\u6863<a href=\\"" + doc.shareDoc + "\\" " + btnStyle + "><span class=\\"text\\" style=\\"width: auto;\\">\\u8F7D\\u70B91</span></a><a href=\\"" + doc2.shareDoc + "\\" " + btnStyle + "><span class=\\"text\\" style=\\"width: auto;\\">\\u8F7D\\u70B92</span></a></p>";
var htmlDonate = "<p id=\\"mzf_donate\\" class=\\"mzf_text\\">\\u82E5\\u559C\\u6B22\\u8BE5\\u811A\\u672C, \\u53EF\\u524D\\u5F80 <a href=\\"" + donatePage + "\\" " + linkStyle + ">\\u8D5E\\u52A9\\u9875</a> \\u652F\\u6301\\u4F5C\\u8005<a id=\\"mzf_kill_donate\\" class=\\"mzf_btn\\">\\u4E0D\\u518D\\u663E\\u793A</a></p>";
var htmlFeedback = "<p id=\\"mzf_feedback\\" class=\\"mzf_text\\">\\u82E5\\u6709\\u4EFB\\u4F55\\u7591\\u95EE, \\u53EF\\u524D\\u5F80 <a href=\\"" + homePage + "\\" " + linkStyle + ">\\u811A\\u672C\\u4E3B\\u9875</a> \\u53CD\\u9988<a id=\\"mzf_kill_feedback\\" class=\\"mzf_btn\\">\\u4E0D\\u518D\\u663E\\u793A</a></p>";
var htmlReferral = "<p id=\\"mzf_referral\\" class=\\"mzf_text\\">(\\u767E\\u5EA6\\u5B98\\u65B9\\u63A8\\u5E7F) <a href=\\"" + referralPage + "\\" " + linkStyle + ">\\u4F18\\u60E0\\u5F00\\u901A\\u7F51\\u76D8\\u4F1A\\u5458</a><a id=\\"mzf_kill_referral\\" class=\\"mzf_btn\\">\\u4E0D\\u518D\\u663E\\u793A</a></p>";
var htmlAboutBdlink = "\\u4EC0\\u4E48\\u662F\\u4E00\\u952E\\u79D2\\u4F20?: <a href=\\"" + doc.bdlinkDoc + "\\" " + linkStyle + ">\\u6587\\u6863\\u8F7D\\u70B91</a> <a href=\\"" + doc2.bdlinkDoc + "\\" " + linkStyle + ">\\u6587\\u6863\\u8F7D\\u70B92</a>";
var copyFailList = '<a id="copy_fail_list" class="mzf_btn2">复制列表</a>';
var copyFailBranchList = '<a id="copy_fail_branch_list" class="mzf_btn2">复制列表</a>';
var copySuccessList = '<a id="copy_success_list" class="mzf_btn2">复制列表</a>';
;// CONCATENATED MODULE: ./src/common/duParser.tsx
/*
* @Author: mengzonefire
* @Date: 2021-08-26 12:01:28
* @LastEditTime: 2022-08-29 10:21:05
* @LastEditors: mengzonefire
* @Description: 各种解析器
*/
/**
* @description: 从url中解析秒传链接
*/
function parseQueryLink(url) {
var bdlinkB64 = url.match(bdlinkPattern);
return bdlinkB64 ? bdlinkB64[1].fromBase64() : "";
}
/**
* @description: 秒传链接解析器
*/
function DuParser() { }
DuParser.parse = function generalDuCodeParse(szUrl) {
var r;
if (szUrl.indexOf("bdpan") === 0) {
r = DuParser.parseDu_v1(szUrl);
r.ver = "PanDL";
}
else if (szUrl.indexOf("BaiduPCS-Go") === 0) {
r = DuParser.parseDu_v2(szUrl);
r.ver = "PCS-Go";
}
else if (szUrl.indexOf("BDLINK") === 0) {
r = DuParser.parseDu_v3(szUrl);
r.ver = "游侠 v1";
}
else {
r = DuParser.parseDu_v4(szUrl);
r.ver = "梦姬标准";
}
return r;
};
DuParser.parseDu_v1 = function parseDu_v1(szUrl) {
return szUrl
.replace(/\\s*bdpan:\\/\\//g, " ")
.trim()
.split(" ")
.map(function (z) {
return z
.trim()
.fromBase64()
.match(/([\\s\\S]+)\\|([\\d]{1,20})\\|([\\da-f]{32})\\|([\\da-f]{32})/i);
})
.filter(function (z) {
return z;
})
.map(function (info) {
return {
md5: info[3],
md5s: info[4],
size: info[2],
path: info[1],
};
});
};
DuParser.parseDu_v2 = function parseDu_v2(szUrl) {
return szUrl
.split("\\n")
.map(function (z) {
// unsigned long long: 0~18446744073709551615
return z
.trim()
.match(/-length=([\\d]{1,20}) -md5=([\\da-f]{32}) -slicemd5=([\\da-f]{32})[\\s\\S]+"([\\s\\S]+)"/i);
})
.filter(function (z) {
return z;
})
.map(function (info) {
return {
md5: info[2],
md5s: info[3],
size: info[1],
path: info[4],
};
});
};
DuParser.parseDu_v3 = function parseDu_v3(szUrl) {
var raw = atob(szUrl.slice(6).replace(/\\s/g, ""));
if (raw.slice(0, 5) !== "BDFS\\x00") {
return null;
}
var buf = new SimpleBuffer(raw);
var ptr = 9;
var arrFiles = [];
var fileInfo, nameSize;
var total = buf.readUInt(5);
var i;
for (i = 0; i < total; i++) {
// 大小 (8 bytes)
// MD5 + MD5S (0x20)
// nameSize (4 bytes)
// Name (unicode)
fileInfo = {};
fileInfo.size = buf.readULong(ptr + 0);
fileInfo.md5 = buf.readHex(ptr + 8, 0x10);
fileInfo.md5s = buf.readHex(ptr + 0x18, 0x10);
nameSize = buf.readUInt(ptr + 0x28) << 1;
fileInfo.nameSize = nameSize;
ptr += 0x2c;
fileInfo.path = buf.readUnicode(ptr, nameSize);
arrFiles.push(fileInfo);
ptr += nameSize;
}
return arrFiles;
};
DuParser.parseDu_v4 = function parseDu_v3(szUrl) {
return szUrl
.split("\\n")
.map(function (z) {
return z
.trim()
.match(/^([\\da-f]{9}[\\da-z][\\da-f]{22})#(?:([\\da-f]{32})#)?([\\d]{1,20})#([\\s\\S]+)/i); // 22.8.29新增支持第10位为g-z的加密md5, 输入后自动解密转存
})
.filter(function (z) {
return z;
})
.map(function (info) {
return {
// 标准码 / 短版标准码(无md5s)
md5: decryptMd5(info[1].toLowerCase()),
md5s: info[2] || "",
size: info[3],
path: info[4],
};
});
};
/**
* 一个简单的类似于 NodeJS Buffer 的实现.
* 用于解析游侠度娘提取码。
* @param {SimpleBuffer}
*/
function SimpleBuffer(str) {
this.fromString(str);
}
SimpleBuffer.toStdHex = function toStdHex(n) {
return ("0" + n.toString(16)).slice(-2);
};
SimpleBuffer.prototype.fromString = function fromString(str) {
var len = str.length;
this.buf = new Uint8Array(len);
for (var i = 0; i < len; i++) {
this.buf[i] = str.charCodeAt(i);
}
};
SimpleBuffer.prototype.readUnicode = function readUnicode(index, size) {
if (size & 1) {
size++;
}
var bufText = Array.prototype.slice
.call(this.buf, index, index + size)
.map(SimpleBuffer.toStdHex);
var buf = [""];
for (var i = 0; i < size; i += 2) {
buf.push(bufText[i + 1] + bufText[i]);
}
return JSON.parse('"' + buf.join("\\\\u") + '"');
};
SimpleBuffer.prototype.readNumber = function readNumber(index, size) {
var ret = 0;
for (var i = index + size; i > index;) {
ret = this.buf[--i] + ret * 256;
}
return ret;
};
SimpleBuffer.prototype.readUInt = function readUInt(index) {
return this.readNumber(index, 4);
};
SimpleBuffer.prototype.readULong = function readULong(index) {
return this.readNumber(index, 8);
};
SimpleBuffer.prototype.readHex = function readHex(index, size) {
return Array.prototype.slice
.call(this.buf, index, index + size)
.map(SimpleBuffer.toStdHex)
.join("");
};
// EXTERNAL MODULE: ./src/components/updateInfo.html
var updateInfo = __webpack_require__(184);
var updateInfo_default = /*#__PURE__*/__webpack_require__.n(updateInfo);
;// CONCATENATED MODULE: ./src/common/swalConfig.tsx
/*
* @Author: mengzonefire
* @Date: 2021-08-26 12:16:57
* @LastEditTime: 2023-02-18 21:27:36
* @LastEditors: mengzonefire
* @Description: 存放各Swal弹窗的固定参数配置
*/
var SwalConfig = {
inputView: {
title: "请输入秒传&保存路径",
showCancelButton: true,
html: "<textarea id=\\"mzf-rapid-input\\" class=\\"swal2-textarea\\" placeholder=\\"\\u00B7 \\u652F\\u6301\\u6279\\u91CF\\u8F6C\\u5B58\\u591A\\u6761\\u79D2\\u4F20(\\u6362\\u884C\\u5206\\u9694)\\n\\u00B7 \\u652F\\u6301PanDL/\\u6E38\\u4FA0/\\u6807\\u51C6\\u7801/PCS-GO\\u683C\\u5F0F\\n\\u00B7 \\u652F\\u6301\\u8F93\\u5165\\u4E00\\u952E\\u79D2\\u4F20(\\u81EA\\u52A8\\u8F6C\\u6362\\u4E3A\\u666E\\u901A\\u79D2\\u4F20)\\n\\u00B7 \\u53EF\\u5728\\u8BBE\\u7F6E\\u9875\\u5F00\\u542F\\u76D1\\u542C\\u526A\\u8D34\\u677F,\\u81EA\\u52A8\\u7C98\\u8D34\\u79D2\\u4F20\\n\\u00B7 \\u8F93\\u5165set\\u8FDB\\u5165\\u8BBE\\u7F6E\\u9875,gen\\u8FDB\\u5165\\u751F\\u6210\\u9875,info\\u8FDB\\u5165\\u7248\\u672C\\u4FE1\\u606F\\u9875\\" style=\\"display: flex;padding: 0.4em;\\"></textarea>\\n <input id=\\"mzf-path-input\\" class=\\"swal2-input\\" placeholder=\\"\\u4FDD\\u5B58\\u8DEF\\u5F84, \\u793A\\u4F8B: /GTA5/, \\u7559\\u7A7A\\u4FDD\\u5B58\\u5728\\u5F53\\u524D\\u76EE\\u5F55\\" style=\\"display: flex;margin-top: 10px;\\">",
confirmButtonText: "确定",
cancelButtonText: "取消",
customClass: { htmlContainer: "mzf_html_container" },
},
processView: {
showCloseButton: true,
showConfirmButton: false,
allowOutsideClick: false,
},
finishView: {
showCloseButton: true,
allowOutsideClick: false,
},
genUnfinish: {
title: "检测到上次未完成的秒传任务",
text: "是否继续该任务?",
showCancelButton: true,
allowOutsideClick: false,
confirmButtonText: "是",
cancelButtonText: "否",
},
genUnfinish2: {
title: "检测到上次未正常退出的秒传任务",
text: "是否恢复该任务?",
showCancelButton: true,
allowOutsideClick: false,
confirmButtonText: "是",
cancelButtonText: "否",
},
genView: {
title: "请输入需要生成的文件路径",
input: "textarea",
showCancelButton: true,
showCloseButton: true,
inputPlaceholder: "[支持批量(换行分隔)]",
confirmButtonText: "确定",
cancelButtonText: "取消",
inputValidator: function (value) {
if (!value) {
return "文件路径不能为空";
}
},
},
updateInfo: {
title: "\\u79D2\\u4F20\\u94FE\\u63A5\\u63D0\\u53D6 v" + version + " (" + updateDate + ")",
showCloseButton: true,
allowOutsideClick: false,
confirmButtonText: "知道了",
html: (updateInfo_default()),
},
checkRecursive: {
icon: "info",
title: "包含文件夹, 是否递归生成?",
text: "若选是, 将同时生成各级子文件夹下的文件",
allowOutsideClick: false,
focusCancel: true,
showCancelButton: true,
reverseButtons: true,
showCloseButton: true,
confirmButtonText: "是",
cancelButtonText: "否",
},
settingView: {
title: "秒传链接提取 设置页",
showCloseButton: true,
showCancelButton: true,
confirmButtonText: "确定",
cancelButtonText: "取消",
allowOutsideClick: false,
html: "<label for=\\"mzf-theme\\" class=\\"swal2-input-label\\" style=\\"margin-top: 0px\\" >\\u4E3B\\u9898\\u8BBE\\u7F6E</label > <select class=\\"swal2-select\\" id=\\"mzf-theme\\" style=\\" display: flex; border-width: 1px; border-style: solid; text-align-last: center; \\" > <option value=\\"Default\\">Default \\u767D\\u8272\\u4E3B\\u9898(\\u9ED8\\u8BA4)</option> <option value=\\"Bulma\\">Bulma \\u767D\\u8272\\u7B80\\u7EA6</option> <option value=\\"Bootstrap 4\\">Bootstrap4 \\u767D\\u8272\\u7B80\\u7EA6</option> <option value=\\"Material UI\\">MaterialUI \\u767D\\u8272\\u4E3B\\u9898</option> <option value=\\"Dark\\">Dark \\u9ED1\\u8272\\u4E3B\\u9898</option> <option value=\\"WordPress Admin\\">WordPressAdmin \\u7070\\u8272\\u4E3B\\u9898</option> </select> <label for=\\"mzf-pathType\\" class=\\"swal2-input-label\\" >\\u751F\\u6210\\u79D2\\u4F20\\u5BFC\\u51FA\\u8DEF\\u5F84\\u8BBE\\u7F6E</label > <select class=\\"swal2-select\\" id=\\"mzf-pathType\\" style=\\" display: flex; border-width: 1px; border-style: solid; text-align-last: center; \\" > <option value=\\"relative\\">\\u5BFC\\u51FA\\u76F8\\u5BF9\\u8DEF\\u5F84</option> <option value=\\"absolute\\">\\u5BFC\\u51FA\\u7EDD\\u5BF9\\u8DEF\\u5F84</option> </select> <label for=\\"mzf-fast-generate\\" class=\\"swal2-checkbox\\" style=\\"display: flex\\" ><span class=\\"swal2-label\\" >\\u6781\\u901F\\u751F\\u6210 \\u8BF4\\u660E\\u6587\\u6863: <a href=\\"" + doc.fastGenDoc + "\\" " + linkStyle + ">\\u8F7D\\u70B91</a> <a href=\\"" + doc2.fastGenDoc + "\\" " + linkStyle + ">\\u8F7D\\u70B92</a></span ><input class=\\"mzf_check_ori\\" type=\\"checkbox\\" value=\\"1\\" id=\\"mzf-fast-generate\\" /><span class=\\"mzf_check\\"></span ></label> <label for=\\"mzf-listen-clipboard\\" class=\\"swal2-checkbox\\" style=\\"display: flex\\" ><span class=\\"swal2-label\\">\\u76D1\\u542C\\u526A\\u8D34\\u677F (\\u9700\\u8981\\u5141\\u8BB8\\u526A\\u8D34\\u677F\\u6743\\u9650)</span ><input class=\\"mzf_check_ori\\" type=\\"checkbox\\" value=\\"1\\" id=\\"mzf-listen-clipboard\\" /><span class=\\"mzf_check\\"></span ></label>",
},
settingWarning: {
title: "设置成功 刷新页面生效",
showCloseButton: true,
allowOutsideClick: false,
confirmButtonText: "知道了",
},
selectNoFileWarning: {
title: "请勾选要生成秒传的文件/文件夹",
icon: "error",
showCloseButton: true,
confirmButtonText: "知道了",
},
};
// EXTERNAL MODULE: ./node_modules/sweetalert2/dist/sweetalert2.all.js
var sweetalert2_all = __webpack_require__(455);
var sweetalert2_all_default = /*#__PURE__*/__webpack_require__.n(sweetalert2_all);
;// CONCATENATED MODULE: ./src/common/swalBase.tsx
/*
* @Author: mengzonefire
* @Date: 2021-08-25 08:34:46
* @LastEditTime: 2023-04-11 14:10:57
* @LastEditors: mengzonefire
* @Description: 定义全套的前台弹窗逻辑, 在Swal的回调函数内调用***Task类内定义的任务代码
*/
var __assign = (undefined && undefined.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __awaiter = (undefined && undefined.__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 = (undefined && undefined.__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 __spreadArray = (undefined && undefined.__spreadArray) || function (to, from) {
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
to[j] = from[i];
return to;
};
var Swalbase = /** @class */ (function () {
function Swalbase(rapiduploadTask, generatebdlinkTask) {
this.rapiduploadTask = rapiduploadTask;
this.generatebdlinkTask = generatebdlinkTask;
}
// 合并swal参数
Swalbase.prototype.mergeArg = function () {
var inputArgs = [];
for (var _i = 0; _i < arguments.length; _i++) {
inputArgs[_i] = arguments[_i];
}
var output = {};
var swalCfgArgs = {
// 禁用backdrop动画, 阻止多次弹窗时的屏闪
showClass: { backdrop: "swal2-noanimation" },
hideClass: { backdrop: "swal2-noanimation" },
};
$.extend.apply($, __spreadArray([output, this.swalGlobalArgs, swalCfgArgs], inputArgs));
return output;
};
// 点击 "秒传链接" 后显示的弹窗
Swalbase.prototype.inputView = function (inputValue) {
if (inputValue === void 0) { inputValue = ""; }
return __awaiter(this, void 0, void 0, function () {
var pathValue, preConfirm, willOpen;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!(GM_getValue("listen-clipboard") && !inputValue)) return [3 /*break*/, 2];
return [4 /*yield*/, parseClipboard()];
case 1:
// 标志位true 且 inputValue为空(非一键秒传进入时) 从剪贴板读取有效的秒传链接
inputValue = _a.sent();
_a.label = 2;
case 2:
pathValue = GM_getValue("last_dir") || "";
preConfirm = function () {
// 手动读取Multiple inputs内的数据, 由于未设置input参数, 原生Validator不生效, 自行添加Validator逻辑
inputValue = $("#mzf-rapid-input")[0].value;
pathValue = $("#mzf-path-input")[0]
.value.trim()
.replace(/(\\s+)?\\/(\\s+)?/g, "/"); // 修正不合规的路径(空白开头/结尾)
if (!inputValue) {
sweetalert2_all_default().showValidationMessage("秒传不能为空");
return false;
}
if (commandList.includes(inputValue.trim())) {
// 输入支持的命令, 跳出检查
inputValue = inputValue.trim();
return;
}
if (!DuParser.parse(inputValue).length) {
sweetalert2_all_default().showValidationMessage("<p>\\u672A\\u8BC6\\u522B\\u5230\\u6B63\\u786E\\u7684\\u94FE\\u63A5 <a href=\\"" + doc.linkTypeDoc + "\\" " + linkStyle + ">\\u67E5\\u770B\\u652F\\u6301\\u683C\\u5F0F</a></p>");
return false;
}
if (pathValue.match(illegalPathPattern)) {
sweetalert2_all_default().showValidationMessage('保存路径不能含有字符\\\\":*?<>|, 示例:/GTA5/');
return false;
}
};
willOpen = function () {
$("#swal2-html-container")
.css("font-size", "1rem")
.css("display", "grid")
.css("margin", "0");
$("#mzf-rapid-input")[0].value = inputValue;
$("#mzf-path-input")[0].value = pathValue;
$("#mzf-rapid-input").on("input", function (event) {
var result = parseQueryLink(event.target.value);
if (DuParser.parse(result).length)
event.target.value = result;
}); // 绑定输入框事件, 输入一键秒传后尝试转换为普通秒传
};
sweetalert2_all_default().fire(this.mergeArg(SwalConfig.inputView, {
preConfirm: preConfirm,
willOpen: willOpen,
})).then(function (result) {
if (result.isConfirmed) {
if (inputValue === "set")
_this.settingView();
else if (inputValue === "gen")
_this.genView();
else if (inputValue === "info")
_this.updateInfo(function () { });
else {
_this.rapiduploadTask.reset();
_this.rapiduploadTask.fileInfoList = DuParser.parse(inputValue);
GM_setValue("last_dir", pathValue);
if (!pathValue) {
// 路径留空
_this.rapiduploadTask.isDefaultPath = true;
var nowPath = location.href.match(/path=(.+?)(?:&|$)/);
if (nowPath)
pathValue = decodeURIComponent(nowPath[1]);
else
pathValue = "/";
}
if (pathValue.charAt(0) !== "/")
pathValue = "/" + pathValue; // 补齐路径前缀斜杠
if (pathValue.charAt(pathValue.length - 1) !== "/")
pathValue += "/"; // 补全路径结尾的斜杠
if (locUrl.includes(baiduSyncPage) &&
!pathValue.includes(syncPathPrefix))
pathValue = syncPathPrefix + pathValue; // 补全同步页路径前缀
console.log("\\u79D2\\u4F20\\u6587\\u4EF6\\u4FDD\\u5B58\\u5230: " + pathValue); // debug
_this.rapiduploadTask.savePath = pathValue;
_this.processView(false);
}
}
});
return [2 /*return*/];
}
});
});
};
// 转存/生成过程中的弹窗
Swalbase.prototype.processView = function (isGen) {
var _this = this;
var swalArg = {
title: isGen ? "秒传生成中" : "文件转存中",
html: isGen
? "<p>正在生成第 <file_num>0</file_num> 个</p><p><gen_prog>正在获取文件列表...</gen_prog></p>"
: "正在转存第 <file_num>0</file_num> 个",
willOpen: function () {
sweetalert2_all_default().showLoading();
isGen || _this.saveFileWork();
},
};
sweetalert2_all_default().fire(this.mergeArg(SwalConfig.processView, swalArg));
};
// 转存/生成秒传完成的弹窗
Swalbase.prototype.finishView = function (isGen) {
var _this = this;
var action = isGen ? "生成" : "转存";
var fileInfoList = isGen
? this.generatebdlinkTask.fileInfoList
: this.rapiduploadTask.fileInfoList;
var parseResult = parsefileInfo(fileInfoList);
this.parseResult = parseResult;
var checkboxArg = {
input: "checkbox",
inputValue: GM_getValue("with_path"),
inputPlaceholder: "导出文件夹目录结构",
}; // 全部失败不显示此checkbox, 22.5.22: 全部失败也显示
var html = (isGen ? htmlDocument : "") + // 生成模式下添加文档入口
(parseResult.htmlInfo && isGen ? "<br>" : "") +
parseResult.htmlInfo; // 添加失败列表, 生成模式下添加顶部空行分隔
var htmlFooter = "";
if (!GM_getValue(donateVer + "_kill_donate"))
htmlFooter += htmlDonate; // 添加赞助入口提示
if (!GM_getValue(feedbackVer + "_kill_feedback"))
htmlFooter += htmlFeedback; // 添加反馈入口提示
if (!GM_getValue(referralVer + "_kill_referral"))
htmlFooter += htmlReferral; // 添加网盘推广入口提示
if (htmlFooter)
htmlFooter = "<br>" + htmlFooter; // 添加底部空行分隔
var swalArg = __assign(__assign({ title: action + "\\u5B8C\\u6BD5 \\u5171" + fileInfoList.length + "\\u4E2A, \\u5931\\u8D25" + parseResult.failList.length + "\\u4E2A!", confirmButtonText: isGen ? "复制秒传代码" : "确认", showDenyButton: isGen, denyButtonText: "复制一键秒传", denyButtonColor: "#ecae3c", reverseButtons: true, html: html + htmlFooter }, (isGen && checkboxArg)), { willOpen: function () {
if (isGen)
GM_setValue("unClose", true); // 生成模式设置结果窗口未关闭的标记
else
_this.addOpenDirBtn(); // 转存模式时添加 "打开目录" 按钮
},
// 秒传生成的 "复制一键秒传" 按钮回调
preDeny: function () {
var with_path = $("#swal2-checkbox")[0].checked;
GM_setValue("with_path", with_path);
if (!with_path)
GM_setClipboard(bdlinkPrefix + parseResult.bdcode.replace(/\\/.+\\//g, "").toBase64());
// 去除目录结构, 并转换为一键秒传
else
GM_setClipboard(bdlinkPrefix + parseResult.bdcode.toBase64()); // 转换为一键秒传
sweetalert2_all_default().getDenyButton().innerText = "复制成功,点击右上关闭";
var footer = sweetalert2_all_default().getFooter();
footer.innerHTML = htmlAboutBdlink;
footer.style.display = "flex";
return false;
}, preConfirm: function () {
if (isGen) {
// 生成模式, "复制秒传代码"按钮
var with_path = $("#swal2-checkbox")[0].checked;
GM_setValue("with_path", with_path);
if (!with_path)
GM_setClipboard(parseResult.bdcode.replace(/(#\\/.+\\/)|(#\\/)/g, "#"));
// 去除秒传链接中的目录结构(仅保留文件名)
else {
var pathType = GM_getValue("pathType") === undefined
? "relative"
: GM_getValue("pathType");
if ("absolute" === pathType)
GM_setClipboard(parseResult.bdcode);
// 保留完整的文件路径(绝对路径)
else if ("relative" === pathType) {
// 去除前置的路径以及路径开头的'/', 将绝对路径转换为相对路径 (默认执行)
var localPathPrefix = "";
var nowPath = location.href.match(/path=(.+?)(?:&|$)/);
if (nowPath)
localPathPrefix = decodeURIComponent(nowPath[1]);
GM_setClipboard(parseResult.bdcode.replace(new RegExp("(#" + localPathPrefix + "/)|(#/)", "g"), "#"));
}
}
sweetalert2_all_default().getConfirmButton().innerText = "复制成功,点击右上关闭";
return false;
}
else {
// 转存模式, "确定" 按钮
refreshList(); // 调用刷新文件列表的方法
return undefined;
}
} });
sweetalert2_all_default().fire(this.mergeArg(SwalConfig.finishView, swalArg)).then(function (result) {
if (result.isDismissed || result.dismiss === (sweetalert2_all_default()).DismissReason.close) {
GM_deleteValue("unfinish"); // 点击了右上角的关闭按钮, 清除任务进度数据
GM_setValue("unClose", false);
}
});
};
// 生成文件夹秒传, 是否递归生成提示
Swalbase.prototype.checkRecursive = function () {
var _this = this;
sweetalert2_all_default().fire(this.mergeArg(SwalConfig.checkRecursive)).then(function (result) {
if (result.isConfirmed) {
_this.generatebdlinkTask.recursive = true;
}
else if (result.dismiss === (sweetalert2_all_default()).DismissReason.cancel)
_this.generatebdlinkTask.recursive = false;
else
return;
_this.processView(true);
_this.generatebdlinkTask.scanFile(0);
});
};
// 设置页
Swalbase.prototype.settingView = function () {
var _this = this;
var willOpen = function () {
$("#swal2-html-container")
.css("font-size", "1rem")
.css("display", "grid")
.css("margin", "0");
$("#mzf-theme")[0].value = GM_getValue("swalThemes") || "Default";
$("#mzf-pathType")[0].value = GM_getValue("pathType") || "relative";
$("#mzf-listen-clipboard")[0].checked = Boolean(GM_getValue("listen-clipboard"));
$("#mzf-fast-generate")[0].checked = Boolean(GM_getValue("fast-generate") === undefined
? true
: GM_getValue("fast-generate"));
};
var preConfirm = function () { return __awaiter(_this, void 0, void 0, function () {
var error_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
// 设置主题
GM_setValue("swalThemes", $("#mzf-theme")[0].value);
// 设置生成秒传导出路径(相对/绝对)
GM_setValue("pathType", $("#mzf-pathType")[0].value);
if (!$("#mzf-listen-clipboard")[0].checked) return [3 /*break*/, 4];
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, navigator.clipboard.readText()];
case 2:
_a.sent();
GM_setValue("listen-clipboard", $("#mzf-listen-clipboard")[0].checked);
return [3 /*break*/, 4];
case 3:
error_1 = _a.sent();
showAlert(appError.ClipboardPremissionErr);
return [2 /*return*/];
case 4:
// 设置极速生成, 若开启则弹出文本提醒
if ($("#mzf-fast-generate")[0].checked)
showAlert(appWarning.fastGenerateWarn);
GM_setValue("fast-generate", $("#mzf-fast-generate")[0].checked);
return [2 /*return*/];
}
});
}); };
sweetalert2_all_default().fire(this.mergeArg(SwalConfig.settingView, {
willOpen: willOpen,
preConfirm: preConfirm,
})).then(function (result) {
if (result.isConfirmed)
sweetalert2_all_default().fire(_this.mergeArg(SwalConfig.settingWarning));
});
};
// 生成页 (输入路径列表进行秒传生成)
Swalbase.prototype.genView = function () {
var _this = this;
sweetalert2_all_default().fire(this.mergeArg(SwalConfig.genView)).then(function (result) {
if (result.isConfirmed) {
_this.generatebdlinkTask.reset();
result.value.split("\\n").forEach(function (filePath) {
if (filePath.charAt(0) !== "/")
filePath = "/" + filePath; // 补齐路径前缀斜杠
if (locUrl.includes(baiduSyncPage) &&
!filePath.includes(syncPathPrefix))
filePath = syncPathPrefix + filePath; // 补全同步页路径前缀
_this.generatebdlinkTask.fileInfoList.push({
path: filePath,
});
});
_this.processView(true); // 显示进度弹窗
_this.genFileWork(false, true); // 跳过获取选择文件列表和扫描文件夹的步骤
_this.generatebdlinkTask.generateBdlink(0); // 开始生成任务
}
});
};
// 生成秒传未完成任务提示
Swalbase.prototype.genUnfinish = function (onConfirm, onCancel) {
sweetalert2_all_default().fire(this.mergeArg(GM_getValue("unClose")
? SwalConfig.genUnfinish2
: SwalConfig.genUnfinish)).then(function (result) {
if (result.isConfirmed)
onConfirm();
else if (result.dismiss === (sweetalert2_all_default()).DismissReason.cancel)
onCancel();
});
};
// 生成秒传, 未选择任何文件的提示
Swalbase.prototype.selectNoFileWarning = function () {
sweetalert2_all_default().fire(this.mergeArg(SwalConfig.selectNoFileWarning));
};
// 更新信息页
Swalbase.prototype.updateInfo = function (onConfirm) {
sweetalert2_all_default().fire(this.mergeArg(SwalConfig.updateInfo)).then(function (result) {
if (result.isConfirmed)
onConfirm();
});
};
// 以下的方法都是任务操作逻辑, 不是弹窗逻辑
Swalbase.prototype.saveFileWork = function () {
var _this = this;
this.rapiduploadTask.onFinish = function () { return _this.finishView(false); };
this.rapiduploadTask.onProcess = function (i, fileInfoList) {
sweetalert2_all_default().getHtmlContainer().querySelector("file_num").textContent = i + 1 + " / " + fileInfoList.length;
};
this.rapiduploadTask.start(); // 开始转存任务
};
Swalbase.prototype.genFileWork = function (isUnfinish, isGenView) {
var _this = this;
if (this.generatebdlinkTask.isSharePage)
this.generatebdlinkTask.selectList = getShareFileList();
else if (!isGenView)
this.generatebdlinkTask.selectList = getSelectedFileList();
if (
// 未选择文件 + 无未完成的生成任务 + 不在生成页 -> 弹出未选择生成文件的警告弹出
!this.generatebdlinkTask.selectList.length &&
!isGenView &&
!isUnfinish) {
this.selectNoFileWarning();
return;
}
this.generatebdlinkTask.onProcess = function (i, fileInfoList) {
sweetalert2_all_default().getHtmlContainer().querySelector("file_num").textContent = i + 1 + " / " + fileInfoList.length;
sweetalert2_all_default().getHtmlContainer().querySelector("gen_prog").textContent = "0%";
};
this.generatebdlinkTask.onProgress = function (e, text) {
if (text === void 0) { text = ""; }
if (text) {
// 显示自定义文本
sweetalert2_all_default().getHtmlContainer().querySelector("gen_prog").textContent = text;
return;
}
if (!e || typeof e.total !== "number")
return; // 参数数据不正确 跳过
sweetalert2_all_default().getHtmlContainer().querySelector("gen_prog").textContent = ((e.loaded / e.total) *
100).toFixed() + "%";
};
if (this.generatebdlinkTask.isSharePage) {
this.generatebdlinkTask.onHasNoDir = function () {
_this.processView(true);
_this.generatebdlinkTask.scanShareFile(0);
};
}
else {
this.generatebdlinkTask.onHasNoDir = function () {
_this.processView(true);
_this.generatebdlinkTask.generateBdlink(0);
};
this.generatebdlinkTask.onHasDir = function () { return _this.checkRecursive(); };
}
this.generatebdlinkTask.onFinish = function () { return _this.finishView(true); };
if (!isUnfinish && !isGenView)
this.generatebdlinkTask.start(); // 执行新任务初始化
};
Swalbase.prototype.checkUnfinish = function () {
var _this = this;
if (GM_getValue("unfinish")) {
this.genUnfinish(function () {
_this.processView(true);
_this.genFileWork(true, false);
var unfinishInfo = GM_getValue("unfinish");
_this.generatebdlinkTask.fileInfoList = unfinishInfo.file_info_list;
unfinishInfo.isCheckMd5
? _this.generatebdlinkTask.checkMd5(unfinishInfo.file_id)
: _this.generatebdlinkTask.generateBdlink(unfinishInfo.file_id);
}, // 确认继续未完成任务
function () {
GM_deleteValue("unfinish");
_this.genFileWork(false, false);
} // 不继续未完成任务, 清除数据, 开启新任务
);
}
else {
this.genFileWork(false, false);
} // 没有未完成任务, 直接开启新任务
};
// 添加 "打开目录" 按钮
Swalbase.prototype.addOpenDirBtn = function () {
if (this.rapiduploadTask.isDefaultPath)
return; // 转存路径留空, 跳出
var _dir = (this.rapiduploadTask.savePath || "").replace(/\\/$/, ""); // 去除路径结尾的"/"
if (_dir.charAt(0) !== "/")
_dir = "/" + _dir; // 补齐路径开头的"/"
var cBtn = sweetalert2_all_default().getConfirmButton();
var btn = cBtn.cloneNode();
btn.textContent = "打开目录";
btn.style.backgroundColor = "#ecae3c";
var nowPath = location.href.match(/(path=(.+?))(?:&|$)/);
btn.onclick = function () {
if (nowPath) {
location.href = location.href.replace(
// 仅替换path参数, 不修改其他参数
nowPath[1], "path=" + encodeURIComponent(_dir));
}
else {
var connectChar = location.href.includes("?") ? "&" : "?"; // 确定参数的连接符
location.href += connectChar + "path=" + encodeURIComponent(_dir);
} // 没有找到path参数, 直接添加
sweetalert2_all_default().close();
};
if ((nowPath ? nowPath[2] : "%2F") != encodeURIComponent(_dir))
// 当前已在转存目录时不添加按钮
cBtn.before(btn);
};
return Swalbase;
}());
/* harmony default export */ const swalBase = (Swalbase);
;// CONCATENATED MODULE: ./src/common/ajax.tsx
/*
* @Author: mengzonefire
* @Date: 2021-08-27 14:48:24
* @LastEditTime: 2023-02-14 04:10:09
* @LastEditors: mengzonefire
* @Description: 自封装JQ ajax方法
*/
var ajax_assign = (undefined && undefined.__assign) || function () {
ajax_assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return ajax_assign.apply(this, arguments);
};
function ajax(config, callback, failback) {
GM_xmlhttpRequest(ajax_assign(ajax_assign({}, config), { onload: function (r) {
// console.log(r); // debug
if (Math.floor(r.status / 100) === 2) {
console.info("%s version: %s 接口返回: %s", TAG, version, JSON.stringify(r.response)); // user debug
callback(r);
}
else
failback(r.status);
}, onerror: function () {
failback(ajaxError);
} }));
}
// EXTERNAL MODULE: ./node_modules/spark-md5/spark-md5.js
var spark_md5 = __webpack_require__(322);
var spark_md5_default = /*#__PURE__*/__webpack_require__.n(spark_md5);
;// CONCATENATED MODULE: ./src/baidu/common/rapiduploadTask.tsx
/*
* @Author: mengzonefire
* @Date: 2021-08-25 01:30:29
* @LastEditTime: 2023-05-04 18:09:10
* @LastEditors: mengzonefire
* @Description: 百度网盘 秒传转存任务实现
*/
var RapiduploadTask = /** @class */ (function () {
function RapiduploadTask() {
}
RapiduploadTask.prototype.reset = function () {
this.bdstoken = getBdstoken();
console.log("bdstoken\\u72B6\\u6001: " + (this.bdstoken ? "获取成功" : "获取失败")); // debug
this.fileInfoList = [];
this.savePath = "";
this.isDefaultPath = false;
this.onFinish = function () { };
this.onProcess = function () { };
};
RapiduploadTask.prototype.start = function () {
this.saveFileV2(0);
};
/**
* @description: 转存秒传 接口2
* @param {number} i
*/
RapiduploadTask.prototype.saveFileV2 = function (i) {
var _this = this;
if (i >= this.fileInfoList.length) {
this.onFinish(this.fileInfoList);
return;
}
this.onProcess(i, this.fileInfoList);
var file = this.fileInfoList[i];
// 文件名为空
if (file.path === "/") {
file.errno = -7;
this.saveFileV2(i + 1);
return;
}
var onFailed = function (statusCode) {
file.errno = statusCode;
_this.saveFileV2(i + 1);
};
createFileV2.call(this, file, function (data) {
data = data.response;
file.errno = 2 === data.errno ? 114 : data.errno;
file.errno = 31190 === file.errno ? 404 : file.errno;
_this.saveFileV2(i + 1);
}, onFailed);
// precreateFileV2.call(
// this,
// file,
// (data: any) => {
// data = data.response;
// if (0 === data.errno) {
// if (0 === data.block_list.length) {
// this.createFileV2(
// file,
// (data) => {
// data = data.response;
// file.errno = 2 === data.errno ? 114 : data.errno;
// file.errno = 31190 === file.errno ? 404 : file.errno;
// this.saveFileV2(i + 1);
// },
// onFailed
// );
// } else {
// file.errno = 404;
// this.saveFileV2(i + 1);
// }
// } else {
// file.errno = data.errno;
// this.saveFileV2(i + 1);
// }
// },
// onFailed
// );
};
return RapiduploadTask;
}());
/* harmony default export */ const rapiduploadTask = (RapiduploadTask);
// 此接口测试结果如下: 错误md5->返回"errno": 31190, 正确md5+错误size->返回"errno": 2
// 此外, 即使md5和size均正确, 连续请求时依旧有小概率返回"errno": 2, 故建议加入retry策略
function createFileV2(file, onResponsed, onFailed, retry, isGen) {
var _this = this;
if (retry === void 0) { retry = 0; }
if (isGen === void 0) { isGen = false; }
ajax({
url: "" + create_url + (this.bdstoken ? "&bdstoken=" + this.bdstoken : ""),
method: "POST",
responseType: "json",
data: convertData({
block_list: JSON.stringify([
isGen ? file.md5.toUpperCase() : file.md5.toLowerCase(),
]),
path: isGen
? testPath
: this.savePath + file.path.replace(illegalPathPattern, "_"),
size: file.size,
isdir: 0,
rtype: isGen ? 3 : 0,
is_revision: isGen ? 1 : 0, // is_revision=0时, rtype=3会不生效 (会依旧返回重名报错), is_revision=1时则等同rtype=3效果
}),
}, function (data) {
// console.log(data.response); // debug
if (31039 === data.response.errno && 31039 != file.errno && !isGen) {
file.errno = 31039;
file.path = suffixChange(file.path);
createFileV2.call(_this, file, onResponsed, onFailed, retry, isGen);
}
else if (2 === data.response.errno && retry < retryMax_apiV2) {
// console.log(`转存接口错误, 重试${retry + 1}次: ${file.path}`); // debug
createFileV2.call(_this, file, onResponsed, onFailed, ++retry, isGen);
}
else
onResponsed(data);
}, onFailed);
}
// 此接口测试结果如下: 错误md5->返回block_list: [0], 正确md5+正确/错误size->返回block_list: []
// 23.4.24测试发现此接口也不稳定, 有效md5也有20-30%概率返回block_list: [0], 建议加入retry策略
// 23.4.25测试发现此接口反复横跳, 今天又全部返回block_list: [0], 垃圾, 我直接弃用
// export function precreateFileV2(
// file: FileInfo,
// onResponsed: (data: any) => void,
// onFailed: (statusCode: number) => void,
// retry: number = 0
// ): void {
// ajax(
// {
// url: `${precreate_url}${this.bdstoken && "&bdstoken=" + this.bdstoken}`, // bdstoken参数不能放在data里, 否则无效
// method: "POST",
// responseType: "json",
// data: convertData({
// block_list: JSON.stringify([file.md5.toLowerCase()]),
// path: this.savePath + file.path.replace(illegalPathPattern, "_"),
// size: file.size,
// isdir: 0,
// autoinit: 1,
// }),
// },
// (data) => {
// let _data = data.response;
// if (0 === _data.errno) {
// if (0 != _data.block_list.length && retry < retryMax_apiV2)
// precreateFileV2.call(this, file, onResponsed, onFailed, ++retry);
// else onResponsed(data);
// } else onResponsed(data);
// },
// onFailed
// );
// }
;// CONCATENATED MODULE: ./src/baidu/common/generatebdlinkTask.tsx
/*
* @Author: mengzonefire
* @Date: 2021-08-25 01:31:01
* @LastEditTime: 2023-05-15 16:50:55
* @LastEditors: mengzonefire
* @Description: 百度网盘 秒传生成任务实现
*/
// import { createFileV2 } from "./rapiduploadTask";
// 普通生成:
var GeneratebdlinkTask = /** @class */ (function () {
function GeneratebdlinkTask() {
}
GeneratebdlinkTask.prototype.reset = function () {
this.isGenView = false;
this.isSharePage = false;
this.isFast =
GM_getValue("fast-generate") === undefined
? true
: GM_getValue("fast-generate");
this.recursive = false;
this.savePath = "";
this.bdstoken = getBdstoken(); // 此处bdstoken不可删除, 会在下方createFileV2方法调用
this.dirList = [];
this.selectList = [];
this.fileInfoList = [];
this.onFinish = function () { };
this.onProcess = function () { };
this.onProgress = function () { };
this.onHasDir = function () { };
this.onHasNoDir = function () { };
};
/**
* @description: 执行新任务的初始化步骤 扫描选择的文件列表
*/
GeneratebdlinkTask.prototype.start = function () {
if (this.isSharePage) {
this.logid = getLogid();
this.surl = getSurl();
if (!this.surl) {
showAlert("surl\\u83B7\\u53D6\\u5931\\u8D25: " + location.href + ", \\u8BF7\\u524D\\u5F80\\u811A\\u672C\\u9875\\u53CD\\u9988:\\n" + homePage);
return;
}
this.parseShareFileList();
this.onHasNoDir();
}
else {
this.parseMainFileList();
if (this.dirList.length)
this.onHasDir();
else
this.onHasNoDir();
}
};
GeneratebdlinkTask.prototype.scanShareFile = function (i, page) {
var _this = this;
if (page === void 0) { page = 1; }
if (i >= this.dirList.length) {
this.generateBdlink(0);
return;
}
this.onProgress(false, "\\u6B63\\u5728\\u83B7\\u53D6\\u6587\\u4EF6\\u5217\\u8868, \\u7B2C" + (i + 1) + "\\u4E2A");
ajax({
url: sharelist_url + "&dir=" + encodeURIComponent(this.dirList[i]) + "&logid=" + this.logid + "&shareid=" + unsafeWindow.yunData.shareid + "&uk=" + unsafeWindow.yunData.share_uk + "&page=" + page,
method: "GET",
responseType: "json",
}, function (data) {
data = data.response;
if (!data.errno) {
if (!data.list.length)
_this.scanShareFile(i + 1);
// 返回列表为空, 即此文件夹文件全部扫描完成
else {
_this.parseShareFileList(data.list);
_this.scanShareFile(i, page + 1); // 下一页
}
}
else {
_this.fileInfoList.push({
path: _this.dirList[i],
isdir: 1,
errno: data.errno,
}); // list接口访问失败, 添加失败信息
_this.scanShareFile(i + 1);
}
}, function (statusCode) {
_this.fileInfoList.push({
path: _this.dirList[i],
isdir: 1,
errno: statusCode,
});
_this.scanShareFile(i + 1);
});
};
/**
* @description: 选择的列表包含文件夹, 获取文件夹下的子文件
* @param {number} i 条目index
* @param {number} start 列表接口检索起点(即翻页参数)
*/
GeneratebdlinkTask.prototype.scanFile = function (i, start) {
var _this = this;
if (start === void 0) { start = 0; }
if (i >= this.dirList.length) {
this.generateBdlink(0);
return;
}
ajax({
url: "" + list_url + encodeURIComponent(this.dirList[i]) + "&recursion=" + (this.recursive ? 1 : 0) + "&start=" + start,
method: "GET",
responseType: "json",
}, // list接口自带递归参数recursion
function (data) {
data = data.response;
if (!data.errno) {
if (!data.list.length)
_this.scanFile(i + 1); // 返回列表为空, 即此文件夹文件全部扫描完成
else {
data.list.forEach(function (item) {
item.isdir ||
_this.fileInfoList.push({
path: item.path,
size: item.size,
fs_id: item.fs_id,
md5: _this.isFast ? decryptMd5(item.md5.toLowerCase()) : "",
md5s: "",
}); // 筛选文件(isdir=0)
});
_this.scanFile(i, start + listLimit); // 从下一个起点继续检索列表
}
}
else {
_this.fileInfoList.push({
path: _this.dirList[i],
isdir: 1,
errno: data.errno,
}); // list接口访问失败, 添加失败信息
_this.scanFile(i + 1);
}
}, function (statusCode) {
_this.fileInfoList.push({
path: _this.dirList[i],
isdir: 1,
errno: statusCode,
});
_this.scanFile(i + 1);
});
};
/**
* @description: 顺序执行生成任务
* @param {number} i
*/
GeneratebdlinkTask.prototype.generateBdlink = function (i) {
// 保存任务进度数据, 分享页生成不保存
if (!this.isSharePage)
GM_setValue("unfinish", {
file_info_list: this.fileInfoList,
file_id: i,
});
// 生成完成
if (i >= this.fileInfoList.length) {
if (this.isFast)
this.checkMd5(0); // 已开启 "极速生成", 执行md5检查
else
this.onFinish(this.fileInfoList);
return;
}
// 未开启 "极速生成", 刷新弹窗内的任务进度
if (!this.isFast)
this.onProcess(i, this.fileInfoList);
var file = this.fileInfoList[i];
// 跳过扫描失败的目录路径
if (file.errno && file.isdir) {
this.generateBdlink(i + 1);
return;
}
// 已开启 "极速生成" 且已获取到md5, 跳过普通生成步骤
if (this.isFast && file.md5)
this.generateBdlink(i + 1);
// 普通生成步骤
else
this.isSharePage ? this.getShareDlink(i) : this.getDlink(i);
};
/**
* @description: 获取文件信息: size, md5(可能错误), fs_id
* @param {number} i
*/
GeneratebdlinkTask.prototype.getFileInfo = function (i) {
var _this = this;
var file = this.fileInfoList[i];
ajax({
url: meta_url + encodeURIComponent(file.path),
responseType: "json",
method: "GET",
}, function (data) {
data = data.response;
if (!data.error_code) {
if (data.list[0].isdir) {
console.log(1111);
file.isdir = 1;
file.errno = 900;
_this.generateBdlink(i + 1);
return;
}
file.size = data.list[0].size;
file.fs_id = data.list[0].fs_id;
// 已开启极速生成, 直接取meta内的md5
file.md5 = _this.isFast
? decryptMd5(data.list[0].md5.toLowerCase())
: "";
file.md5s = "";
_this.getDlink(i);
}
else {
file.errno = data.error_code;
_this.generateBdlink(i + 1);
}
}, function (statusCode) {
file.errno = statusCode === 404 ? 909 : statusCode;
_this.generateBdlink(i + 1);
});
};
/**
* @description: 获取分享页的文件dlink(下载直链)
* @param {number} i
*/
GeneratebdlinkTask.prototype.getShareDlink = function (i) {
var _this = this;
var sign, timestamp, file = this.fileInfoList[i], onFailed = function (errno) {
file.errno = errno;
_this.checkMd5(i + 1);
// md5为空只在分享单个文件时出现, 故无需考虑获取多文件md5(跳转generateBdlink), 直接跳转checkMd5即可
};
function getTplconfig(file) {
var _this = this;
ajax({
url: tpl_url + "&surl=" + this.surl + "&logid=" + this.logid,
responseType: "json",
method: "GET",
}, function (data) {
data = data.response;
// 请求正常
if (!data.errno) {
sign = data.data.sign;
timestamp = data.data.timestamp;
getDlink.call(_this, file);
return;
}
// 请求报错
onFailed(data.errno);
}, onFailed);
}
function getDlink(file) {
var _this = this;
ajax({
url: sharedownload_url + "&sign=" + sign + "×tamp=" + timestamp,
responseType: "json",
method: "POST",
data: convertData({
extra: getExtra(),
logid: this.logid,
fid_list: JSON.stringify([file.fs_id]),
primaryid: unsafeWindow.yunData.shareid,
uk: unsafeWindow.yunData.share_uk,
product: "share",
encrypt: 0,
}),
}, function (data) {
data = data.response;
// 请求正常
if (!data.errno) {
_this.downloadFileData(i, data.list[0].dlink);
return;
}
// 请求报错
onFailed(data.errno);
}, onFailed);
}
getTplconfig.call(this, file);
};
/**
* @description: 获取文件dlink(下载直链)
* @param {number} i
*/
GeneratebdlinkTask.prototype.getDlink = function (i) {
var _this = this;
var file = this.fileInfoList[i];
// 使用生成页时仅有path没有fs_id, 跳转到获取fs_id
if (!file.fs_id) {
this.getFileInfo(i);
return;
}
ajax({
url: meta_url2 + JSON.stringify([String(file.fs_id)]),
responseType: "json",
method: "GET",
headers: { "User-Agent": UA },
}, function (data) {
data = data.response;
// 请求正常
if (!data.errno) {
_this.downloadFileData(i, data.info[0].dlink);
return;
}
// 请求报错
file.errno = data.errno;
_this.isFast ? _this.checkMd5(i + 1) : _this.generateBdlink(i + 1);
}, function (statusCode) {
file.errno = statusCode;
_this.isFast ? _this.checkMd5(i + 1) : _this.generateBdlink(i + 1);
});
};
/**
* @description: 调用下载直链
* @param {number} i
* @param {string} dlink
*/
GeneratebdlinkTask.prototype.downloadFileData = function (i, dlink) {
var _this = this;
var dlSize, file = this.fileInfoList[i];
if (this.isFast)
dlSize = 1; // "极速下载" 不需要生成slice-md5, 故无需下载文件数据
else
dlSize = file.size < 262144 ? 1 : 262143; //slice-md5: 文件前256KiB的md5, size<256KiB则直接取md5即可, 无需下载文件数据
ajax({
url: dlink,
method: "GET",
responseType: "arraybuffer",
headers: {
Range: "bytes=0-" + dlSize,
"User-Agent": UA,
},
onprogress: this.isFast ? function () { } : this.onProgress,
}, function (data) {
if (!_this.isFast)
_this.onProgress({ loaded: 100, total: 100 }); // 100%
_this.parseDownloadData(i, data);
}, function (statusCode) {
if (statusCode === 404)
file.errno = 909;
else
file.errno = statusCode;
_this.isFast ? _this.checkMd5(i + 1) : _this.generateBdlink(i + 1);
});
};
/**
* @description: 解析直链请求返回的数据
* @param {number} i
* @param {any} data
*/
GeneratebdlinkTask.prototype.parseDownloadData = function (i, data) {
var _this = this;
var file = this.fileInfoList[i];
console.log("dl_url: " + data.finalUrl); // debug
// 下载直链重定向到此域名, 判定为文件和谐
if (data.finalUrl.includes("issuecdn.baidupcs.com")) {
file.errno = 1919;
this.isFast ? this.checkMd5(i + 1) : this.generateBdlink(i + 1);
return;
}
// 从下载接口获取md5, 此步骤可确保获取到正确md5
var fileMd5 = data.responseHeaders.match(/content-md5: ([\\da-f]{32})/i);
if (fileMd5)
file.md5 = fileMd5[1].toLowerCase();
else if (file.size <= 3900000000 && !file.retry_996 && !this.isSharePage) {
// 默认下载接口未拿到md5, 尝试使用旧下载接口, 旧接口请求文件size大于3.9G会返回403
// 分享页的生成任务不要调用旧接口
file.retry_996 = true;
this.downloadFileData(i, pcs_url + ("&path=" + encodeURIComponent(file.path)));
return;
}
else {
// 两个下载接口均未拿到md5, 失败跳出
file.errno = 996;
this.isFast ? this.checkMd5(i + 1) : this.generateBdlink(i + 1);
return;
}
// 获取md5s, "极速生成" 跳过此步
if (!this.isFast) {
if (file.size < 262144)
file.md5s = file.md5; // 此时md5s=md5
else {
// 计算md5s
var spark = new (spark_md5_default()).ArrayBuffer();
spark.append(data.response);
var sliceMd5 = spark.end();
file.md5s = sliceMd5;
}
var interval = this.fileInfoList.length > 1 ? 2000 : 1000;
setTimeout(function () {
_this.generateBdlink(i + 1);
}, interval);
}
else
this.checkMd5(i + 1);
};
/**
* @description: "极速生成" 可能得到错误md5, 故执行验证步骤, 若验证不通过则执行普通生成
* @param {number} i
*/
GeneratebdlinkTask.prototype.checkMd5 = function (i) {
var _this = this;
if (i >= this.fileInfoList.length) {
this.onFinish(this.fileInfoList);
return;
}
var file = this.fileInfoList[i];
// 跳过扫描失败的目录路径
if (file.errno && file.isdir) {
this.checkMd5(i + 1);
return;
}
this.onProcess(i, this.fileInfoList);
this.onProgress(false, "极速生成中...");
// this.isSharePage ? this.getShareDlink(i) : this.getDlink(i);
// 23.4.27: 错误md5在文件上传者账号使用此接口正常转存, 在其他账号则报错#404(#31190), 导致生成秒传完全无法验证, 故弃用meta内的md5
// 23.5.4: 发现错误md5只要改成大写, 在上传者账号就能正常返回#31190, 而正确md5则大小写都能正常转存, 故重新启用此验证过程
// 主要是因为频繁请求直链接口获取正确md5会导致#9019错误(即账号被限制), 对大批量生成秒传有很大影响, 极速生成功能使用此验证则可以节约请求以避免此问题
// 23.5.15: 错误md5问题的原理: 通过网页端上传大文件(分片上传)发现, list接口的错误md5仅在上传完成后24h内有效, 且多次上传相同的文件时, 得到的错误md5也相同
// 故猜测此错误md5实际对应block_list(分片md5列表), 用于在服务端计算出文件完整md5前临时代替使用
createFileV2.call(this, file, function (data) {
data = data.response;
// errno=-10即网盘容量已满, 由于31190(秒传无效)的优先级高于-10, 所以验证md5时此错误可视为验证成功
if ([0, -10].includes(data.errno))
_this.checkMd5(i + 1); // md5验证成功
else if (31190 === data.errno) {
// md5验证失败, 执行普通生成, 仅在此处保存任务进度, 生成页不保存进度
if (!_this.isSharePage)
GM_setValue("unfinish", {
file_info_list: _this.fileInfoList,
file_id: i,
isCheckMd5: true,
});
_this.isSharePage ? _this.getShareDlink(i) : _this.getDlink(i);
}
else {
// 接口访问失败
file.errno = data.errno;
_this.checkMd5(i + 1);
}
}, function (statusCode) {
file.errno = statusCode;
_this.checkMd5(i + 1);
}, 0, true);
};
/**
* @description: 用于解析度盘主页的文件列表数据
*/
GeneratebdlinkTask.prototype.parseMainFileList = function () {
for (var _i = 0, _a = this.selectList; _i < _a.length; _i++) {
var item = _a[_i];
if (item.isdir)
this.dirList.push(item.path);
else
this.fileInfoList.push({
path: item.path,
size: item.size,
fs_id: item.fs_id,
// 已开启极速生成, 直接取meta内的md5
md5: this.isFast ? decryptMd5(item.md5.toLowerCase()) : "",
md5s: "",
});
}
};
/**
* @description: 用于解析分享页的文件列表数据
*/
GeneratebdlinkTask.prototype.parseShareFileList = function (list) {
if (list === void 0) { list = this.selectList; }
for (var _i = 0, list_1 = list; _i < list_1.length; _i++) {
var item = list_1[_i];
var path = void 0;
if ("app_id" in item)
path = item.isdir ? item.path : item.server_filename;
else
path = item.path;
if ("/" !== path.charAt(0))
path = "/" + path; // 补齐路径开头的斜杠
if (item.isdir)
this.dirList.push(path);
else
this.fileInfoList.push({
path: path,
size: item.size,
fs_id: item.fs_id,
md5: item.md5 && decryptMd5(item.md5.toLowerCase()),
md5s: "",
});
}
};
return GeneratebdlinkTask;
}());
/* harmony default export */ const generatebdlinkTask = (GeneratebdlinkTask);
;// CONCATENATED MODULE: ./src/baidu/common/const.tsx
/*
* @Author: mengzonefire
* @Date: 2022-10-20 10:36:43
* @LastEditTime: 2023-05-04 12:43:06
* @LastEditors: mengzonefire
* @Description: 存放各种全局常量对象
*/
var host = location.host;
var listLimit = 10000;
var syncPathPrefix = "/_pcs_.workspace";
var retryMax_apiV2 = 4; // v2转存接口的最大重试次数
var create_url = "https://" + host + "/api/create";
var precreate_url = "https://" + host + "/api/precreate";
var list_url = "https://" + host + "/rest/2.0/xpan/multimedia?method=listall&order=name&limit=" + listLimit + "&path=";
var meta_url = "<https://pcs.baidu.com/rest/2.0/pcs/file?app_id=778750&method=meta&path=>";
var meta_url2 = "https://" + host + "/api/filemetas?dlink=1&fsids=";
var tpl_url = "https://" + host + "/share/tplconfig?fields=sign,timestamp&channel=chunlei&web=1&app_id=250528&clienttype=0";
var sharedownload_url = "https://" + host + "/api/sharedownload?channel=chunlei&clienttype=12&web=1&app_id=250528";
var sharelist_url = "https://" + host + "/share/list?showempty=0&num=" + listLimit + "&channel=chunlei&web=1&app_id=250528&clienttype=0";
var syncdownload_url = "https://" + host + "/api/download";
var testPath = "/apps/生成秒传测试文件.mengzonefire";
var pcs_url = "<https://pcs.baidu.com/rest/2.0/pcs/file?app_id=778750&method=download>";
var illegalPathPattern = /[\\\\":*?<>|]/g; // 匹配路径中的非法字符
var getBdstoken; // 获取bdstoken的实现
function setGetBdstoken(func) {
getBdstoken = func;
}
var refreshList; // 刷新文件列表的实现
function setRefreshList(func) {
refreshList = func;
}
var getSelectedFileList; // 获取选中的文件列表的实现
function setGetSelectedFileList(func) {
getSelectedFileList = func;
}
var swalInstance = new swalBase(new rapiduploadTask(), new generatebdlinkTask());
function baiduErrno(errno) {
switch (errno) {
case 31045:
case -6:
return "\\u8BA4\\u8BC1\\u5931\\u8D25(\\u8BF7\\u770B\\u6587\\u6863:<a href=\\"" + doc.shareDoc + "#\\u8BA4\\u8BC1\\u5931\\u8D25-6\\" " + linkStyle + ">\\u8F7D\\u70B91</a> <a href=\\"" + doc2.shareDoc + "#\\u8BA4\\u8BC1\\u5931\\u8D25-6\\" " + linkStyle + ">\\u8F7D\\u70B92</a>)";
case -7:
return "\\u8F6C\\u5B58\\u8DEF\\u5F84\\u542B\\u6709\\u975E\\u6CD5\\u5B57\\u7B26(\\u8BF7\\u770B\\u6587\\u6863:<a href=\\"" + doc.shareDoc + "#\\u8F6C\\u5B58\\u8DEF\\u5F84\\u542B\\u6709\\u975E\\u6CD5\\u5B57\\u7B26-7\\" " + linkStyle + ">\\u8F7D\\u70B91</a> <a href=\\"" + doc2.shareDoc + "#\\u8F6C\\u5B58\\u8DEF\\u5F84\\u542B\\u6709\\u975E\\u6CD5\\u5B57\\u7B26-7\\" " + linkStyle + ">\\u8F7D\\u70B92</a>)";
case -8:
return "路径下存在同名文件";
case -9:
return "验证已过期, 请刷新页面";
case 400:
return "\\u8BF7\\u6C42\\u9519\\u8BEF(\\u8BF7\\u770B\\u6587\\u6863:<a href=\\"" + doc.shareDoc + "#\\u8BF7\\u6C42\\u9519\\u8BEF-400\\" " + linkStyle + ">\\u8F7D\\u70B91</a> <a href=\\"" + doc2.shareDoc + "#\\u8BF7\\u6C42\\u9519\\u8BEF-400\\" " + linkStyle + ">\\u8F7D\\u70B92</a>)";
case 9019:
case 403:
return "\\u63A5\\u53E3\\u9650\\u5236\\u8BBF\\u95EE(\\u8BF7\\u770B\\u6587\\u6863:<a href=\\"" + doc.shareDoc + "#\\u63A5\\u53E3\\u9650\\u5236\\u8BBF\\u95EE-403\\" " + linkStyle + ">\\u8F7D\\u70B91</a> <a href=\\"" + doc2.shareDoc + "#\\u63A5\\u53E3\\u9650\\u5236\\u8BBF\\u95EE-403\\" " + linkStyle + ">\\u8F7D\\u70B92</a>)";
case 404:
return "\\u79D2\\u4F20\\u672A\\u751F\\u6548(\\u8BF7\\u770B\\u6587\\u6863:<a href=\\"" + doc.shareDoc + "#\\u79D2\\u4F20\\u672A\\u751F\\u6548-404\\" " + linkStyle + ">\\u8F7D\\u70B91</a> <a href=\\"" + doc2.shareDoc + "#\\u79D2\\u4F20\\u672A\\u751F\\u6548-404\\" " + linkStyle + ">\\u8F7D\\u70B92</a>)";
case 114:
return "\\u8F6C\\u5B58\\u5931\\u8D25-v2\\u63A5\\u53E3(\\u8BF7\\u770B\\u6587\\u6863:<a href=\\"" + doc.shareDoc + "#\\u8F6C\\u5B58\\u5931\\u8D25-v2\\u63A5\\u53E3-114\\" " + linkStyle + ">\\u8F7D\\u70B91</a> <a href=\\"" + doc2.shareDoc + "#\\u8F6C\\u5B58\\u5931\\u8D25-v2\\u63A5\\u53E3-114\\" " + linkStyle + ">\\u8F7D\\u70B92</a>)";
case 514:
return "\\u8BF7\\u6C42\\u5931\\u8D25(\\u8BF7\\u770B\\u6587\\u6863:<a href=\\"" + doc.shareDoc + "#\\u8BF7\\u6C42\\u5931\\u8D25-514\\" " + linkStyle + ">\\u8F7D\\u70B91</a> <a href=\\"" + doc2.shareDoc + "#\\u8BF7\\u6C42\\u5931\\u8D25-514\\" " + linkStyle + ">\\u8F7D\\u70B92</a>)";
case 1919:
return "\\u6587\\u4EF6\\u5DF2\\u88AB\\u548C\\u8C10(\\u8BF7\\u770B\\u6587\\u6863:<a href=\\"" + doc.shareDoc + "#\\u6587\\u4EF6\\u5DF2\\u88AB\\u548C\\u8C10-1919\\" " + linkStyle + ">\\u8F7D\\u70B91</a> <a href=\\"" + doc2.shareDoc + "#\\u6587\\u4EF6\\u5DF2\\u88AB\\u548C\\u8C10-1919\\" " + linkStyle + ">\\u8F7D\\u70B92</a>)";
case 996:
return "md5\\u83B7\\u53D6\\u5931\\u8D25(\\u8BF7\\u770B\\u6587\\u6863:<a href=\\"" + doc.shareDoc + "#md5-\\u83B7\\u53D6\\u5931\\u8D25-996\\" " + linkStyle + ">\\u8F7D\\u70B91</a> <a href=\\"" + doc2.shareDoc + "#md5-\\u83B7\\u53D6\\u5931\\u8D25-996\\" " + linkStyle + ">\\u8F7D\\u70B92</a>)";
case 2:
return "\\u8F6C\\u5B58\\u5931\\u8D25-v1\\u63A5\\u53E3(\\u8BF7\\u770B\\u6587\\u6863:<a href=\\"" + doc.shareDoc + "#\\u8F6C\\u5B58\\u5931\\u8D25-v1\\u63A5\\u53E3-2\\" " + linkStyle + ">\\u8F7D\\u70B91</a> <a href=\\"" + doc2.shareDoc + "#\\u8F6C\\u5B58\\u5931\\u8D25-v1\\u63A5\\u53E3-2\\" " + linkStyle + ">\\u8F7D\\u70B92</a>)";
case -10:
return "网盘容量已满";
case 500:
case 502:
case 503:
return "\\u670D\\u52A1\\u5668\\u9519\\u8BEF(\\u8BF7\\u770B\\u6587\\u6863:<a href=\\"" + doc.shareDoc + "#\\u670D\\u52A1\\u5668\\u9519\\u8BEF-50x\\" " + linkStyle + ">\\u8F7D\\u70B91</a> <a href=\\"" + doc2.shareDoc + "#\\u670D\\u52A1\\u5668\\u9519\\u8BEF-50x\\" " + linkStyle + ">\\u8F7D\\u70B92</a>)";
case 31066:
case 909:
return "路径不存在/云端文件已损坏";
case 900:
return "路径为文件夹, 不支持生成秒传";
case 31039:
return "\\u670D\\u52A1\\u5668\\u9519\\u8BEF(\\u8BF7\\u770B\\u6587\\u6863:<a href=\\"" + doc.shareDoc + "#\\u670D\\u52A1\\u5668\\u9519\\u8BEF-31039\\" " + linkStyle + ">\\u8F7D\\u70B91</a> <a href=\\"" + doc2.shareDoc + "#\\u670D\\u52A1\\u5668\\u9519\\u8BEF-31039\\" " + linkStyle + ">\\u8F7D\\u70B92</a>)";
case 110:
return "请先登录百度账号";
case 9013:
return "账号被限制, 尝试 更换账号 或 等待一段时间再重试";
default:
return "\\u672A\\u77E5\\u9519\\u8BEF(\\u8BF7\\u770B\\u6587\\u6863:<a href=\\"" + doc.shareDoc + "#\\u672A\\u77E5\\u9519\\u8BEF\\" " + linkStyle + ">\\u8F7D\\u70B91</a> <a href=\\"" + doc2.shareDoc + "#\\u672A\\u77E5\\u9519\\u8BEF\\" " + linkStyle + ">\\u8F7D\\u70B92</a>)";
}
} // 自定义百度api返回errno的报错
;// CONCATENATED MODULE: ./src/common/utils.tsx
/*
* @Author: mengzonefire
* @Date: 2021-08-22 04:01:11
* @LastEditTime: 2023-03-10 19:47:20
* @LastEditors: mengzonefire
* @Description: 存放工具函数
*/
var utils_awaiter = (undefined && undefined.__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 utils_generator = (undefined && undefined.__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 };
}
};
/**
* @description: 弹出一个文本提示框
* @param {string} text
*/
function showAlert(text) {
alert(TAG + ":\\n" + text);
}
/**
* @description: 解析文件信息, 返回转存结果列表html, 秒传链接, 失败文件个数, 成功的文件信息列表, 失败的文件信息列表
* @param {Array} fileInfoList 文件信息数据列表
*/
function parsefileInfo(fileInfoList) {
var bdcode = "";
var successInfo = "";
var failedInfo = "";
var successList = [];
var failList = [];
var failCodeDic = {};
fileInfoList.forEach(function (item) {
item.path = item.path.replace(syncPathPrefix, ""); // 移除同步页前缀
// 成功文件
if (0 === item.errno || undefined === item.errno) {
successInfo += "<p>" + item.path + "</p>";
bdcode += "" + item.md5 + (item.md5s && "#" + item.md5s) + "#" + item.size + "#" + item.path + "\\n";
successList.push(item);
}
// 失败文件
else {
failList.push(item);
if (String(item.errno) in failCodeDic)
failCodeDic[String(item.errno)].push(item);
else
failCodeDic[String(item.errno)] = [item];
}
});
var _loop_1 = function (failCode) {
var failBranchInfo = "";
var failBranchList = failCodeDic[failCode];
failBranchList.forEach(function (item) {
failBranchInfo += "<p>" + item.path + "</p>";
});
failedInfo += "<details class=\\"mzf_details mzf_details_branch\\"><summary><svg class=\\"mzf_arrow\\" width=\\"16\\" height=\\"7\\"><polyline points=\\"0,0 8,7 16,0\\"/></svg><b>" + baiduErrno(Number(failCode)) + "(#" + Number(failCode) + "):</b>" + copyFailBranchList + "</summary></details><div class=\\"mzf_content\\">" + failBranchInfo + "</div>";
};
for (var failCode in failCodeDic) {
_loop_1(failCode);
}
if (failedInfo)
failedInfo = "<details class=\\"mzf_details\\"><summary><svg class=\\"mzf_arrow\\" width=\\"16\\" height=\\"7\\"><polyline points=\\"0,0 8,7 16,0\\"/></svg><b>\\u5931\\u8D25\\u6587\\u4EF6\\u5217\\u8868(\\u70B9\\u8FD9\\u91CC\\u770B\\u5931\\u8D25\\u539F\\u56E0):</b>" + copyFailList + "</summary></details><div class=\\"mzf_content\\">" + failedInfo + "</div>";
if (successInfo)
successInfo = "<details class=\\"mzf_details\\"><summary><svg class=\\"mzf_arrow\\" width=\\"16\\" height=\\"7\\"><polyline points=\\"0,0 8,7 16,0\\"/></svg><b>\\u6210\\u529F\\u6587\\u4EF6\\u5217\\u8868(\\u70B9\\u51FB\\u5C55\\u5F00):</b>" + copySuccessList + "</summary></details><div class=\\"mzf_content\\">" + successInfo + "</div>";
bdcode = bdcode.trim();
return {
htmlInfo: successInfo && failedInfo
? successInfo + "<p><br /></p>" + failedInfo
: successInfo + failedInfo,
bdcode: bdcode,
successList: successList,
failList: failList,
};
}
/**
* @description: 获取分享页的文件列表
*/
function getShareFileList() {
var bdListInstance = unsafeWindow.require("system-core:context/context.js")
.instanceForSystem.list;
var selectList = bdListInstance.getSelected();
if (!selectList.length)
selectList = bdListInstance.getCurrentList();
return selectList;
}
/**
* @description: 获取选择的文件列表(旧版界面)
*/
function getSelectedFileListLegacy() {
return unsafeWindow
.require("system-core:context/context.js")
.instanceForSystem.list.getSelected();
}
/**
* @description: 获取选择的文件列表(新版界面)
* 我从这里抄的, 谢谢你: <https://greasyfork.org/zh-CN/scripts/436446>
*/
function getSelectedFileListNew() {
return document.querySelector(".nd-main-list, .nd-new-main-list").__vue__
.selectedList;
}
/**
* @description: 将data键值对转换为query字符串
* @param {any} data
* @return {string} query
*/
function convertData(data) {
var query = "";
for (var key in data)
query += "&" + key + "=" + encodeURIComponent(data[key]);
return query;
}
/**
* @description: 从剪贴板获取字符串数据
* @return {string} bdlink
*/
function parseClipboard() {
return utils_awaiter(this, void 0, void 0, function () {
var bdlink, error_1;
return utils_generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, navigator.clipboard.readText()];
case 1:
bdlink = _a.sent();
if (!DuParser.parse(bdlink).length)
return [2 /*return*/, ""];
return [2 /*return*/, bdlink];
case 2:
error_1 = _a.sent();
showAlert(appError.ClipboardPremissionErr);
return [2 /*return*/, ""];
case 3: return [2 /*return*/];
}
});
});
}
/**
* @description: 解密已加密的md5
* @param {string} md5 (加密)
* @return {string} md5 (解密)
*/
function decryptMd5(md5) {
if (!((parseInt(md5[9]) >= 0 && parseInt(md5[9]) <= 9) ||
(md5[9] >= "a" && md5[9] <= "f")))
return decrypt(md5);
else
return md5;
function decrypt(encryptMd5) {
var key = (encryptMd5[9].charCodeAt(0) - "g".charCodeAt(0)).toString(16);
var key2 = encryptMd5.slice(0, 9) + key + encryptMd5.slice(10);
var key3 = "";
for (var a = 0; a < key2.length; a++)
key3 += (parseInt(key2[a], 16) ^ (15 & a)).toString(16);
var md5 = key3.slice(8, 16) +
key3.slice(0, 8) +
key3.slice(24, 32) +
key3.slice(16, 24);
return md5;
}
}
/**
* @description: 用于解决#31039报错
* @param {string} path 原文件路径
* @return {string} 修改文件后缀的路径
*/
function suffixChange(path) {
var suffix = path.substring(path.lastIndexOf(".") + 1); // 获取后缀
return path.substring(0, path.length - suffix.length) + reverseStr(suffix);
}
/**
* @description: 逆转字符串大小写
* @param {string} str 输入字符串
* @return {string} 处理后的字符串
*/
function reverseStr(str) {
var newStr = "";
for (var i = 0; i < str.length; i++) {
var reverseChar = void 0;
if (str.charAt(i) >= "a")
reverseChar = str.charAt(i).toUpperCase();
else if (str.charAt(i) >= "A")
reverseChar = str.charAt(i).toLowerCase();
else
reverseChar = str.charAt(i);
newStr += reverseChar;
}
return newStr;
}
// 下方四个function用于分享页生成秒传
// 依旧是从这里抄的: <https://greasyfork.org/zh-CN/scripts/436446>
function getCookie(name) {
var arr = document.cookie.replace(/\\s/g, "").split(";");
for (var i = 0, l = arr.length; i < l; i++) {
var tempArr = arr[i].split("=");
if (tempArr[0] === name) {
return decodeURIComponent(tempArr[1]);
}
}
return "";
}
function getLogid() {
var ut = unsafeWindow.require("system-core:context/context.js")
.instanceForSystem.tools.baseService;
return ut.base64Encode(getCookie("BAIDUID"));
}
function getSurl() {
var reg = /(s\\/|surl=)([a-zA-Z0-9_-]+)/;
if (reg.test(location.href)) {
return location.href.match(reg)[2];
}
return "";
}
function getExtra() {
var seKey = decodeURIComponent(getCookie("BDCLND"));
return "{" + '"sekey":"' + seKey + '"' + "}";
}
;// CONCATENATED MODULE: ./src/baidu/newPage/loader.tsx
/*
* @Author: mengzonefire
* @Date: 2022-10-20 10:36:43
* @LastEditTime: 2023-02-14 03:53:02
* @LastEditors: mengzonefire
* @Description: 新版度盘界面loader入口: <https://pan.baidu.com/disk/main>
*/
var htmlTagNew = "div.nd-file-list-toolbar__actions"; // 新版界面秒传按钮的html父对象
var htmlTagNew2 = "div.wp-s-agile-tool-bar__header"; // 22.5.24: 新版界面新增的一个父对象
var htmlBtnRapidNew = // 新版界面秒传按钮的html元素
'<button id="bdlink_btn" class="mzf_new_btn"></i><span>秒传</span></button>';
var htmlBtnGenNew = // 新版界面秒传生成按钮的html元素
'<button id="gen_bdlink_btn" class="mzf_new_btn"></i><span>生成秒传</span></button>';
function installNew() {
console.info("%s version: %s DOM方式安装", TAG, version);
swalInstance.swalGlobalArgs = {
heightAuto: false,
scrollbarPadding: false,
}; // 添加swal参数以防止新版界面下的body样式突变
setRefreshList(function () {
document
.querySelector(".nd-main-list, .nd-new-main-list")
.__vue__.reloadList();
});
setGetSelectedFileList(getSelectedFileListNew);
setGetBdstoken(function () {
return document.querySelector(".nd-main-list, .nd-new-main-list").__vue__.yunData
.bdstoken;
});
$(document).on("click", "#bdlink_btn", function () {
swalInstance.inputView();
}); // 绑定转存秒传按钮事件
$(document).on("click", "#gen_bdlink_btn", function () {
swalInstance.generatebdlinkTask.reset();
swalInstance.checkUnfinish();
}); // 绑定生成秒传按钮事件
addBtn();
}
function addBtn() {
// 轮询添加按钮, 防止新版页面重复init时, 将按钮覆盖
var target = $(htmlTagNew);
if (!target.length)
target = $(htmlTagNew2);
if (target.length && !$("#bdlink_btn").length)
target.append(htmlBtnRapidNew, htmlBtnGenNew);
setTimeout(addBtn, 500);
}
;// CONCATENATED MODULE: ./src/baidu/legacyPage/loader.tsx
/*
* @Author: mengzonefire
* @Date: 2022-10-20 10:36:43
* @LastEditTime: 2022-12-24 10:57:23
* @LastEditors: mengzonefire
* @Description: 旧版度盘界面loader入口: <https://pan.baidu.com/disk/home?stayAtHome=true>
*/
var htmlTagLegacy = "div.tcuLAu"; // 旧版界面秒传按钮的html父对象
var htmlBtnRapidLegacy = // 旧版界面秒传按钮的html元素
'<a class="g-button g-button-blue" id="bdlink_btn" title="秒传链接" style="display: inline-block;""><span class="g-button-right"><em class="icon icon-disk" title="秒传链接提取"></em><span class="text" style="width: auto;">秒传链接</span></span></a>';
var htmlBtnGenLegacy = // 旧版界面秒传生成按钮的html元素
'<a class="g-button" id="gen_bdlink_btn"><span class="g-button-right"><em class="icon icon-share"></em><span class="text" style="width: auto;">生成秒传</span></span></a>';
function installLegacy() {
console.info("%s version: %s DOM方式安装", TAG, version);
setRefreshList(function () {
// 旧版界面, 调用原生方法刷新文件列表, 无需重新加载页面
unsafeWindow
.require("system-core:system/baseService/message/message.js")
.trigger("system-refresh");
});
setGetSelectedFileList(getSelectedFileListLegacy);
setGetBdstoken(function () { return unsafeWindow.locals.get("bdstoken"); });
loader_addBtn(); // DOM添加秒传按钮
addGenBtn(); // DOM添加生成按钮
$(document).on("click", "#bdlink_btn", function () {
swalInstance.inputView();
}); // 绑定秒传按钮事件
$(document).on("click", "#gen_bdlink_btn", function () {
swalInstance.generatebdlinkTask.reset();
swalInstance.checkUnfinish();
}); // 绑定生成按钮事件
}
function getSystemContext() {
return unsafeWindow.require("system-core:context/context.js")
.instanceForSystem;
}
function addGenBtn() {
var listTools = getSystemContext().Broker.getButtonBroker("listTools");
if (listTools && listTools.$box)
$(listTools.$box).children("div").after(htmlBtnGenLegacy);
else
setTimeout(addGenBtn, 300);
}
function loader_addBtn() {
if ($(htmlTagLegacy).length)
$(htmlTagLegacy).append(htmlBtnRapidLegacy);
else
setTimeout(loader_addBtn, 100);
}
;// CONCATENATED MODULE: ./src/baidu/syncPage/loader.tsx
/*
* @Author: mengzonefire
* @Date: 2022-12-12 10:58:59
* @LastEditTime: 2022-12-24 10:57:12
* @LastEditors: mengzonefire
* @Description: 同步空间loader入口: <https://pan.baidu.com/disk/synchronization#>
*/
var loader_htmlTagNew = "div.nd-btn-group > span";
var loader_htmlBtnRapidNew = '<button id="bdlink_btn" type="button" class="u-button is-round is-has-icon" style="background: #06a7ff;color: #fff;"><span><i class="iconfont icon-copy"></i><span class=" nd-file-list-toolbar-action-item-text">秒传</span></span></button>';
// const htmlBtnGenNew =
// '<button id="gen_bdlink_btn" type="button" class="u-button is-round is-has-icon" style="margin-left: 8px;background: #06a7ff;color: #fff;"><span><i class="iconfont icon-copy"></i><span class=" nd-file-list-toolbar-action-item-text">生成秒传</span></span></button>';
function installSync() {
console.info("%s version: %s DOM方式安装", TAG, version);
swalInstance.swalGlobalArgs = {
heightAuto: false,
scrollbarPadding: false,
};
setRefreshList(function () {
document
.querySelector(".nd-main-list, .nd-new-main-list")
.__vue__.reloadList();
});
setGetSelectedFileList(getSelectedFileListNew);
setGetBdstoken(function () {
return document.querySelector(".nd-main-list, .nd-new-main-list").__vue__.yunData
.bdstoken;
});
$(document).on("click", "#bdlink_btn", function () {
swalInstance.inputView();
}); // 绑定转存秒传按钮事件
$(document).on("click", "#gen_bdlink_btn", function () {
swalInstance.generatebdlinkTask.reset();
swalInstance.checkUnfinish();
}); // 绑定生成秒传按钮事件
syncPage_loader_addBtn();
}
function syncPage_loader_addBtn() {
// 轮询添加按钮, 防止新版页面重复init时, 将按钮覆盖
var target = $(loader_htmlTagNew);
if (target.length && !$("#bdlink_btn").length)
target.append(loader_htmlBtnRapidNew);
// target.append(htmlBtnRapidNew, htmlBtnGenNew);
// 同步页中的文件使用另一种的接口获取dlink, 故暂不添加生成功能
setTimeout(syncPage_loader_addBtn, 500);
}
;// CONCATENATED MODULE: ./src/baidu/sharePage/loader.tsx
/*
* @Author: mengzonefire
* @Date: 2022-12-12 10:57:58
* @LastEditTime: 2022-12-24 10:57:15
* @LastEditors: mengzonefire
* @Description: 文件分享页loader入口: <https://pan.baidu.com/s/xxx>
*/
var htmlBtnGenShare = // 分享页的秒传生成按钮html元素
'<a id="gen_bdlink_btn_sharePage" title="生成秒传" class="g-button g-button-blue-large" style="margin-right: 5px;margin-left: 5px;"> <span class="g-button-right"> <em class="icon icon-share" style="color:#ffffff" title="生成秒传"></em> <span class="text" style="width: auto;">生成秒传</span> </span> </a>';
var htmlTagSahre = "[node-type=qrCode]";
function installShare() {
console.info("%s version: %s DOM方式安装", TAG, version);
setGetBdstoken(function () { return unsafeWindow.locals.get("bdstoken"); });
sharePage_loader_addBtn();
$(document).on("click", "#gen_bdlink_btn_sharePage", function () {
swalInstance.generatebdlinkTask.reset();
swalInstance.generatebdlinkTask.isSharePage = true;
swalInstance.generatebdlinkTask.isFast = true; // 强制使用极速生成
swalInstance.genFileWork(false, false);
}); // 绑定生成按钮事件
}
function sharePage_loader_addBtn() {
if ($(htmlTagSahre).length)
$(htmlTagSahre).before(htmlBtnGenShare);
else
setTimeout(sharePage_loader_addBtn, 100);
}
;// CONCATENATED MODULE: ./src/baidu/loader.tsx
/*
* @Author: mengzonefire
* @Date: 2022-10-20 10:36:43
* @LastEditTime: 2023-04-05 07:30:42
* @LastEditors: mengzonefire
* @Description: 主函数入口
*/
function loaderBaidu() {
var load = function () {
if (locUrl.includes(baiduNewPage))
installNew();
else if (locUrl.includes(baiduSharePage))
installShare();
else if (locUrl.includes(baiduSyncPage))
installSync();
else
installLegacy();
// 进入页面后的弹窗任务
var bdlink = parseQueryLink(locUrl); // 解析url中的秒传链接
if (bdlink) {
// 解析到秒传链接, 弹出转存窗口
swalInstance.inputView(bdlink);
}
else if (!GM_getValue(updateInfoVer + "_no_first"))
// 检查是否首次运行, 若是则弹出更新信息窗口
swalInstance.updateInfo(function () {
GM_setValue(updateInfoVer + "_no_first", true);
});
// 预先绑定好按钮事件
$(document).on("click", "#mzf_kill_donate", function () {
GM_setValue(donateVer + "_kill_donate", true);
$("#mzf_donate").remove();
}); // 赞助提示 "不再显示" 按钮
$(document).on("click", "#mzf_kill_feedback", function () {
GM_setValue(feedbackVer + "_kill_feedback", true);
$("#mzf_feedback").remove();
}); // 反馈提示 "不再显示" 按钮
$(document).on("click", "#mzf_kill_referral", function () {
GM_setValue(referralVer + "_kill_referral", true);
$("#mzf_referral").remove();
}); // 网盘会员推广 "不再显示" 按钮
$(document).on("click", "#copy_fail_list", function (btn) {
var listText = "";
for (var _i = 0, _a = swalInstance.parseResult.failList; _i < _a.length; _i++) {
var item = _a[_i];
listText += item.path + "\\n";
}
GM_setClipboard(listText);
btn.target.innerText = "复制成功";
}); // 失败文件列表复制
$(document).on("click", "#copy_success_list", function (btn) {
var listText = "";
for (var _i = 0, _a = swalInstance.parseResult.successList; _i < _a.length; _i++) {
var item = _a[_i];
listText += item.path + "\\n";
}
GM_setClipboard(listText);
btn.target.innerText = "复制成功";
}); // 成功文件列表复制
$(document).on("click", "#copy_fail_branch_list", function (btn) {
var ele = $(btn.target);
GM_setClipboard(ele
.parents("details.mzf_details_branch")
.next()[0]
.innerText.replace(/\\n\\n/g, "\\n"));
btn.target.innerText = "复制成功";
}); // 失败文件分支列表复制
try {
// 添加油猴插件菜单按钮
GM_registerMenuCommand("🕮 版本信息", function () {
swalInstance.updateInfo(function () { });
});
GM_registerMenuCommand("⚙ 工具设置", function () {
swalInstance.settingView();
});
GM_registerMenuCommand("⚡生成秒传(输入文件路径)", function () {
swalInstance.genView();
});
}
catch (_) {
console.info("%s version: %s 插件菜单添加失败, 使用的插件不支持GM_registerMenuCommand", TAG, version);
}
};
// 绑定入口函数到dom事件
if (["interactive", "complete"].includes(document.readyState))
load();
else
window.addEventListener("DOMContentLoaded", load);
}
;// CONCATENATED MODULE: ./src/common/injectStyle.tsx
/*
* @Author: mengzonefire
* @Date: 2021-07-23 17:32:18
* @LastEditTime: 2023-04-19 21:51:03
* @LastEditors: mengzonefire
* @Description: 样式注入模块
*/
/**
* @description: 注入脚本样式
*/
function injectStyle() {
// 注入自定义样式
GM_addStyle((app_default()));
GM_addStyle((css_app_default()));
var swalThemes = GM_getValue("swalThemes") || "Default"; // sweetAlert的主题(css), 默认为Default
if ("Default" != swalThemes) {
var ThemesCss = GM_getValue("" + swalCssVer + swalThemes); // 从缓存获取非默认主题的css代码
if (ThemesCss)
GM_addStyle(ThemesCss);
else {
getThemesCss(swalThemes); // 未找到缓存, fallback到下载css代码
return;
}
}
loaderBaidu();
}
/**
* @description: 下载并注入对应主题的css样式代码, 会将css代码缓存本地
* @param {string} swalThemes 主题包名
*/
function getThemesCss(swalThemes) {
ajax({
url: extCssUrl[swalThemes],
method: "GET",
}, function (data) {
var ThemesCss = data.responseText;
if (ThemesCss.length < 100) {
showAlert(appError.SwalCssInvalid +
("\\n\\u9519\\u8BEF\\u6570\\u636E:" + swalThemes + " InvalidCss:\\n" + ThemesCss));
GM_setValue("swalThemes", "Default");
loaderBaidu();
return;
} // 返回data数据长度过小, 判定为无效样式代码
GM_setValue("" + swalCssVer + swalThemes, ThemesCss); // 缓存css代码
GM_addStyle(ThemesCss); // 注入css
loaderBaidu();
}, function (statusCode) {
showAlert(appError.SwalCssErrReq + ("#" + statusCode));
GM_setValue("swalThemes", "Default");
loaderBaidu();
});
}
;// CONCATENATED MODULE: ./node_modules/js-base64/base64.mjs
/**
* base64.ts
*
* Licensed under the BSD 3-Clause License.
* <http://opensource.org/licenses/BSD-3-Clause>
*
* References:
* <http://en.wikipedia.org/wiki/Base64>
*
* @author Dan Kogai (<https://github.com/dankogai>)
*/
const base64_version = '3.7.2';
/**
* @deprecated use lowercase `version`.
*/
const VERSION = base64_version;
const _hasatob = typeof atob === 'function';
const _hasbtoa = typeof btoa === 'function';
const _hasBuffer = typeof Buffer === 'function';
const _TD = typeof TextDecoder === 'function' ? new TextDecoder() : undefined;
const _TE = typeof TextEncoder === 'function' ? new TextEncoder() : undefined;
const b64ch = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
const b64chs = Array.prototype.slice.call(b64ch);
const b64tab = ((a) => {
let tab = {};
a.forEach((c, i) => tab[c] = i);
return tab;
})(b64chs);
const b64re = /^(?:[A-Za-z\\d+\\/]{4})*?(?:[A-Za-z\\d+\\/]{2}(?:==)?|[A-Za-z\\d+\\/]{3}=?)?$/;
const _fromCC = String.fromCharCode.bind(String);
const _U8Afrom = typeof Uint8Array.from === 'function'
? Uint8Array.from.bind(Uint8Array)
: (it, fn = (x) => x) => new Uint8Array(Array.prototype.slice.call(it, 0).map(fn));
const _mkUriSafe = (src) => src
.replace(/=/g, '').replace(/[+\\/]/g, (m0) => m0 == '+' ? '-' : '_');
const _tidyB64 = (s) => s.replace(/[^A-Za-z0-9\\+\\/]/g, '');
/**
* polyfill version of `btoa`
*/
const btoaPolyfill = (bin) => {
// console.log('polyfilled');
let u32, c0, c1, c2, asc = '';
const pad = bin.length % 3;
for (let i = 0; i < bin.length;) {
if ((c0 = bin.charCodeAt(i++)) > 255 ||
(c1 = bin.charCodeAt(i++)) > 255 ||
(c2 = bin.charCodeAt(i++)) > 255)
throw new TypeError('invalid character found');
u32 = (c0 << 16) | (c1 << 8) | c2;
asc += b64chs[u32 >> 18 & 63]
+ b64chs[u32 >> 12 & 63]
+ b64chs[u32 >> 6 & 63]
+ b64chs[u32 & 63];
}
return pad ? asc.slice(0, pad - 3) + "===".substring(pad) : asc;
};
/**
* does what `window.btoa` of web browsers do.
* @param {String} bin binary string
* @returns {string} Base64-encoded string
*/
const _btoa = _hasbtoa ? (bin) => btoa(bin)
: _hasBuffer ? (bin) => Buffer.from(bin, 'binary').toString('base64')
: btoaPolyfill;
const _fromUint8Array = _hasBuffer
? (u8a) => Buffer.from(u8a).toString('base64')
: (u8a) => {
// cf. <https://stackoverflow.com/questions/12710001/how-to-convert-uint8-array-to-base64-encoded-string/12713326#12713326>
const maxargs = 0x1000;
let strs = [];
for (let i = 0, l = u8a.length; i < l; i += maxargs) {
strs.push(_fromCC.apply(null, u8a.subarray(i, i + maxargs)));
}
return _btoa(strs.join(''));
};
/**
* converts a Uint8Array to a Base64 string.
* @param {boolean} [urlsafe] URL-and-filename-safe a la RFC4648 §5
* @returns {string} Base64 string
*/
const fromUint8Array = (u8a, urlsafe = false) => urlsafe ? _mkUriSafe(_fromUint8Array(u8a)) : _fromUint8Array(u8a);
// This trick is found broken <https://github.com/dankogai/js-base64/issues/130>
// const utob = (src: string) => unescape(encodeURIComponent(src));
// reverting good old fationed regexp
const cb_utob = (c) => {
if (c.length < 2) {
var cc = c.charCodeAt(0);
return cc < 0x80 ? c
: cc < 0x800 ? (_fromCC(0xc0 | (cc >>> 6))
+ _fromCC(0x80 | (cc & 0x3f)))
: (_fromCC(0xe0 | ((cc >>> 12) & 0x0f))
+ _fromCC(0x80 | ((cc >>> 6) & 0x3f))
+ _fromCC(0x80 | (cc & 0x3f)));
}
else {
var cc = 0x10000
+ (c.charCodeAt(0) - 0xD800) * 0x400
+ (c.charCodeAt(1) - 0xDC00);
return (_fromCC(0xf0 | ((cc >>> 18) & 0x07))
+ _fromCC(0x80 | ((cc >>> 12) & 0x3f))
+ _fromCC(0x80 | ((cc >>> 6) & 0x3f))
+ _fromCC(0x80 | (cc & 0x3f)));
}
};
const re_utob = /[\\uD800-\\uDBFF][\\uDC00-\\uDFFFF]|[^\\x00-\\x7F]/g;
/**
* @deprecated should have been internal use only.
* @param {string} src UTF-8 string
* @returns {string} UTF-16 string
*/
const utob = (u) => u.replace(re_utob, cb_utob);
//
const _encode = _hasBuffer
? (s) => Buffer.from(s, 'utf8').toString('base64')
: _TE
? (s) => _fromUint8Array(_TE.encode(s))
: (s) => _btoa(utob(s));
/**
* converts a UTF-8-encoded string to a Base64 string.
* @param {boolean} [urlsafe] if `true` make the result URL-safe
* @returns {string} Base64 string
*/
const encode = (src, urlsafe = false) => urlsafe
? _mkUriSafe(_encode(src))
: _encode(src);
/**
* converts a UTF-8-encoded string to URL-safe Base64 RFC4648 §5.
* @returns {string} Base64 string
*/
const base64_encodeURI = (src) => encode(src, true);
// This trick is found broken <https://github.com/dankogai/js-base64/issues/130>
// const btou = (src: string) => decodeURIComponent(escape(src));
// reverting good old fationed regexp
const re_btou = /[\\xC0-\\xDF][\\x80-\\xBF]|[\\xE0-\\xEF][\\x80-\\xBF]{2}|[\\xF0-\\xF7][\\x80-\\xBF]{3}/g;
const cb_btou = (cccc) => {
switch (cccc.length) {
case 4:
var cp = ((0x07 & cccc.charCodeAt(0)) << 18)
| ((0x3f & cccc.charCodeAt(1)) << 12)
| ((0x3f & cccc.charCodeAt(2)) << 6)
| (0x3f & cccc.charCodeAt(3)), offset = cp - 0x10000;
return (_fromCC((offset >>> 10) + 0xD800)
+ _fromCC((offset & 0x3FF) + 0xDC00));
case 3:
return _fromCC(((0x0f & cccc.charCodeAt(0)) << 12)
| ((0x3f & cccc.charCodeAt(1)) << 6)
| (0x3f & cccc.charCodeAt(2)));
default:
return _fromCC(((0x1f & cccc.charCodeAt(0)) << 6)
| (0x3f & cccc.charCodeAt(1)));
}
};
/**
* @deprecated should have been internal use only.
* @param {string} src UTF-16 string
* @returns {string} UTF-8 string
*/
const btou = (b) => b.replace(re_btou, cb_btou);
/**
* polyfill version of `atob`
*/
const atobPolyfill = (asc) => {
// console.log('polyfilled');
asc = asc.replace(/\\s+/g, '');
if (!b64re.test(asc))
throw new TypeError('malformed base64.');
asc += '=='.slice(2 - (asc.length & 3));
let u24, bin = '', r1, r2;
for (let i = 0; i < asc.length;) {
u24 = b64tab[asc.charAt(i++)] << 18
| b64tab[asc.charAt(i++)] << 12
| (r1 = b64tab[asc.charAt(i++)]) << 6
| (r2 = b64tab[asc.charAt(i++)]);
bin += r1 === 64 ? _fromCC(u24 >> 16 & 255)
: r2 === 64 ? _fromCC(u24 >> 16 & 255, u24 >> 8 & 255)
: _fromCC(u24 >> 16 & 255, u24 >> 8 & 255, u24 & 255);
}
return bin;
};
/**
* does what `window.atob` of web browsers do.
* @param {String} asc Base64-encoded string
* @returns {string} binary string
*/
const _atob = _hasatob ? (asc) => atob(_tidyB64(asc))
: _hasBuffer ? (asc) => Buffer.from(asc, 'base64').toString('binary')
: atobPolyfill;
//
const _toUint8Array = _hasBuffer
? (a) => _U8Afrom(Buffer.from(a, 'base64'))
: (a) => _U8Afrom(_atob(a), c => c.charCodeAt(0));
/**
* converts a Base64 string to a Uint8Array.
*/
const toUint8Array = (a) => _toUint8Array(_unURI(a));
//
const _decode = _hasBuffer
? (a) => Buffer.from(a, 'base64').toString('utf8')
: _TD
? (a) => _TD.decode(_toUint8Array(a))
: (a) => btou(_atob(a));
const _unURI = (a) => _tidyB64(a.replace(/[-_]/g, (m0) => m0 == '-' ? '+' : '/'));
/**
* converts a Base64 string to a UTF-8 string.
* @param {String} src Base64 string. Both normal and URL-safe are supported
* @returns {string} UTF-8 string
*/
const decode = (src) => _decode(_unURI(src));
/**
* check if a value is a valid Base64 string
* @param {String} src a value to check
*/
const isValid = (src) => {
if (typeof src !== 'string')
return false;
const s = src.replace(/\\s+/g, '').replace(/={0,2}$/, '');
return !/[^\\s0-9a-zA-Z\\+/]/.test(s) || !/[^\\s0-9a-zA-Z\\-_]/.test(s);
};
//
const _noEnum = (v) => {
return {
value: v, enumerable: false, writable: true, configurable: true
};
};
/**
* extend String.prototype with relevant methods
*/
const extendString = function () {
const _add = (name, body) => Object.defineProperty(String.prototype, name, _noEnum(body));
_add('fromBase64', function () { return decode(this); });
_add('toBase64', function (urlsafe) { return encode(this, urlsafe); });
_add('toBase64URI', function () { return encode(this, true); });
_add('toBase64URL', function () { return encode(this, true); });
_add('toUint8Array', function () { return toUint8Array(this); });
};
/**
* extend Uint8Array.prototype with relevant methods
*/
const extendUint8Array = function () {
const _add = (name, body) => Object.defineProperty(Uint8Array.prototype, name, _noEnum(body));
_add('toBase64', function (urlsafe) { return fromUint8Array(this, urlsafe); });
_add('toBase64URI', function () { return fromUint8Array(this, true); });
_add('toBase64URL', function () { return fromUint8Array(this, true); });
};
/**
* extend Builtin prototypes with relevant methods
*/
const extendBuiltins = () => {
extendString();
extendUint8Array();
};
const gBase64 = {
version: base64_version,
VERSION: VERSION,
atob: _atob,
atobPolyfill: atobPolyfill,
btoa: _btoa,
btoaPolyfill: btoaPolyfill,
fromBase64: decode,
toBase64: encode,
encode: encode,
encodeURI: base64_encodeURI,
encodeURL: base64_encodeURI,
utob: utob,
btou: btou,
decode: decode,
isValid: isValid,
fromUint8Array: fromUint8Array,
toUint8Array: toUint8Array,
extendString: extendString,
extendUint8Array: extendUint8Array,
extendBuiltins: extendBuiltins,
};
// makecjs:CUT //
// and finally,
;// CONCATENATED MODULE: ./src/app.tsx
/**
* @description: 主函数入口
*/
function app_app() {
gBase64.extendString();
injectStyle();
}
// 广告拦截插件会导致脚本报错跳出, 网页卡死, 故加入异常处理
try {
app_app();
}
catch (error) {
console.log(error);
}
})();
/******/ })()
;