/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD AND TERSER
if you want to view the source, please visit the github repository of this plugin
*/
"use strict";
var extendStatics, __assign, __create = Object.create, __defProp = Object.defineProperty, __getOwnPropDesc = Object.getOwnPropertyDescriptor, __getOwnPropNames = Object.getOwnPropertyNames, __getProtoOf = Object.getPrototypeOf, __hasOwnProp = Object.prototype.hasOwnProperty, __defNormalProp = (_, ee, ne) => ee in _ ? __defProp(_, ee, {
enumerable: true,
configurable: true,
writable: true,
value: ne
}) : _[ee] = ne, __esm = (_, ee) => function __init() {
return _ && (ee = (0, _[__getOwnPropNames(_)[0]])(_ = 0)), ee;
}, __commonJS = (_, ee) => function __require() {
return ee || (0, _[__getOwnPropNames(_)[0]])((ee = {
exports: {}
}).exports, ee), ee.exports;
}, __export = (_, ee) => {
for (var ne in ee) __defProp(_, ne, {
get: ee[ne],
enumerable: true
});
}, __copyProps = (_, ee, ne, ie) => {
if (ee && "object" == typeof ee || "function" == typeof ee) for (let re of __getOwnPropNames(ee)) if (!__hasOwnProp.call(_, re) && re !== ne) __defProp(_, re, {
get: () => ee[re],
enumerable: !(ie = __getOwnPropDesc(ee, re)) || ie.enumerable
});
return _;
}, __toESM = (_, ee, ne) => (ne = null != _ ? __create(__getProtoOf(_)) : {}, __copyProps(ee || !_ || !_.__esModule ? __defProp(ne, "default", {
value: _,
enumerable: true
}) : ne, _)), __toCommonJS = _ => __copyProps(__defProp({}, "__esModule", {
value: true
}), _), __publicField = (_, ee, ne) => {
__defNormalProp(_, "symbol" != typeof ee ? ee + "" : ee, ne);
return ne;
}, __accessCheck = (_, ee, ne) => {
if (!ee.has(_)) throw TypeError("Cannot " + ne);
}, __privateGet = (_, ee, ne) => {
__accessCheck(_, ee, "read from private field");
return ne ? ne.call(_) : ee.get(_);
}, __privateAdd = (_, ee, ne) => {
if (ee.has(_)) throw TypeError("Cannot add the same private member more than once");
ee instanceof WeakSet ? ee.add(_) : ee.set(_, ne);
}, __privateSet = (_, ee, ne, ie) => {
__accessCheck(_, ee, "write to private field");
ie ? ie.call(_, ne) : ee.set(_, ne);
return ne;
}, __privateMethod = (_, ee, ne) => {
__accessCheck(_, ee, "access private method");
return ne;
}, require_diff_match_patch = __commonJS({
"node_modules/diff-match-patch/index.js"(_, ee) {
var diff_match_patch2 = function() {
this.Diff_Timeout = 1;
this.Diff_EditCost = 4;
this.Match_Threshold = .5;
this.Match_Distance = 1e3;
this.Patch_DeleteThreshold = .5;
this.Patch_Margin = 4;
this.Match_MaxBits = 32;
}, ne = -1;
diff_match_patch2.Diff = function(_, ee) {
return [ _, ee ];
};
diff_match_patch2.prototype.diff_main = function(_, ee, ne, ie) {
if ("undefined" == typeof ie) if (this.Diff_Timeout <= 0) ie = Number.MAX_VALUE; else ie = (new Date).getTime() + 1e3 * this.Diff_Timeout;
var re = ie;
if (null == _ || null == ee) throw new Error("Null input. (diff_main)");
if (_ == ee) if (_) return [ new diff_match_patch2.Diff(0, _) ]; else return [];
if ("undefined" == typeof ne) ne = true;
var se = ne, oe = this.diff_commonPrefix(_, ee), le = _.substring(0, oe);
_ = _.substring(oe);
ee = ee.substring(oe);
oe = this.diff_commonSuffix(_, ee);
var ue = _.substring(_.length - oe);
_ = _.substring(0, _.length - oe);
ee = ee.substring(0, ee.length - oe);
var de = this.diff_compute_(_, ee, se, re);
if (le) de.unshift(new diff_match_patch2.Diff(0, le));
if (ue) de.push(new diff_match_patch2.Diff(0, ue));
this.diff_cleanupMerge(de);
return de;
};
diff_match_patch2.prototype.diff_compute_ = function(_, ee, ie, re) {
var se;
if (!_) return [ new diff_match_patch2.Diff(1, ee) ];
if (!ee) return [ new diff_match_patch2.Diff(ne, _) ];
var oe = _.length > ee.length ? _ : ee, le = _.length > ee.length ? ee : _, ue = oe.indexOf(le);
if (-1 != ue) {
se = [ new diff_match_patch2.Diff(1, oe.substring(0, ue)), new diff_match_patch2.Diff(0, le), new diff_match_patch2.Diff(1, oe.substring(ue + le.length)) ];
if (_.length > ee.length) se[0][0] = se[2][0] = ne;
return se;
}
if (1 == le.length) return [ new diff_match_patch2.Diff(ne, _), new diff_match_patch2.Diff(1, ee) ];
var de = this.diff_halfMatch_(_, ee);
if (de) {
var fe = de[0], he = de[1], pe = de[2], ge = de[3], me = de[4], ye = this.diff_main(fe, pe, ie, re), ve = this.diff_main(he, ge, ie, re);
return ye.concat([ new diff_match_patch2.Diff(0, me) ], ve);
}
if (ie && _.length > 100 && ee.length > 100) return this.diff_lineMode_(_, ee, re); else return this.diff_bisect_(_, ee, re);
};
diff_match_patch2.prototype.diff_lineMode_ = function(_, ee, ie) {
var re = this.diff_linesToChars_(_, ee);
_ = re.chars1;
ee = re.chars2;
var se = re.lineArray, oe = this.diff_main(_, ee, false, ie);
this.diff_charsToLines_(oe, se);
this.diff_cleanupSemantic(oe);
oe.push(new diff_match_patch2.Diff(0, ""));
for (var le = 0, ue = 0, de = 0, fe = "", he = ""; le < oe.length; ) {
switch (oe[le][0]) {
case 1:
de++;
he += oe[le][1];
break;
case ne:
ue++;
fe += oe[le][1];
break;
case 0:
if (ue >= 1 && de >= 1) {
oe.splice(le - ue - de, ue + de);
le = le - ue - de;
for (var pe = this.diff_main(fe, he, false, ie), ge = pe.length - 1; ge >= 0; ge--) oe.splice(le, 0, pe[ge]);
le += pe.length;
}
de = 0;
ue = 0;
fe = "";
he = "";
break;
}
le++;
}
oe.pop();
return oe;
};
diff_match_patch2.prototype.diff_bisect_ = function(_, ee, ie) {
for (var re = _.length, se = ee.length, oe = Math.ceil((re + se) / 2), le = oe, ue = 2 * oe, de = new Array(ue), fe = new Array(ue), he = 0; he < ue; he++) {
de[he] = -1;
fe[he] = -1;
}
de[le + 1] = 0;
fe[le + 1] = 0;
for (var pe = re - se, ge = pe % 2 != 0, me = 0, ye = 0, ve = 0, Se = 0, Ee = 0; Ee < oe && !((new Date).getTime() > ie); Ee++) {
for (var Ce = -Ee + me; Ce <= Ee - ye; Ce += 2) {
var we = le + Ce;
if (Ce == -Ee || Ce != Ee && de[we - 1] < de[we + 1]) Re = de[we + 1]; else Re = de[we - 1] + 1;
for (var Oe = Re - Ce; Re < re && Oe < se && _.charAt(Re) == ee.charAt(Oe); ) {
Re++;
Oe++;
}
de[we] = Re;
if (Re > re) ye += 2; else if (Oe > se) me += 2; else if (ge) if ((Ae = le + pe - Ce) >= 0 && Ae < ue && -1 != fe[Ae]) if (Re >= (xe = re - fe[Ae])) return this.diff_bisectSplit_(_, ee, Re, Oe, ie);
}
for (var ke = -Ee + ve; ke <= Ee - Se; ke += 2) {
var xe, Ae = le + ke;
if (ke == -Ee || ke != Ee && fe[Ae - 1] < fe[Ae + 1]) xe = fe[Ae + 1]; else xe = fe[Ae - 1] + 1;
for (var Le = xe - ke; xe < re && Le < se && _.charAt(re - xe - 1) == ee.charAt(se - Le - 1); ) {
xe++;
Le++;
}
fe[Ae] = xe;
if (xe > re) Se += 2; else if (Le > se) ve += 2; else if (!ge) if ((we = le + pe - ke) >= 0 && we < ue && -1 != de[we]) {
var Re;
Oe = le + (Re = de[we]) - we;
if (Re >= (xe = re - xe)) return this.diff_bisectSplit_(_, ee, Re, Oe, ie);
}
}
}
return [ new diff_match_patch2.Diff(ne, _), new diff_match_patch2.Diff(1, ee) ];
};
diff_match_patch2.prototype.diff_bisectSplit_ = function(_, ee, ne, ie, re) {
var se = _.substring(0, ne), oe = ee.substring(0, ie), le = _.substring(ne), ue = ee.substring(ie), de = this.diff_main(se, oe, false, re), fe = this.diff_main(le, ue, false, re);
return de.concat(fe);
};
diff_match_patch2.prototype.diff_linesToChars_ = function(_, ee) {
var ne = [], ie = {};
ne[0] = "";
function diff_linesToCharsMunge_(_) {
for (var ee = "", se = 0, oe = -1, le = ne.length; oe < _.length - 1; ) {
if (-1 == (oe = _.indexOf("\n", se))) oe = _.length - 1;
var ue = _.substring(se, oe + 1);
if (ie.hasOwnProperty ? ie.hasOwnProperty(ue) : void 0 !== ie[ue]) ee += String.fromCharCode(ie[ue]); else {
if (le == re) {
ue = _.substring(se);
oe = _.length;
}
ee += String.fromCharCode(le);
ie[ue] = le;
ne[le++] = ue;
}
se = oe + 1;
}
return ee;
}
var re = 4e4, se = diff_linesToCharsMunge_(_);
re = 65535;
return {
chars1: se,
chars2: diff_linesToCharsMunge_(ee),
lineArray: ne
};
};
diff_match_patch2.prototype.diff_charsToLines_ = function(_, ee) {
for (var ne = 0; ne < _.length; ne++) {
for (var ie = _[ne][1], re = [], se = 0; se < ie.length; se++) re[se] = ee[ie.charCodeAt(se)];
_[ne][1] = re.join("");
}
};
diff_match_patch2.prototype.diff_commonPrefix = function(_, ee) {
if (!_ || !ee || _.charAt(0) != ee.charAt(0)) return 0;
for (var ne = 0, ie = Math.min(_.length, ee.length), re = ie, se = 0; ne < re; ) {
if (_.substring(se, re) == ee.substring(se, re)) se = ne = re; else ie = re;
re = Math.floor((ie - ne) / 2 + ne);
}
return re;
};
diff_match_patch2.prototype.diff_commonSuffix = function(_, ee) {
if (!_ || !ee || _.charAt(_.length - 1) != ee.charAt(ee.length - 1)) return 0;
for (var ne = 0, ie = Math.min(_.length, ee.length), re = ie, se = 0; ne < re; ) {
if (_.substring(_.length - re, _.length - se) == ee.substring(ee.length - re, ee.length - se)) se = ne = re; else ie = re;
re = Math.floor((ie - ne) / 2 + ne);
}
return re;
};
diff_match_patch2.prototype.diff_commonOverlap_ = function(_, ee) {
var ne = _.length, ie = ee.length;
if (0 == ne || 0 == ie) return 0;
if (ne > ie) _ = _.substring(ne - ie); else if (ne < ie) ee = ee.substring(0, ne);
var re = Math.min(ne, ie);
if (_ == ee) return re;
for (var se = 0, oe = 1; ;) {
var le = _.substring(re - oe), ue = ee.indexOf(le);
if (-1 == ue) return se;
oe += ue;
if (0 == ue || _.substring(re - oe) == ee.substring(0, oe)) {
se = oe;
oe++;
}
}
};
diff_match_patch2.prototype.diff_halfMatch_ = function(_, ee) {
if (this.Diff_Timeout <= 0) return null;
var ne = _.length > ee.length ? _ : ee, ie = _.length > ee.length ? ee : _;
if (ne.length < 4 || 2 * ie.length < ne.length) return null;
var re = this;
function diff_halfMatchI_(_, ee, ne) {
for (var ie, se, oe, le, ue = _.substring(ne, ne + Math.floor(_.length / 4)), de = -1, fe = ""; -1 != (de = ee.indexOf(ue, de + 1)); ) {
var he = re.diff_commonPrefix(_.substring(ne), ee.substring(de)), pe = re.diff_commonSuffix(_.substring(0, ne), ee.substring(0, de));
if (fe.length < pe + he) {
fe = ee.substring(de - pe, de) + ee.substring(de, de + he);
ie = _.substring(0, ne - pe);
se = _.substring(ne + he);
oe = ee.substring(0, de - pe);
le = ee.substring(de + he);
}
}
if (2 * fe.length >= _.length) return [ ie, se, oe, le, fe ]; else return null;
}
var se, oe, le, ue, de, fe = diff_halfMatchI_(ne, ie, Math.ceil(ne.length / 4)), he = diff_halfMatchI_(ne, ie, Math.ceil(ne.length / 2));
if (!fe && !he) return null; else if (!he) se = fe; else if (!fe) se = he; else se = fe[4].length > he[4].length ? fe : he;
if (_.length > ee.length) {
oe = se[0];
le = se[1];
ue = se[2];
de = se[3];
} else {
ue = se[0];
de = se[1];
oe = se[2];
le = se[3];
}
return [ oe, le, ue, de, se[4] ];
};
diff_match_patch2.prototype.diff_cleanupSemantic = function(_) {
for (var ee = false, ie = [], re = 0, se = null, oe = 0, le = 0, ue = 0, de = 0, fe = 0; oe < _.length; ) {
if (0 == _[oe][0]) {
ie[re++] = oe;
le = de;
ue = fe;
de = 0;
fe = 0;
se = _[oe][1];
} else {
if (1 == _[oe][0]) de += _[oe][1].length; else fe += _[oe][1].length;
if (se && se.length <= Math.max(le, ue) && se.length <= Math.max(de, fe)) {
_.splice(ie[re - 1], 0, new diff_match_patch2.Diff(ne, se));
_[ie[re - 1] + 1][0] = 1;
re--;
oe = --re > 0 ? ie[re - 1] : -1;
le = 0;
ue = 0;
de = 0;
fe = 0;
se = null;
ee = true;
}
}
oe++;
}
if (ee) this.diff_cleanupMerge(_);
this.diff_cleanupSemanticLossless(_);
oe = 1;
for (;oe < _.length; ) {
if (_[oe - 1][0] == ne && 1 == _[oe][0]) {
var he = _[oe - 1][1], pe = _[oe][1], ge = this.diff_commonOverlap_(he, pe), me = this.diff_commonOverlap_(pe, he);
if (ge >= me) {
if (ge >= he.length / 2 || ge >= pe.length / 2) {
_.splice(oe, 0, new diff_match_patch2.Diff(0, pe.substring(0, ge)));
_[oe - 1][1] = he.substring(0, he.length - ge);
_[oe + 1][1] = pe.substring(ge);
oe++;
}
} else if (me >= he.length / 2 || me >= pe.length / 2) {
_.splice(oe, 0, new diff_match_patch2.Diff(0, he.substring(0, me)));
_[oe - 1][0] = 1;
_[oe - 1][1] = pe.substring(0, pe.length - me);
_[oe + 1][0] = ne;
_[oe + 1][1] = he.substring(me);
oe++;
}
oe++;
}
oe++;
}
};
diff_match_patch2.prototype.diff_cleanupSemanticLossless = function(_) {
function diff_cleanupSemanticScore_(_, ee) {
if (!_ || !ee) return 6;
var ne = _.charAt(_.length - 1), ie = ee.charAt(0), re = ne.match(diff_match_patch2.nonAlphaNumericRegex_), se = ie.match(diff_match_patch2.nonAlphaNumericRegex_), oe = re && ne.match(diff_match_patch2.whitespaceRegex_), le = se && ie.match(diff_match_patch2.whitespaceRegex_), ue = oe && ne.match(diff_match_patch2.linebreakRegex_), de = le && ie.match(diff_match_patch2.linebreakRegex_), fe = ue && _.match(diff_match_patch2.blanklineEndRegex_), he = de && ee.match(diff_match_patch2.blanklineStartRegex_);
if (fe || he) return 5; else if (ue || de) return 4; else if (re && !oe && le) return 3; else if (oe || le) return 2; else if (re || se) return 1;
return 0;
}
for (var ee = 1; ee < _.length - 1; ) {
if (0 == _[ee - 1][0] && 0 == _[ee + 1][0]) {
var ne = _[ee - 1][1], ie = _[ee][1], re = _[ee + 1][1], se = this.diff_commonSuffix(ne, ie);
if (se) {
var oe = ie.substring(ie.length - se);
ne = ne.substring(0, ne.length - se);
ie = oe + ie.substring(0, ie.length - se);
re = oe + re;
}
for (var le = ne, ue = ie, de = re, fe = diff_cleanupSemanticScore_(ne, ie) + diff_cleanupSemanticScore_(ie, re); ie.charAt(0) === re.charAt(0); ) {
ne += ie.charAt(0);
ie = ie.substring(1) + re.charAt(0);
re = re.substring(1);
var he = diff_cleanupSemanticScore_(ne, ie) + diff_cleanupSemanticScore_(ie, re);
if (he >= fe) {
fe = he;
le = ne;
ue = ie;
de = re;
}
}
if (_[ee - 1][1] != le) {
if (le) _[ee - 1][1] = le; else {
_.splice(ee - 1, 1);
ee--;
}
_[ee][1] = ue;
if (de) _[ee + 1][1] = de; else {
_.splice(ee + 1, 1);
ee--;
}
}
}
ee++;
}
};
diff_match_patch2.nonAlphaNumericRegex_ = /[^a-zA-Z0-9]/;
diff_match_patch2.whitespaceRegex_ = /\s/;
diff_match_patch2.linebreakRegex_ = /[\r\n]/;
diff_match_patch2.blanklineEndRegex_ = /\n\r?\n$/;
diff_match_patch2.blanklineStartRegex_ = /^\r?\n\r?\n/;
diff_match_patch2.prototype.diff_cleanupEfficiency = function(_) {
for (var ee = false, ie = [], re = 0, se = null, oe = 0, le = false, ue = false, de = false, fe = false; oe < _.length; ) {
if (0 == _[oe][0]) {
if (_[oe][1].length < this.Diff_EditCost && (de || fe)) {
ie[re++] = oe;
le = de;
ue = fe;
se = _[oe][1];
} else {
re = 0;
se = null;
}
de = fe = false;
} else {
if (_[oe][0] == ne) fe = true; else de = true;
if (se && (le && ue && de && fe || se.length < this.Diff_EditCost / 2 && le + ue + de + fe == 3)) {
_.splice(ie[re - 1], 0, new diff_match_patch2.Diff(ne, se));
_[ie[re - 1] + 1][0] = 1;
re--;
se = null;
if (le && ue) {
de = fe = true;
re = 0;
} else {
oe = --re > 0 ? ie[re - 1] : -1;
de = fe = false;
}
ee = true;
}
}
oe++;
}
if (ee) this.diff_cleanupMerge(_);
};
diff_match_patch2.prototype.diff_cleanupMerge = function(_) {
_.push(new diff_match_patch2.Diff(0, ""));
for (var ee, ie = 0, re = 0, se = 0, oe = "", le = ""; ie < _.length; ) switch (_[ie][0]) {
case 1:
se++;
le += _[ie][1];
ie++;
break;
case ne:
re++;
oe += _[ie][1];
ie++;
break;
case 0:
if (re + se > 1) {
if (0 !== re && 0 !== se) {
if (0 !== (ee = this.diff_commonPrefix(le, oe))) {
if (ie - re - se > 0 && 0 == _[ie - re - se - 1][0]) _[ie - re - se - 1][1] += le.substring(0, ee); else {
_.splice(0, 0, new diff_match_patch2.Diff(0, le.substring(0, ee)));
ie++;
}
le = le.substring(ee);
oe = oe.substring(ee);
}
if (0 !== (ee = this.diff_commonSuffix(le, oe))) {
_[ie][1] = le.substring(le.length - ee) + _[ie][1];
le = le.substring(0, le.length - ee);
oe = oe.substring(0, oe.length - ee);
}
}
ie -= re + se;
_.splice(ie, re + se);
if (oe.length) {
_.splice(ie, 0, new diff_match_patch2.Diff(ne, oe));
ie++;
}
if (le.length) {
_.splice(ie, 0, new diff_match_patch2.Diff(1, le));
ie++;
}
ie++;
} else if (0 !== ie && 0 == _[ie - 1][0]) {
_[ie - 1][1] += _[ie][1];
_.splice(ie, 1);
} else ie++;
se = 0;
re = 0;
oe = "";
le = "";
break;
}
if ("" === _[_.length - 1][1]) _.pop();
var ue = false;
ie = 1;
for (;ie < _.length - 1; ) {
if (0 == _[ie - 1][0] && 0 == _[ie + 1][0]) if (_[ie][1].substring(_[ie][1].length - _[ie - 1][1].length) == _[ie - 1][1]) {
_[ie][1] = _[ie - 1][1] + _[ie][1].substring(0, _[ie][1].length - _[ie - 1][1].length);
_[ie + 1][1] = _[ie - 1][1] + _[ie + 1][1];
_.splice(ie - 1, 1);
ue = true;
} else if (_[ie][1].substring(0, _[ie + 1][1].length) == _[ie + 1][1]) {
_[ie - 1][1] += _[ie + 1][1];
_[ie][1] = _[ie][1].substring(_[ie + 1][1].length) + _[ie + 1][1];
_.splice(ie + 1, 1);
ue = true;
}
ie++;
}
if (ue) this.diff_cleanupMerge(_);
};
diff_match_patch2.prototype.diff_xIndex = function(_, ee) {
var ie, re = 0, se = 0, oe = 0, le = 0;
for (ie = 0; ie < _.length; ie++) {
if (1 !== _[ie][0]) re += _[ie][1].length;
if (_[ie][0] !== ne) se += _[ie][1].length;
if (re > ee) break;
oe = re;
le = se;
}
if (_.length != ie && _[ie][0] === ne) return le; else return le + (ee - oe);
};
diff_match_patch2.prototype.diff_prettyHtml = function(_) {
for (var ee = [], ie = /&/g, re = //g, oe = /\n/g, le = 0; le < _.length; le++) {
var ue = _[le][0], de = _[le][1].replace(ie, "&").replace(re, "<").replace(se, ">").replace(oe, "¶
");
switch (ue) {
case 1:
ee[le] = '' + de + "";
break;
case ne:
ee[le] = '' + de + "";
break;
case 0:
ee[le] = "" + de + "";
break;
}
}
return ee.join("");
};
diff_match_patch2.prototype.diff_text1 = function(_) {
for (var ee = [], ne = 0; ne < _.length; ne++) if (1 !== _[ne][0]) ee[ne] = _[ne][1];
return ee.join("");
};
diff_match_patch2.prototype.diff_text2 = function(_) {
for (var ee = [], ie = 0; ie < _.length; ie++) if (_[ie][0] !== ne) ee[ie] = _[ie][1];
return ee.join("");
};
diff_match_patch2.prototype.diff_levenshtein = function(_) {
for (var ee = 0, ie = 0, re = 0, se = 0; se < _.length; se++) {
var oe = _[se][0], le = _[se][1];
switch (oe) {
case 1:
ie += le.length;
break;
case ne:
re += le.length;
break;
case 0:
ee += Math.max(ie, re);
ie = 0;
re = 0;
break;
}
}
return ee += Math.max(ie, re);
};
diff_match_patch2.prototype.diff_toDelta = function(_) {
for (var ee = [], ie = 0; ie < _.length; ie++) switch (_[ie][0]) {
case 1:
ee[ie] = "+" + encodeURI(_[ie][1]);
break;
case ne:
ee[ie] = "-" + _[ie][1].length;
break;
case 0:
ee[ie] = "=" + _[ie][1].length;
break;
}
return ee.join("\t").replace(/%20/g, " ");
};
diff_match_patch2.prototype.diff_fromDelta = function(_, ee) {
for (var ie = [], re = 0, se = 0, oe = ee.split(/\t/g), le = 0; le < oe.length; le++) {
var ue = oe[le].substring(1);
switch (oe[le].charAt(0)) {
case "+":
try {
ie[re++] = new diff_match_patch2.Diff(1, decodeURI(ue));
} catch (_) {
throw new Error("Illegal escape in diff_fromDelta: " + ue);
}
break;
case "-":
case "=":
var de = parseInt(ue, 10);
if (isNaN(de) || de < 0) throw new Error("Invalid number in diff_fromDelta: " + ue);
var fe = _.substring(se, se += de);
if ("=" == oe[le].charAt(0)) ie[re++] = new diff_match_patch2.Diff(0, fe); else ie[re++] = new diff_match_patch2.Diff(ne, fe);
break;
default:
if (oe[le]) throw new Error("Invalid diff operation in diff_fromDelta: " + oe[le]);
}
}
if (se != _.length) throw new Error("Delta length (" + se + ") does not equal source text length (" + _.length + ").");
return ie;
};
diff_match_patch2.prototype.match_main = function(_, ee, ne) {
if (null == _ || null == ee || null == ne) throw new Error("Null input. (match_main)");
ne = Math.max(0, Math.min(ne, _.length));
if (_ == ee) return 0; else if (!_.length) return -1; else if (_.substring(ne, ne + ee.length) == ee) return ne; else return this.match_bitap_(_, ee, ne);
};
diff_match_patch2.prototype.match_bitap_ = function(_, ee, ne) {
if (ee.length > this.Match_MaxBits) throw new Error("Pattern too long for this browser.");
var ie = this.match_alphabet_(ee), re = this;
function match_bitapScore_(_, ie) {
var se = _ / ee.length, oe = Math.abs(ne - ie);
if (!re.Match_Distance) return oe ? 1 : se; else return se + oe / re.Match_Distance;
}
var se = this.Match_Threshold, oe = _.indexOf(ee, ne);
if (-1 != oe) {
se = Math.min(match_bitapScore_(0, oe), se);
if (-1 != (oe = _.lastIndexOf(ee, ne + ee.length))) se = Math.min(match_bitapScore_(0, oe), se);
}
var le, ue, de = 1 << ee.length - 1;
oe = -1;
for (var fe, he = ee.length + _.length, pe = 0; pe < ee.length; pe++) {
le = 0;
ue = he;
for (;le < ue; ) {
if (match_bitapScore_(pe, ne + ue) <= se) le = ue; else he = ue;
ue = Math.floor((he - le) / 2 + le);
}
he = ue;
var ge = Math.max(1, ne - ue + 1), me = Math.min(ne + ue, _.length) + ee.length, ye = Array(me + 2);
ye[me + 1] = (1 << pe) - 1;
for (var ve = me; ve >= ge; ve--) {
var Se = ie[_.charAt(ve - 1)];
if (0 === pe) ye[ve] = (ye[ve + 1] << 1 | 1) & Se; else ye[ve] = (ye[ve + 1] << 1 | 1) & Se | (fe[ve + 1] | fe[ve]) << 1 | 1 | fe[ve + 1];
if (ye[ve] & de) {
var Ee = match_bitapScore_(pe, ve - 1);
if (Ee <= se) {
se = Ee;
if ((oe = ve - 1) > ne) ge = Math.max(1, 2 * ne - oe); else break;
}
}
}
if (match_bitapScore_(pe + 1, ne) > se) break;
fe = ye;
}
return oe;
};
diff_match_patch2.prototype.match_alphabet_ = function(_) {
for (var ee = {}, ne = 0; ne < _.length; ne++) ee[_.charAt(ne)] = 0;
for (ne = 0; ne < _.length; ne++) ee[_.charAt(ne)] |= 1 << _.length - ne - 1;
return ee;
};
diff_match_patch2.prototype.patch_addContext_ = function(_, ee) {
if (0 != ee.length) {
if (null === _.start2) throw Error("patch not initialized");
for (var ne = ee.substring(_.start2, _.start2 + _.length1), ie = 0; ee.indexOf(ne) != ee.lastIndexOf(ne) && ne.length < this.Match_MaxBits - this.Patch_Margin - this.Patch_Margin; ) {
ie += this.Patch_Margin;
ne = ee.substring(_.start2 - ie, _.start2 + _.length1 + ie);
}
ie += this.Patch_Margin;
var re = ee.substring(_.start2 - ie, _.start2);
if (re) _.diffs.unshift(new diff_match_patch2.Diff(0, re));
var se = ee.substring(_.start2 + _.length1, _.start2 + _.length1 + ie);
if (se) _.diffs.push(new diff_match_patch2.Diff(0, se));
_.start1 -= re.length;
_.start2 -= re.length;
_.length1 += re.length + se.length;
_.length2 += re.length + se.length;
}
};
diff_match_patch2.prototype.patch_make = function(_, ee, ie) {
var re, se;
if ("string" == typeof _ && "string" == typeof ee && "undefined" == typeof ie) {
re = _;
if ((se = this.diff_main(re, ee, true)).length > 2) {
this.diff_cleanupSemantic(se);
this.diff_cleanupEfficiency(se);
}
} else if (_ && "object" == typeof _ && "undefined" == typeof ee && "undefined" == typeof ie) {
se = _;
re = this.diff_text1(se);
} else if ("string" == typeof _ && ee && "object" == typeof ee && "undefined" == typeof ie) {
re = _;
se = ee;
} else if ("string" == typeof _ && "string" == typeof ee && ie && "object" == typeof ie) {
re = _;
se = ie;
} else throw new Error("Unknown call format to patch_make.");
if (0 === se.length) return [];
for (var oe = [], le = new diff_match_patch2.patch_obj, ue = 0, de = 0, fe = 0, he = re, pe = re, ge = 0; ge < se.length; ge++) {
var me = se[ge][0], ye = se[ge][1];
if (!ue && 0 !== me) {
le.start1 = de;
le.start2 = fe;
}
switch (me) {
case 1:
le.diffs[ue++] = se[ge];
le.length2 += ye.length;
pe = pe.substring(0, fe) + ye + pe.substring(fe);
break;
case ne:
le.length1 += ye.length;
le.diffs[ue++] = se[ge];
pe = pe.substring(0, fe) + pe.substring(fe + ye.length);
break;
case 0:
if (ye.length <= 2 * this.Patch_Margin && ue && se.length != ge + 1) {
le.diffs[ue++] = se[ge];
le.length1 += ye.length;
le.length2 += ye.length;
} else if (ye.length >= 2 * this.Patch_Margin) if (ue) {
this.patch_addContext_(le, he);
oe.push(le);
le = new diff_match_patch2.patch_obj;
ue = 0;
he = pe;
de = fe;
}
break;
}
if (1 !== me) de += ye.length;
if (me !== ne) fe += ye.length;
}
if (ue) {
this.patch_addContext_(le, he);
oe.push(le);
}
return oe;
};
diff_match_patch2.prototype.patch_deepCopy = function(_) {
for (var ee = [], ne = 0; ne < _.length; ne++) {
var ie = _[ne], re = new diff_match_patch2.patch_obj;
re.diffs = [];
for (var se = 0; se < ie.diffs.length; se++) re.diffs[se] = new diff_match_patch2.Diff(ie.diffs[se][0], ie.diffs[se][1]);
re.start1 = ie.start1;
re.start2 = ie.start2;
re.length1 = ie.length1;
re.length2 = ie.length2;
ee[ne] = re;
}
return ee;
};
diff_match_patch2.prototype.patch_apply = function(_, ee) {
if (0 == _.length) return [ ee, [] ];
_ = this.patch_deepCopy(_);
var ie = this.patch_addPadding(_);
ee = ie + ee + ie;
this.patch_splitMax(_);
for (var re = 0, se = [], oe = 0; oe < _.length; oe++) {
var le, ue = _[oe].start2 + re, de = this.diff_text1(_[oe].diffs), fe = -1;
if (de.length > this.Match_MaxBits) {
if (-1 != (le = this.match_main(ee, de.substring(0, this.Match_MaxBits), ue))) if (-1 == (fe = this.match_main(ee, de.substring(de.length - this.Match_MaxBits), ue + de.length - this.Match_MaxBits)) || le >= fe) le = -1;
} else le = this.match_main(ee, de, ue);
if (-1 == le) {
se[oe] = false;
re -= _[oe].length2 - _[oe].length1;
} else {
se[oe] = true;
re = le - ue;
var he;
if (-1 == fe) he = ee.substring(le, le + de.length); else he = ee.substring(le, fe + this.Match_MaxBits);
if (de == he) ee = ee.substring(0, le) + this.diff_text2(_[oe].diffs) + ee.substring(le + de.length); else {
var pe = this.diff_main(de, he, false);
if (de.length > this.Match_MaxBits && this.diff_levenshtein(pe) / de.length > this.Patch_DeleteThreshold) se[oe] = false; else {
this.diff_cleanupSemanticLossless(pe);
for (var ge, me = 0, ye = 0; ye < _[oe].diffs.length; ye++) {
var ve = _[oe].diffs[ye];
if (0 !== ve[0]) ge = this.diff_xIndex(pe, me);
if (1 === ve[0]) ee = ee.substring(0, le + ge) + ve[1] + ee.substring(le + ge); else if (ve[0] === ne) ee = ee.substring(0, le + ge) + ee.substring(le + this.diff_xIndex(pe, me + ve[1].length));
if (ve[0] !== ne) me += ve[1].length;
}
}
}
}
}
return [ ee = ee.substring(ie.length, ee.length - ie.length), se ];
};
diff_match_patch2.prototype.patch_addPadding = function(_) {
for (var ee = this.Patch_Margin, ne = "", ie = 1; ie <= ee; ie++) ne += String.fromCharCode(ie);
for (ie = 0; ie < _.length; ie++) {
_[ie].start1 += ee;
_[ie].start2 += ee;
}
var re = _[0], se = re.diffs;
if (0 == se.length || 0 != se[0][0]) {
se.unshift(new diff_match_patch2.Diff(0, ne));
re.start1 -= ee;
re.start2 -= ee;
re.length1 += ee;
re.length2 += ee;
} else if (ee > se[0][1].length) {
var oe = ee - se[0][1].length;
se[0][1] = ne.substring(se[0][1].length) + se[0][1];
re.start1 -= oe;
re.start2 -= oe;
re.length1 += oe;
re.length2 += oe;
}
if (0 == (se = (re = _[_.length - 1]).diffs).length || 0 != se[se.length - 1][0]) {
se.push(new diff_match_patch2.Diff(0, ne));
re.length1 += ee;
re.length2 += ee;
} else if (ee > se[se.length - 1][1].length) {
oe = ee - se[se.length - 1][1].length;
se[se.length - 1][1] += ne.substring(0, oe);
re.length1 += oe;
re.length2 += oe;
}
return ne;
};
diff_match_patch2.prototype.patch_splitMax = function(_) {
for (var ee = this.Match_MaxBits, ie = 0; ie < _.length; ie++) if (!(_[ie].length1 <= ee)) {
var re = _[ie];
_.splice(ie--, 1);
for (var se = re.start1, oe = re.start2, le = ""; 0 !== re.diffs.length; ) {
var ue = new diff_match_patch2.patch_obj, de = true;
ue.start1 = se - le.length;
ue.start2 = oe - le.length;
if ("" !== le) {
ue.length1 = ue.length2 = le.length;
ue.diffs.push(new diff_match_patch2.Diff(0, le));
}
for (;0 !== re.diffs.length && ue.length1 < ee - this.Patch_Margin; ) {
var fe = re.diffs[0][0], he = re.diffs[0][1];
if (1 === fe) {
ue.length2 += he.length;
oe += he.length;
ue.diffs.push(re.diffs.shift());
de = false;
} else if (fe === ne && 1 == ue.diffs.length && 0 == ue.diffs[0][0] && he.length > 2 * ee) {
ue.length1 += he.length;
se += he.length;
de = false;
ue.diffs.push(new diff_match_patch2.Diff(fe, he));
re.diffs.shift();
} else {
he = he.substring(0, ee - ue.length1 - this.Patch_Margin);
ue.length1 += he.length;
se += he.length;
if (0 === fe) {
ue.length2 += he.length;
oe += he.length;
} else de = false;
ue.diffs.push(new diff_match_patch2.Diff(fe, he));
if (he == re.diffs[0][1]) re.diffs.shift(); else re.diffs[0][1] = re.diffs[0][1].substring(he.length);
}
}
le = (le = this.diff_text2(ue.diffs)).substring(le.length - this.Patch_Margin);
var pe = this.diff_text1(re.diffs).substring(0, this.Patch_Margin);
if ("" !== pe) {
ue.length1 += pe.length;
ue.length2 += pe.length;
if (0 !== ue.diffs.length && 0 === ue.diffs[ue.diffs.length - 1][0]) ue.diffs[ue.diffs.length - 1][1] += pe; else ue.diffs.push(new diff_match_patch2.Diff(0, pe));
}
if (!de) _.splice(++ie, 0, ue);
}
}
};
diff_match_patch2.prototype.patch_toText = function(_) {
for (var ee = [], ne = 0; ne < _.length; ne++) ee[ne] = _[ne];
return ee.join("");
};
diff_match_patch2.prototype.patch_fromText = function(_) {
var ee = [];
if (!_) return ee;
for (var ie = _.split("\n"), re = 0, se = /^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$/; re < ie.length; ) {
var oe = ie[re].match(se);
if (!oe) throw new Error("Invalid patch string: " + ie[re]);
var le = new diff_match_patch2.patch_obj;
ee.push(le);
le.start1 = parseInt(oe[1], 10);
if ("" === oe[2]) {
le.start1--;
le.length1 = 1;
} else if ("0" == oe[2]) le.length1 = 0; else {
le.start1--;
le.length1 = parseInt(oe[2], 10);
}
le.start2 = parseInt(oe[3], 10);
if ("" === oe[4]) {
le.start2--;
le.length2 = 1;
} else if ("0" == oe[4]) le.length2 = 0; else {
le.start2--;
le.length2 = parseInt(oe[4], 10);
}
re++;
for (;re < ie.length; ) {
var ue = ie[re].charAt(0);
try {
var de = decodeURI(ie[re].substring(1));
} catch (_) {
throw new Error("Illegal escape in patch_fromText: " + de);
}
if ("-" == ue) le.diffs.push(new diff_match_patch2.Diff(ne, de)); else if ("+" == ue) le.diffs.push(new diff_match_patch2.Diff(1, de)); else if (" " == ue) le.diffs.push(new diff_match_patch2.Diff(0, de)); else if ("@" == ue) break; else if ("" === ue) ; else throw new Error('Invalid patch mode "' + ue + '" in: ' + de);
re++;
}
}
return ee;
};
diff_match_patch2.patch_obj = function() {
this.diffs = [];
this.start1 = null;
this.start2 = null;
this.length1 = 0;
this.length2 = 0;
};
diff_match_patch2.patch_obj.prototype.toString = function() {
var _, ee;
if (0 === this.length1) _ = this.start1 + ",0"; else if (1 == this.length1) _ = this.start1 + 1; else _ = this.start1 + 1 + "," + this.length1;
if (0 === this.length2) ee = this.start2 + ",0"; else if (1 == this.length2) ee = this.start2 + 1; else ee = this.start2 + 1 + "," + this.length2;
for (var ie, re = [ "@@ -" + _ + " +" + ee + " @@\n" ], se = 0; se < this.diffs.length; se++) {
switch (this.diffs[se][0]) {
case 1:
ie = "+";
break;
case ne:
ie = "-";
break;
case 0:
ie = " ";
break;
}
re[se + 1] = ie + encodeURI(this.diffs[se][1]) + "\n";
}
return re.join("").replace(/%20/g, " ");
};
ee.exports = diff_match_patch2;
ee.exports["diff_match_patch"] = diff_match_patch2;
ee.exports["DIFF_DELETE"] = ne;
ee.exports["DIFF_INSERT"] = 1;
ee.exports["DIFF_EQUAL"] = 0;
}
}), require_balanced_match = __commonJS({
"node_modules/balanced-match/index.js"(_, ee) {
"use strict";
ee.exports = balanced;
function balanced(_, ee, ne) {
if (_ instanceof RegExp) _ = maybeMatch(_, ne);
if (ee instanceof RegExp) ee = maybeMatch(ee, ne);
var ie = range2(_, ee, ne);
return ie && {
start: ie[0],
end: ie[1],
pre: ne.slice(0, ie[0]),
body: ne.slice(ie[0] + _.length, ie[1]),
post: ne.slice(ie[1] + ee.length)
};
}
function maybeMatch(_, ee) {
var ne = ee.match(_);
return ne ? ne[0] : null;
}
balanced.range = range2;
function range2(_, ee, ne) {
var ie, re, se, oe, le, ue = ne.indexOf(_), de = ne.indexOf(ee, ue + 1), fe = ue;
if (ue >= 0 && de > 0) {
if (_ === ee) return [ ue, de ];
ie = [];
se = ne.length;
for (;fe >= 0 && !le; ) {
if (fe == ue) {
ie.push(fe);
ue = ne.indexOf(_, fe + 1);
} else if (1 == ie.length) le = [ ie.pop(), de ]; else {
if ((re = ie.pop()) < se) {
se = re;
oe = de;
}
de = ne.indexOf(ee, fe + 1);
}
fe = ue < de && ue >= 0 ? ue : de;
}
if (ie.length) le = [ se, oe ];
}
return le;
}
}
}), require_brace_expansion = __commonJS({
"node_modules/brace-expansion/index.js"(_, ee) {
var ne = require_balanced_match();
ee.exports = function expandTop(_) {
if (!_) return [];
if ("{}" === _.substr(0, 2)) _ = "\\{\\}" + _.substr(2);
return expand2(function escapeBraces(_) {
return _.split("\\\\").join(ie).split("\\{").join(re).split("\\}").join(se).split("\\,").join(oe).split("\\.").join(le);
}(_), true).map(unescapeBraces);
};
var ie = "\0SLASH" + Math.random() + "\0", re = "\0OPEN" + Math.random() + "\0", se = "\0CLOSE" + Math.random() + "\0", oe = "\0COMMA" + Math.random() + "\0", le = "\0PERIOD" + Math.random() + "\0";
function numeric(_) {
return parseInt(_, 10) == _ ? parseInt(_, 10) : _.charCodeAt(0);
}
function unescapeBraces(_) {
return _.split(ie).join("\\").split(re).join("{").split(se).join("}").split(oe).join(",").split(le).join(".");
}
function parseCommaParts(_) {
if (!_) return [ "" ];
var ee = [], ie = ne("{", "}", _);
if (!ie) return _.split(",");
var re = ie.pre, se = ie.body, oe = ie.post, le = re.split(",");
le[le.length - 1] += "{" + se + "}";
var ue = parseCommaParts(oe);
if (oe.length) {
le[le.length - 1] += ue.shift();
le.push.apply(le, ue);
}
ee.push.apply(ee, le);
return ee;
}
function embrace(_) {
return "{" + _ + "}";
}
function isPadded(_) {
return /^-?0\d/.test(_);
}
function lte(_, ee) {
return _ <= ee;
}
function gte(_, ee) {
return _ >= ee;
}
function expand2(_, ee) {
var ie = [], re = ne("{", "}", _);
if (!re) return [ _ ];
var oe = re.pre, le = re.post.length ? expand2(re.post, false) : [ "" ];
if (/\$$/.test(re.pre)) for (var ue = 0; ue < le.length; ue++) {
var de = oe + "{" + re.body + "}" + le[ue];
ie.push(de);
} else {
var fe, he, pe = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(re.body), ge = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(re.body), me = pe || ge, ye = re.body.indexOf(",") >= 0;
if (!me && !ye) if (re.post.match(/,.*\}/)) return expand2(_ = re.pre + "{" + re.body + se + re.post); else return [ _ ];
if (me) fe = re.body.split(/\.\./); else if (1 === (fe = parseCommaParts(re.body)).length) if (1 === (fe = expand2(fe[0], false).map(embrace)).length) return le.map((function(_) {
return re.pre + fe[0] + _;
}));
if (me) {
var ve = numeric(fe[0]), Se = numeric(fe[1]), Ee = Math.max(fe[0].length, fe[1].length), Ce = 3 == fe.length ? Math.abs(numeric(fe[2])) : 1, we = lte;
if (Se < ve) {
Ce *= -1;
we = gte;
}
var Oe = fe.some(isPadded);
he = [];
for (var ke = ve; we(ke, Se); ke += Ce) {
var xe;
if (ge) {
if ("\\" === (xe = String.fromCharCode(ke))) xe = "";
} else {
xe = String(ke);
if (Oe) {
var Ae = Ee - xe.length;
if (Ae > 0) {
var Le = new Array(Ae + 1).join("0");
if (ke < 0) xe = "-" + Le + xe.slice(1); else xe = Le + xe;
}
}
}
he.push(xe);
}
} else {
he = [];
for (var Re = 0; Re < fe.length; Re++) he.push.apply(he, expand2(fe[Re], false));
}
for (Re = 0; Re < he.length; Re++) for (ue = 0; ue < le.length; ue++) {
de = oe + he[Re] + le[ue];
if (!ee || me || de) ie.push(de);
}
}
return ie;
}
}
}), require_nextTick = __commonJS({
"(disabled):node_modules/immediate/lib/nextTick"() {}
}), require_queueMicrotask = __commonJS({
"node_modules/immediate/lib/queueMicrotask.js"(_) {
"use strict";
_.test = function() {
return "function" == typeof window.queueMicrotask;
};
_.install = function(_) {
return function() {
window.queueMicrotask(_);
};
};
}
}), require_mutation = __commonJS({
"node_modules/immediate/lib/mutation.js"(_) {
"use strict";
var ee = window.MutationObserver || window.WebKitMutationObserver;
_.test = function() {
return ee;
};
_.install = function(_) {
var ne = 0, ie = new ee(_), re = window.document.createTextNode("");
ie.observe(re, {
characterData: true
});
return function() {
re.data = ne = ++ne % 2;
};
};
}
}), require_messageChannel = __commonJS({
"node_modules/immediate/lib/messageChannel.js"(_) {
"use strict";
_.test = function() {
if (window.setImmediate) return false; else return "undefined" != typeof window.MessageChannel;
};
_.install = function(_) {
var ee = new window.MessageChannel;
ee.port1.onmessage = _;
return function() {
ee.port2.postMessage(0);
};
};
}
}), require_stateChange = __commonJS({
"node_modules/immediate/lib/stateChange.js"(_) {
"use strict";
_.test = function() {
return "document" in window && "onreadystatechange" in window.document.createElement("script");
};
_.install = function(_) {
return function() {
var ee = window.document.createElement("script");
ee.onreadystatechange = function() {
_();
ee.onreadystatechange = null;
ee.parentNode.removeChild(ee);
ee = null;
};
window.document.documentElement.appendChild(ee);
return _;
};
};
}
}), require_timeout = __commonJS({
"node_modules/immediate/lib/timeout.js"(_) {
"use strict";
_.test = function() {
return true;
};
_.install = function(_) {
return function() {
setTimeout(_, 0);
};
};
}
}), require_lib = __commonJS({
"node_modules/immediate/lib/index.js"(_, ee) {
"use strict";
var ne, ie, re, se = [ require_nextTick(), require_queueMicrotask(), require_mutation(), require_messageChannel(), require_stateChange(), require_timeout() ], oe = -1, le = [], ue = false;
function cleanUpNextTick() {
if (ne && ie) {
ne = false;
if (ie.length) le = ie.concat(le); else oe = -1;
if (le.length) nextTick();
}
}
function nextTick() {
if (!ne) {
ue = false;
ne = true;
for (var _ = le.length, ee = setTimeout(cleanUpNextTick); _; ) {
ie = le;
le = [];
for (;ie && ++oe < _; ) ie[oe].run();
oe = -1;
_ = le.length;
}
ie = null;
oe = -1;
ne = false;
clearTimeout(ee);
}
}
for (var de = -1, fe = se.length; ++de < fe; ) if (se[de] && se[de].test && se[de].test()) {
re = se[de].install(nextTick);
break;
}
function Item(_, ee) {
this.fun = _;
this.array = ee;
}
Item.prototype.run = function() {
var _ = this.fun, ee = this.array;
switch (ee.length) {
case 0:
return _();
case 1:
return _(ee[0]);
case 2:
return _(ee[0], ee[1]);
case 3:
return _(ee[0], ee[1], ee[2]);
default:
return _.apply(null, ee);
}
};
ee.exports = function immediate2(_) {
var ee = new Array(arguments.length - 1);
if (arguments.length > 1) for (var ie = 1; ie < arguments.length; ie++) ee[ie - 1] = arguments[ie];
le.push(new Item(_, ee));
if (!ue && !ne) {
ue = true;
re();
}
};
}
}), require_events = __commonJS({
"node_modules/events/events.js"(_, ee) {
"use strict";
var ne, ie = "object" == typeof Reflect ? Reflect : null, re = ie && "function" == typeof ie.apply ? ie.apply : function ReflectApply2(_, ee, ne) {
return Function.prototype.apply.call(_, ee, ne);
};
if (ie && "function" == typeof ie.ownKeys) ne = ie.ownKeys; else if (Object.getOwnPropertySymbols) ne = function ReflectOwnKeys2(_) {
return Object.getOwnPropertyNames(_).concat(Object.getOwnPropertySymbols(_));
}; else ne = function ReflectOwnKeys2(_) {
return Object.getOwnPropertyNames(_);
};
var se = Number.isNaN || function NumberIsNaN2(_) {
return _ != _;
};
function EventEmitter2() {
EventEmitter2.init.call(this);
}
ee.exports = EventEmitter2;
ee.exports.once = function once2(_, ee) {
return new Promise((function(ne, ie) {
function errorListener(ne) {
_.removeListener(ee, resolver);
ie(ne);
}
function resolver() {
if ("function" == typeof _.removeListener) _.removeListener("error", errorListener);
ne([].slice.call(arguments));
}
eventTargetAgnosticAddListener(_, ee, resolver, {
once: true
});
if ("error" !== ee) (function addErrorHandlerIfEventEmitter(_, ee, ne) {
if ("function" == typeof _.on) eventTargetAgnosticAddListener(_, "error", ee, ne);
})(_, errorListener, {
once: true
});
}));
};
EventEmitter2.EventEmitter = EventEmitter2;
EventEmitter2.prototype._events = void 0;
EventEmitter2.prototype._eventsCount = 0;
EventEmitter2.prototype._maxListeners = void 0;
var oe = 10;
function checkListener(_) {
if ("function" != typeof _) throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof _);
}
Object.defineProperty(EventEmitter2, "defaultMaxListeners", {
enumerable: true,
get: function() {
return oe;
},
set: function(_) {
if ("number" != typeof _ || _ < 0 || se(_)) throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + _ + ".");
oe = _;
}
});
EventEmitter2.init = function() {
if (void 0 === this._events || this._events === Object.getPrototypeOf(this)._events) {
this._events = Object.create(null);
this._eventsCount = 0;
}
this._maxListeners = this._maxListeners || void 0;
};
EventEmitter2.prototype.setMaxListeners = function setMaxListeners(_) {
if ("number" != typeof _ || _ < 0 || se(_)) throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + _ + ".");
this._maxListeners = _;
return this;
};
function _getMaxListeners(_) {
if (void 0 === _._maxListeners) return EventEmitter2.defaultMaxListeners; else return _._maxListeners;
}
EventEmitter2.prototype.getMaxListeners = function getMaxListeners() {
return _getMaxListeners(this);
};
EventEmitter2.prototype.emit = function emit2(_) {
for (var ee = [], ne = 1; ne < arguments.length; ne++) ee.push(arguments[ne]);
var ie = "error" === _, se = this._events;
if (void 0 !== se) ie = ie && void 0 === se.error; else if (!ie) return false;
if (ie) {
var oe;
if (ee.length > 0) oe = ee[0];
if (oe instanceof Error) throw oe;
var le = new Error("Unhandled error." + (oe ? " (" + oe.message + ")" : ""));
le.context = oe;
throw le;
}
var ue = se[_];
if (void 0 === ue) return false;
if ("function" == typeof ue) re(ue, this, ee); else {
var de = ue.length, fe = arrayClone(ue, de);
for (ne = 0; ne < de; ++ne) re(fe[ne], this, ee);
}
return true;
};
function _addListener(_, ee, ne, ie) {
var re, se, oe;
checkListener(ne);
if (void 0 === (se = _._events)) {
se = _._events = Object.create(null);
_._eventsCount = 0;
} else {
if (void 0 !== se.newListener) {
_.emit("newListener", ee, ne.listener ? ne.listener : ne);
se = _._events;
}
oe = se[ee];
}
if (void 0 === oe) {
oe = se[ee] = ne;
++_._eventsCount;
} else {
if ("function" == typeof oe) oe = se[ee] = ie ? [ ne, oe ] : [ oe, ne ]; else if (ie) oe.unshift(ne); else oe.push(ne);
if ((re = _getMaxListeners(_)) > 0 && oe.length > re && !oe.warned) {
oe.warned = true;
var le = new Error("Possible EventEmitter memory leak detected. " + oe.length + " " + String(ee) + " listeners added. Use emitter.setMaxListeners() to increase limit");
le.name = "MaxListenersExceededWarning";
le.emitter = _;
le.type = ee;
le.count = oe.length;
(function ProcessEmitWarning(_) {
if (console && console.warn) console.warn(_);
})(le);
}
}
return _;
}
EventEmitter2.prototype.addListener = function addListener(_, ee) {
return _addListener(this, _, ee, false);
};
EventEmitter2.prototype.on = EventEmitter2.prototype.addListener;
EventEmitter2.prototype.prependListener = function prependListener(_, ee) {
return _addListener(this, _, ee, true);
};
function onceWrapper() {
if (!this.fired) {
this.target.removeListener(this.type, this.wrapFn);
this.fired = true;
if (0 === arguments.length) return this.listener.call(this.target); else return this.listener.apply(this.target, arguments);
}
}
function _onceWrap(_, ee, ne) {
var ie = {
fired: false,
wrapFn: void 0,
target: _,
type: ee,
listener: ne
}, re = onceWrapper.bind(ie);
re.listener = ne;
ie.wrapFn = re;
return re;
}
EventEmitter2.prototype.once = function once3(_, ee) {
checkListener(ee);
this.on(_, _onceWrap(this, _, ee));
return this;
};
EventEmitter2.prototype.prependOnceListener = function prependOnceListener(_, ee) {
checkListener(ee);
this.prependListener(_, _onceWrap(this, _, ee));
return this;
};
EventEmitter2.prototype.removeListener = function removeListener(_, ee) {
var ne, ie, re, se, oe;
checkListener(ee);
if (void 0 === (ie = this._events)) return this;
if (void 0 === (ne = ie[_])) return this;
if (ne === ee || ne.listener === ee) if (0 == --this._eventsCount) this._events = Object.create(null); else {
delete ie[_];
if (ie.removeListener) this.emit("removeListener", _, ne.listener || ee);
} else if ("function" != typeof ne) {
re = -1;
for (se = ne.length - 1; se >= 0; se--) if (ne[se] === ee || ne[se].listener === ee) {
oe = ne[se].listener;
re = se;
break;
}
if (re < 0) return this;
if (0 === re) ne.shift(); else (function spliceOne(_, ee) {
for (;ee + 1 < _.length; ee++) _[ee] = _[ee + 1];
_.pop();
})(ne, re);
if (1 === ne.length) ie[_] = ne[0];
if (void 0 !== ie.removeListener) this.emit("removeListener", _, oe || ee);
}
return this;
};
EventEmitter2.prototype.off = EventEmitter2.prototype.removeListener;
EventEmitter2.prototype.removeAllListeners = function removeAllListeners(_) {
var ee, ne, ie;
if (void 0 === (ne = this._events)) return this;
if (void 0 === ne.removeListener) {
if (0 === arguments.length) {
this._events = Object.create(null);
this._eventsCount = 0;
} else if (void 0 !== ne[_]) if (0 == --this._eventsCount) this._events = Object.create(null); else delete ne[_];
return this;
}
if (0 === arguments.length) {
var re, se = Object.keys(ne);
for (ie = 0; ie < se.length; ++ie) if ("removeListener" !== (re = se[ie])) this.removeAllListeners(re);
this.removeAllListeners("removeListener");
this._events = Object.create(null);
this._eventsCount = 0;
return this;
}
if ("function" == typeof (ee = ne[_])) this.removeListener(_, ee); else if (void 0 !== ee) for (ie = ee.length - 1; ie >= 0; ie--) this.removeListener(_, ee[ie]);
return this;
};
function _listeners(_, ee, ne) {
var ie = _._events;
if (void 0 === ie) return [];
var re = ie[ee];
if (void 0 === re) return [];
if ("function" == typeof re) return ne ? [ re.listener || re ] : [ re ]; else return ne ? function unwrapListeners(_) {
for (var ee = new Array(_.length), ne = 0; ne < ee.length; ++ne) ee[ne] = _[ne].listener || _[ne];
return ee;
}(re) : arrayClone(re, re.length);
}
EventEmitter2.prototype.listeners = function listeners(_) {
return _listeners(this, _, true);
};
EventEmitter2.prototype.rawListeners = function rawListeners(_) {
return _listeners(this, _, false);
};
EventEmitter2.listenerCount = function(_, ee) {
if ("function" == typeof _.listenerCount) return _.listenerCount(ee); else return listenerCount2.call(_, ee);
};
EventEmitter2.prototype.listenerCount = listenerCount2;
function listenerCount2(_) {
var ee = this._events;
if (void 0 !== ee) {
var ne = ee[_];
if ("function" == typeof ne) return 1; else if (void 0 !== ne) return ne.length;
}
return 0;
}
EventEmitter2.prototype.eventNames = function eventNames() {
return this._eventsCount > 0 ? ne(this._events) : [];
};
function arrayClone(_, ee) {
for (var ne = new Array(ee), ie = 0; ie < ee; ++ie) ne[ie] = _[ie];
return ne;
}
function eventTargetAgnosticAddListener(_, ee, ne, ie) {
if ("function" == typeof _.on) if (ie.once) _.once(ee, ne); else _.on(ee, ne); else if ("function" == typeof _.addEventListener) _.addEventListener(ee, (function wrapListener(re) {
if (ie.once) _.removeEventListener(ee, wrapListener);
ne(re);
})); else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof _);
}
}
}), require_spark_md5 = __commonJS({
"node_modules/spark-md5/spark-md5.js"(_, ee) {
(function(ne) {
if ("object" == typeof _) ee.exports = ne(); else if ("function" == typeof define && define.amd) define(ne); else {
var ie;
try {
ie = window;
} catch (_) {
ie = self;
}
ie.SparkMD5 = ne();
}
})((function(_) {
"use strict";
var ee = [ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" ];
function md5cycle(_, ee) {
var ne = _[0], ie = _[1], re = _[2], se = _[3];
ie = ((ie += ((re = ((re += ((se = ((se += ((ne = ((ne += (ie & re | ~ie & se) + ee[0] - 680876936 | 0) << 7 | ne >>> 25) + ie | 0) & ie | ~ne & re) + ee[1] - 389564586 | 0) << 12 | se >>> 20) + ne | 0) & ne | ~se & ie) + ee[2] + 606105819 | 0) << 17 | re >>> 15) + se | 0) & se | ~re & ne) + ee[3] - 1044525330 | 0) << 22 | ie >>> 10) + re | 0;
ie = ((ie += ((re = ((re += ((se = ((se += ((ne = ((ne += (ie & re | ~ie & se) + ee[4] - 176418897 | 0) << 7 | ne >>> 25) + ie | 0) & ie | ~ne & re) + ee[5] + 1200080426 | 0) << 12 | se >>> 20) + ne | 0) & ne | ~se & ie) + ee[6] - 1473231341 | 0) << 17 | re >>> 15) + se | 0) & se | ~re & ne) + ee[7] - 45705983 | 0) << 22 | ie >>> 10) + re | 0;
ie = ((ie += ((re = ((re += ((se = ((se += ((ne = ((ne += (ie & re | ~ie & se) + ee[8] + 1770035416 | 0) << 7 | ne >>> 25) + ie | 0) & ie | ~ne & re) + ee[9] - 1958414417 | 0) << 12 | se >>> 20) + ne | 0) & ne | ~se & ie) + ee[10] - 42063 | 0) << 17 | re >>> 15) + se | 0) & se | ~re & ne) + ee[11] - 1990404162 | 0) << 22 | ie >>> 10) + re | 0;
ie = ((ie += ((re = ((re += ((se = ((se += ((ne = ((ne += (ie & re | ~ie & se) + ee[12] + 1804603682 | 0) << 7 | ne >>> 25) + ie | 0) & ie | ~ne & re) + ee[13] - 40341101 | 0) << 12 | se >>> 20) + ne | 0) & ne | ~se & ie) + ee[14] - 1502002290 | 0) << 17 | re >>> 15) + se | 0) & se | ~re & ne) + ee[15] + 1236535329 | 0) << 22 | ie >>> 10) + re | 0;
ie = ((ie += ((re = ((re += ((se = ((se += ((ne = ((ne += (ie & se | re & ~se) + ee[1] - 165796510 | 0) << 5 | ne >>> 27) + ie | 0) & re | ie & ~re) + ee[6] - 1069501632 | 0) << 9 | se >>> 23) + ne | 0) & ie | ne & ~ie) + ee[11] + 643717713 | 0) << 14 | re >>> 18) + se | 0) & ne | se & ~ne) + ee[0] - 373897302 | 0) << 20 | ie >>> 12) + re | 0;
ie = ((ie += ((re = ((re += ((se = ((se += ((ne = ((ne += (ie & se | re & ~se) + ee[5] - 701558691 | 0) << 5 | ne >>> 27) + ie | 0) & re | ie & ~re) + ee[10] + 38016083 | 0) << 9 | se >>> 23) + ne | 0) & ie | ne & ~ie) + ee[15] - 660478335 | 0) << 14 | re >>> 18) + se | 0) & ne | se & ~ne) + ee[4] - 405537848 | 0) << 20 | ie >>> 12) + re | 0;
ie = ((ie += ((re = ((re += ((se = ((se += ((ne = ((ne += (ie & se | re & ~se) + ee[9] + 568446438 | 0) << 5 | ne >>> 27) + ie | 0) & re | ie & ~re) + ee[14] - 1019803690 | 0) << 9 | se >>> 23) + ne | 0) & ie | ne & ~ie) + ee[3] - 187363961 | 0) << 14 | re >>> 18) + se | 0) & ne | se & ~ne) + ee[8] + 1163531501 | 0) << 20 | ie >>> 12) + re | 0;
ie = ((ie += ((re = ((re += ((se = ((se += ((ne = ((ne += (ie & se | re & ~se) + ee[13] - 1444681467 | 0) << 5 | ne >>> 27) + ie | 0) & re | ie & ~re) + ee[2] - 51403784 | 0) << 9 | se >>> 23) + ne | 0) & ie | ne & ~ie) + ee[7] + 1735328473 | 0) << 14 | re >>> 18) + se | 0) & ne | se & ~ne) + ee[12] - 1926607734 | 0) << 20 | ie >>> 12) + re | 0;
ie = ((ie += ((re = ((re += ((se = ((se += ((ne = ((ne += (ie ^ re ^ se) + ee[5] - 378558 | 0) << 4 | ne >>> 28) + ie | 0) ^ ie ^ re) + ee[8] - 2022574463 | 0) << 11 | se >>> 21) + ne | 0) ^ ne ^ ie) + ee[11] + 1839030562 | 0) << 16 | re >>> 16) + se | 0) ^ se ^ ne) + ee[14] - 35309556 | 0) << 23 | ie >>> 9) + re | 0;
ie = ((ie += ((re = ((re += ((se = ((se += ((ne = ((ne += (ie ^ re ^ se) + ee[1] - 1530992060 | 0) << 4 | ne >>> 28) + ie | 0) ^ ie ^ re) + ee[4] + 1272893353 | 0) << 11 | se >>> 21) + ne | 0) ^ ne ^ ie) + ee[7] - 155497632 | 0) << 16 | re >>> 16) + se | 0) ^ se ^ ne) + ee[10] - 1094730640 | 0) << 23 | ie >>> 9) + re | 0;
ie = ((ie += ((re = ((re += ((se = ((se += ((ne = ((ne += (ie ^ re ^ se) + ee[13] + 681279174 | 0) << 4 | ne >>> 28) + ie | 0) ^ ie ^ re) + ee[0] - 358537222 | 0) << 11 | se >>> 21) + ne | 0) ^ ne ^ ie) + ee[3] - 722521979 | 0) << 16 | re >>> 16) + se | 0) ^ se ^ ne) + ee[6] + 76029189 | 0) << 23 | ie >>> 9) + re | 0;
ie = ((ie += ((re = ((re += ((se = ((se += ((ne = ((ne += (ie ^ re ^ se) + ee[9] - 640364487 | 0) << 4 | ne >>> 28) + ie | 0) ^ ie ^ re) + ee[12] - 421815835 | 0) << 11 | se >>> 21) + ne | 0) ^ ne ^ ie) + ee[15] + 530742520 | 0) << 16 | re >>> 16) + se | 0) ^ se ^ ne) + ee[2] - 995338651 | 0) << 23 | ie >>> 9) + re | 0;
ie = ((ie += ((se = ((se += (ie ^ ((ne = ((ne += (re ^ (ie | ~se)) + ee[0] - 198630844 | 0) << 6 | ne >>> 26) + ie | 0) | ~re)) + ee[7] + 1126891415 | 0) << 10 | se >>> 22) + ne | 0) ^ ((re = ((re += (ne ^ (se | ~ie)) + ee[14] - 1416354905 | 0) << 15 | re >>> 17) + se | 0) | ~ne)) + ee[5] - 57434055 | 0) << 21 | ie >>> 11) + re | 0;
ie = ((ie += ((se = ((se += (ie ^ ((ne = ((ne += (re ^ (ie | ~se)) + ee[12] + 1700485571 | 0) << 6 | ne >>> 26) + ie | 0) | ~re)) + ee[3] - 1894986606 | 0) << 10 | se >>> 22) + ne | 0) ^ ((re = ((re += (ne ^ (se | ~ie)) + ee[10] - 1051523 | 0) << 15 | re >>> 17) + se | 0) | ~ne)) + ee[1] - 2054922799 | 0) << 21 | ie >>> 11) + re | 0;
ie = ((ie += ((se = ((se += (ie ^ ((ne = ((ne += (re ^ (ie | ~se)) + ee[8] + 1873313359 | 0) << 6 | ne >>> 26) + ie | 0) | ~re)) + ee[15] - 30611744 | 0) << 10 | se >>> 22) + ne | 0) ^ ((re = ((re += (ne ^ (se | ~ie)) + ee[6] - 1560198380 | 0) << 15 | re >>> 17) + se | 0) | ~ne)) + ee[13] + 1309151649 | 0) << 21 | ie >>> 11) + re | 0;
ie = ((ie += ((se = ((se += (ie ^ ((ne = ((ne += (re ^ (ie | ~se)) + ee[4] - 145523070 | 0) << 6 | ne >>> 26) + ie | 0) | ~re)) + ee[11] - 1120210379 | 0) << 10 | se >>> 22) + ne | 0) ^ ((re = ((re += (ne ^ (se | ~ie)) + ee[2] + 718787259 | 0) << 15 | re >>> 17) + se | 0) | ~ne)) + ee[9] - 343485551 | 0) << 21 | ie >>> 11) + re | 0;
_[0] = ne + _[0] | 0;
_[1] = ie + _[1] | 0;
_[2] = re + _[2] | 0;
_[3] = se + _[3] | 0;
}
function md5blk(_) {
var ee, ne = [];
for (ee = 0; ee < 64; ee += 4) ne[ee >> 2] = _.charCodeAt(ee) + (_.charCodeAt(ee + 1) << 8) + (_.charCodeAt(ee + 2) << 16) + (_.charCodeAt(ee + 3) << 24);
return ne;
}
function md5blk_array(_) {
var ee, ne = [];
for (ee = 0; ee < 64; ee += 4) ne[ee >> 2] = _[ee] + (_[ee + 1] << 8) + (_[ee + 2] << 16) + (_[ee + 3] << 24);
return ne;
}
function md51(_) {
var ee, ne, ie, re, se, oe, le = _.length, ue = [ 1732584193, -271733879, -1732584194, 271733878 ];
for (ee = 64; ee <= le; ee += 64) md5cycle(ue, md5blk(_.substring(ee - 64, ee)));
ne = (_ = _.substring(ee - 64)).length;
ie = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ];
for (ee = 0; ee < ne; ee += 1) ie[ee >> 2] |= _.charCodeAt(ee) << (ee % 4 << 3);
ie[ee >> 2] |= 128 << (ee % 4 << 3);
if (ee > 55) {
md5cycle(ue, ie);
for (ee = 0; ee < 16; ee += 1) ie[ee] = 0;
}
re = (re = 8 * le).toString(16).match(/(.*?)(.{0,8})$/);
se = parseInt(re[2], 16);
oe = parseInt(re[1], 16) || 0;
ie[14] = se;
ie[15] = oe;
md5cycle(ue, ie);
return ue;
}
function rhex(_) {
var ne, ie = "";
for (ne = 0; ne < 4; ne += 1) ie += ee[_ >> 8 * ne + 4 & 15] + ee[_ >> 8 * ne & 15];
return ie;
}
function hex(_) {
var ee;
for (ee = 0; ee < _.length; ee += 1) _[ee] = rhex(_[ee]);
return _.join("");
}
if ("5d41402abc4b2a76b9719d911017c592" !== hex(md51("hello"))) ;
if ("undefined" != typeof ArrayBuffer && !ArrayBuffer.prototype.slice) (function() {
function clamp(_, ee) {
if ((_ = 0 | _ || 0) < 0) return Math.max(_ + ee, 0); else return Math.min(_, ee);
}
ArrayBuffer.prototype.slice = function(ee, ne) {
var ie, re, se, oe, le = this.byteLength, ue = clamp(ee, le), de = le;
if (ne !== _) de = clamp(ne, le);
if (ue > de) return new ArrayBuffer(0);
ie = de - ue;
re = new ArrayBuffer(ie);
se = new Uint8Array(re);
oe = new Uint8Array(this, ue, ie);
se.set(oe);
return re;
};
})();
function toUtf85(_) {
if (/[\u0080-\uFFFF]/.test(_)) _ = unescape(encodeURIComponent(_));
return _;
}
function hexToBinaryString(_) {
var ee, ne = [], ie = _.length;
for (ee = 0; ee < ie - 1; ee += 2) ne.push(parseInt(_.substr(ee, 2), 16));
return String.fromCharCode.apply(String, ne);
}
function SparkMD5() {
this.reset();
}
SparkMD5.prototype.append = function(_) {
this.appendBinary(toUtf85(_));
return this;
};
SparkMD5.prototype.appendBinary = function(_) {
this._buff += _;
this._length += _.length;
var ee, ne = this._buff.length;
for (ee = 64; ee <= ne; ee += 64) md5cycle(this._hash, md5blk(this._buff.substring(ee - 64, ee)));
this._buff = this._buff.substring(ee - 64);
return this;
};
SparkMD5.prototype.end = function(_) {
var ee, ne, ie = this._buff, re = ie.length, se = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ];
for (ee = 0; ee < re; ee += 1) se[ee >> 2] |= ie.charCodeAt(ee) << (ee % 4 << 3);
this._finish(se, re);
ne = hex(this._hash);
if (_) ne = hexToBinaryString(ne);
this.reset();
return ne;
};
SparkMD5.prototype.reset = function() {
this._buff = "";
this._length = 0;
this._hash = [ 1732584193, -271733879, -1732584194, 271733878 ];
return this;
};
SparkMD5.prototype.getState = function() {
return {
buff: this._buff,
length: this._length,
hash: this._hash.slice()
};
};
SparkMD5.prototype.setState = function(_) {
this._buff = _.buff;
this._length = _.length;
this._hash = _.hash;
return this;
};
SparkMD5.prototype.destroy = function() {
delete this._hash;
delete this._buff;
delete this._length;
};
SparkMD5.prototype._finish = function(_, ee) {
var ne, ie, re, se = ee;
_[se >> 2] |= 128 << (se % 4 << 3);
if (se > 55) {
md5cycle(this._hash, _);
for (se = 0; se < 16; se += 1) _[se] = 0;
}
ne = (ne = 8 * this._length).toString(16).match(/(.*?)(.{0,8})$/);
ie = parseInt(ne[2], 16);
re = parseInt(ne[1], 16) || 0;
_[14] = ie;
_[15] = re;
md5cycle(this._hash, _);
};
SparkMD5.hash = function(_, ee) {
return SparkMD5.hashBinary(toUtf85(_), ee);
};
SparkMD5.hashBinary = function(_, ee) {
var ne = hex(md51(_));
return ee ? hexToBinaryString(ne) : ne;
};
SparkMD5.ArrayBuffer = function() {
this.reset();
};
SparkMD5.ArrayBuffer.prototype.append = function(_) {
var ee, ne = function concatenateArrayBuffers(_, ee, ne) {
var ie = new Uint8Array(_.byteLength + ee.byteLength);
ie.set(new Uint8Array(_));
ie.set(new Uint8Array(ee), _.byteLength);
return ne ? ie : ie.buffer;
}(this._buff.buffer, _, true), ie = ne.length;
this._length += _.byteLength;
for (ee = 64; ee <= ie; ee += 64) md5cycle(this._hash, md5blk_array(ne.subarray(ee - 64, ee)));
this._buff = ee - 64 < ie ? new Uint8Array(ne.buffer.slice(ee - 64)) : new Uint8Array(0);
return this;
};
SparkMD5.ArrayBuffer.prototype.end = function(_) {
var ee, ne, ie = this._buff, re = ie.length, se = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ];
for (ee = 0; ee < re; ee += 1) se[ee >> 2] |= ie[ee] << (ee % 4 << 3);
this._finish(se, re);
ne = hex(this._hash);
if (_) ne = hexToBinaryString(ne);
this.reset();
return ne;
};
SparkMD5.ArrayBuffer.prototype.reset = function() {
this._buff = new Uint8Array(0);
this._length = 0;
this._hash = [ 1732584193, -271733879, -1732584194, 271733878 ];
return this;
};
SparkMD5.ArrayBuffer.prototype.getState = function() {
var _ = SparkMD5.prototype.getState.call(this);
_.buff = function arrayBuffer2Utf8Str(_) {
return String.fromCharCode.apply(null, new Uint8Array(_));
}(_.buff);
return _;
};
SparkMD5.ArrayBuffer.prototype.setState = function(_) {
_.buff = function utf8Str2ArrayBuffer(_, ee) {
var ne, ie = _.length, re = new ArrayBuffer(ie), se = new Uint8Array(re);
for (ne = 0; ne < ie; ne += 1) se[ne] = _.charCodeAt(ne);
return ee ? se : re;
}(_.buff, true);
return SparkMD5.prototype.setState.call(this, _);
};
SparkMD5.ArrayBuffer.prototype.destroy = SparkMD5.prototype.destroy;
SparkMD5.ArrayBuffer.prototype._finish = SparkMD5.prototype._finish;
SparkMD5.ArrayBuffer.hash = function(_, ee) {
var ne = function md51_array(_) {
var ee, ne, ie, re, se, oe, le = _.length, ue = [ 1732584193, -271733879, -1732584194, 271733878 ];
for (ee = 64; ee <= le; ee += 64) md5cycle(ue, md5blk_array(_.subarray(ee - 64, ee)));
ne = (_ = ee - 64 < le ? _.subarray(ee - 64) : new Uint8Array(0)).length;
ie = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ];
for (ee = 0; ee < ne; ee += 1) ie[ee >> 2] |= _[ee] << (ee % 4 << 3);
ie[ee >> 2] |= 128 << (ee % 4 << 3);
if (ee > 55) {
md5cycle(ue, ie);
for (ee = 0; ee < 16; ee += 1) ie[ee] = 0;
}
re = (re = 8 * le).toString(16).match(/(.*?)(.{0,8})$/);
se = parseInt(re[2], 16);
oe = parseInt(re[1], 16) || 0;
ie[14] = se;
ie[15] = oe;
md5cycle(ue, ie);
return ue;
}(new Uint8Array(_)), ie = hex(ne);
return ee ? hexToBinaryString(ie) : ie;
};
return SparkMD5;
}));
}
}), require_vuvuzela = __commonJS({
"node_modules/vuvuzela/index.js"(_) {
"use strict";
_.stringify = function stringify3(_) {
var ee = [];
ee.push({
obj: _
});
for (var ne, ie, re, se, oe, le, ue, de, fe, he, pe = ""; ne = ee.pop(); ) {
ie = ne.obj;
pe += ne.prefix || "";
if (re = ne.val || "") pe += re; else if ("object" != typeof ie) pe += "undefined" == typeof ie ? null : JSON.stringify(ie); else if (null === ie) pe += "null"; else if (Array.isArray(ie)) {
ee.push({
val: "]"
});
for (se = ie.length - 1; se >= 0; se--) {
oe = 0 === se ? "" : ",";
ee.push({
obj: ie[se],
prefix: oe
});
}
ee.push({
val: "["
});
} else {
le = [];
for (ue in ie) if (ie.hasOwnProperty(ue)) le.push(ue);
ee.push({
val: "}"
});
for (se = le.length - 1; se >= 0; se--) {
fe = ie[de = le[se]];
he = se > 0 ? "," : "";
he += JSON.stringify(de) + ":";
ee.push({
obj: fe,
prefix: he
});
}
ee.push({
val: "{"
});
}
}
return pe;
};
function pop2(_, ee, ne) {
var ie = ne[ne.length - 1];
if (_ === ie.element) {
ne.pop();
ie = ne[ne.length - 1];
}
var re = ie.element, se = ie.index;
if (Array.isArray(re)) re.push(_); else if (se === ee.length - 2) re[ee.pop()] = _; else ee.push(_);
}
_.parse = function(_) {
for (var ee, ne, ie, re, se, oe, le, ue, de, fe = [], he = [], pe = 0; ;) {
if ("}" === (ee = _[pe++]) || "]" === ee || "undefined" == typeof ee) if (1 === fe.length) return fe.pop(); else {
pop2(fe.pop(), fe, he);
continue;
}
switch (ee) {
case " ":
case "\t":
case "\n":
case ":":
case ",":
break;
case "n":
pe += 3;
pop2(null, fe, he);
break;
case "t":
pe += 3;
pop2(true, fe, he);
break;
case "f":
pe += 4;
pop2(false, fe, he);
break;
case "0":
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "8":
case "9":
case "-":
ne = "";
pe--;
for (;;) {
ie = _[pe++];
if (/[\d\.\-e\+]/.test(ie)) ne += ie; else {
pe--;
break;
}
}
pop2(parseFloat(ne), fe, he);
break;
case '"':
re = "";
se = void 0;
oe = 0;
for (;'"' !== (le = _[pe++]) || "\\" === se && oe % 2 == 1; ) {
re += le;
if ("\\" === (se = le)) oe++; else oe = 0;
}
pop2(JSON.parse('"' + re + '"'), fe, he);
break;
case "[":
ue = {
element: [],
index: fe.length
};
fe.push(ue.element);
he.push(ue);
break;
case "{":
de = {
element: {},
index: fe.length
};
fe.push(de.element);
he.push(de);
break;
default:
throw new Error("unexpectedly reached end of input: " + ee);
}
}
};
}
}), require_pouchdb_wrappers = __commonJS({
"node_modules/pouchdb-wrappers/index.js"(_, ee) {
"use strict";
function replacementMethod(_, ee) {
return function(...ne) {
function doMethod() {
let ie = null;
const re = "query" === ee ? 1 : 0;
if (ne.length > re && "function" == typeof ne[ne.length - 1]) ie = ne.pop();
let se = _._originals[ee].bind(_);
for (const ne of _._handlers[ee]) se = ne.bind(_, se);
const oe = se(...ne);
if (oe.then && ie) (function nodify(_, ee) {
_.then(((..._) => {
ee(null, ..._);
})).catch((_ => {
ee(_);
}));
})(oe, ie);
return oe;
}
if ("changes" !== ee && _.taskqueue && !_.taskqueue.isReady) return new Promise(((ee, ne) => {
_.taskqueue.addTask((_ => {
if (_) ne(_); else ee();
}));
})).then(doMethod); else return doMethod();
};
}
var ne = {
install: function installWrappers(_, ee = {}) {
if (!_._originals || !_._handlers) {
_._originals = {};
_._handlers = {};
}
for (const [ne, ie] of Object.entries(ee)) {
if (!(ne in _)) throw new Error(`Method '${ne}' does not exist on given base, so it cannot be wrapped.`);
if (!(ne in _._originals)) _._originals[ne] = _[ne];
if (ne in _._handlers) _._handlers[ne].unshift(ie); else {
_._handlers[ne] = [ ie ];
_[ne] = replacementMethod(_, ne);
}
}
},
uninstall: function uninstallWrappers(_, ee) {
if (!_._originals || !_._handlers) throw new Error("No wrapper methods installed, so no methods can be uninstalled.");
for (const [ne, ie] of Object.entries(ee)) {
const ee = `Wrapper method for '${ne}' not installed: ${ie.toString()}`;
if (!(ne in _._handlers)) throw new Error(ee);
const re = _._handlers[ne].indexOf(ie);
if (-1 === re) throw new Error(ee); else _._handlers[ne].splice(re, 1);
}
}
};
try {
ee.exports = ne;
} catch (_) {}
try {
window.PouchDBWrappers = ne;
} catch (_) {}
}
}), require_transform_pouch = __commonJS({
"node_modules/transform-pouch/index.js"(_, ee) {
"use strict";
var ne = require_pouchdb_wrappers();
function isntInternalKey(_) {
return "_" !== _[0];
}
function isUntransformable(_) {
if ("string" == typeof _._id && /^_local/.test(_._id)) return true;
if (_._deleted) return 0 === Object.keys(_).filter(isntInternalKey).length; else return false;
}
ee.exports = {
transform: transform2,
filter: transform2
};
function transform2(_) {
const incoming = function(ee) {
if (!isUntransformable(ee) && _.incoming) return _.incoming(ee); else return ee;
}, outgoing = function(ee) {
if (!isUntransformable(ee) && _.outgoing) return _.outgoing(ee); else return ee;
}, ee = {
async get(_, ...ee) {
const ne = await _(...ee);
if (Array.isArray(ne)) {
await Promise.all(ne.map((async _ => {
if (_.ok) _.ok = await outgoing(_.ok);
})));
return ne;
} else return outgoing(ne);
},
async bulkDocs(_, ee, ...ne) {
if (ee.docs) ee.docs = await Promise.all(ee.docs.map(incoming)); else ee = await Promise.all(ee.map(incoming));
return _(ee, ...ne);
},
async allDocs(_, ...ee) {
const ne = await _(...ee);
await Promise.all(ne.rows.map((async _ => {
if (_.doc) _.doc = await outgoing(_.doc);
})));
return ne;
},
async bulkGet(_, ...ee) {
const mapDoc = async _ => {
if (_.ok) return {
ok: await outgoing(_.ok)
}; else return _;
};
let {results: ne, ...ie} = await _(...ee);
ne = await Promise.all(ne.map((async _ => {
const {id: ee, docs: ne} = _;
if (ee && ne && Array.isArray(ne)) return {
id: ee,
docs: await Promise.all(ne.map(mapDoc))
}; else return _;
})));
return {
results: ne,
...ie
};
},
changes(_, ...ee) {
async function modifyChange(_) {
if (_.doc) {
_.doc = await outgoing(_.doc);
return _;
}
return _;
}
async function modifyChanges(_) {
if (_.results) {
_.results = await Promise.all(_.results.map(modifyChange));
return _;
}
return _;
}
const ne = _(...ee), {on: ie, then: re} = ne;
return Object.assign(ne, {
on(_, ee) {
const re = ee;
if ("change" === _) ee = async _ => {
re(await modifyChange(_));
}; else if ("complete" === _) ee = async _ => {
re(await modifyChanges(_));
};
return ie.call(ne, _, ee);
},
then: (_, ee) => re.call(ne, modifyChanges).then(_, ee)
});
}
};
if ("http" === this.type()) {
ee.put = async function(_, ee, ...ne) {
return _(ee = await incoming(ee), ...ne);
};
ee.query = async function(_, ...ee) {
const ne = await _(...ee);
await Promise.all(ne.rows.map((async _ => {
if (_.doc) _.doc = await outgoing(_.doc);
})));
return ne;
};
}
ne.install(this, ee);
}
if ("undefined" != typeof window && window.PouchDB) window.PouchDB.plugin(_);
}
}), require_util = __commonJS({
"node_modules/fast-xml-parser/src/util.js"(_) {
"use strict";
var ee = ":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD", ne = "[" + ee + "][" + ee + "\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*", ie = new RegExp("^" + ne + "$");
_.isExist = function(_) {
return "undefined" != typeof _;
};
_.isEmptyObject = function(_) {
return 0 === Object.keys(_).length;
};
_.merge = function(_, ee, ne) {
if (ee) {
const ie = Object.keys(ee), re = ie.length;
for (let se = 0; se < re; se++) if ("strict" === ne) _[ie[se]] = [ ee[ie[se]] ]; else _[ie[se]] = ee[ie[se]];
}
};
_.getValue = function(ee) {
if (_.isExist(ee)) return ee; else return "";
};
_.isName = function(_) {
const ee = ie.exec(_);
return !(null === ee || "undefined" == typeof ee);
};
_.getAllMatches = function(_, ee) {
const ne = [];
let ie = ee.exec(_);
for (;ie; ) {
const re = [];
re.startIndex = ee.lastIndex - ie[0].length;
const se = ie.length;
for (let _ = 0; _ < se; _++) re.push(ie[_]);
ne.push(re);
ie = ee.exec(_);
}
return ne;
};
_.nameRegexp = ne;
}
}), require_validator = __commonJS({
"node_modules/fast-xml-parser/src/validator.js"(_) {
"use strict";
var ee = require_util(), ne = {
allowBooleanAttributes: false,
unpairedTags: []
};
_.validate = function(_, ie) {
ie = Object.assign({}, ne, ie);
const re = [];
let se = false, oe = false;
if ("\ufeff" === _[0]) _ = _.substr(1);
for (let ne = 0; ne < _.length; ne++) if ("<" === _[ne] && "?" === _[ne + 1]) {
ne += 2;
ne = readPI(_, ne);
if (ne.err) return ne;
} else if ("<" === _[ne]) {
let ue = ne;
ne++;
if ("!" === _[ne]) {
ne = readCommentAndCDATA(_, ne);
continue;
} else {
let de = false;
if ("/" === _[ne]) {
de = true;
ne++;
}
let fe = "";
for (;ne < _.length && ">" !== _[ne] && " " !== _[ne] && "\t" !== _[ne] && "\n" !== _[ne] && "\r" !== _[ne]; ne++) fe += _[ne];
fe = fe.trim();
if ("/" === fe[fe.length - 1]) {
fe = fe.substring(0, fe.length - 1);
ne--;
}
if (!(le = fe, ee.isName(le))) {
let ee;
if (0 === fe.trim().length) ee = "Invalid space after '<'."; else ee = "Tag '" + fe + "' is an invalid name.";
return getErrorObject("InvalidTag", ee, getLineNumberForPosition(_, ne));
}
const he = readAttributeStr(_, ne);
if (false === he) return getErrorObject("InvalidAttr", "Attributes for '" + fe + "' have open quote.", getLineNumberForPosition(_, ne));
let pe = he.value;
ne = he.index;
if ("/" === pe[pe.length - 1]) {
const ee = ne - pe.length;
pe = pe.substring(0, pe.length - 1);
const re = validateAttributeString(pe, ie);
if (true === re) se = true; else return getErrorObject(re.err.code, re.err.msg, getLineNumberForPosition(_, ee + re.err.line));
} else if (de) if (!he.tagClosed) return getErrorObject("InvalidTag", "Closing tag '" + fe + "' doesn't have proper closing.", getLineNumberForPosition(_, ne)); else if (pe.trim().length > 0) return getErrorObject("InvalidTag", "Closing tag '" + fe + "' can't have attributes or invalid starting.", getLineNumberForPosition(_, ue)); else {
const ee = re.pop();
if (fe !== ee.tagName) {
let ne = getLineNumberForPosition(_, ee.tagStartPos);
return getErrorObject("InvalidTag", "Expected closing tag '" + ee.tagName + "' (opened in line " + ne.line + ", col " + ne.col + ") instead of closing tag '" + fe + "'.", getLineNumberForPosition(_, ue));
}
if (0 == re.length) oe = true;
} else {
const ee = validateAttributeString(pe, ie);
if (true !== ee) return getErrorObject(ee.err.code, ee.err.msg, getLineNumberForPosition(_, ne - pe.length + ee.err.line));
if (true === oe) return getErrorObject("InvalidXml", "Multiple possible root nodes found.", getLineNumberForPosition(_, ne)); else if (-1 !== ie.unpairedTags.indexOf(fe)) ; else re.push({
tagName: fe,
tagStartPos: ue
});
se = true;
}
for (ne++; ne < _.length; ne++) if ("<" === _[ne]) if ("!" === _[ne + 1]) {
ne++;
ne = readCommentAndCDATA(_, ne);
continue;
} else if ("?" === _[ne + 1]) {
ne = readPI(_, ++ne);
if (ne.err) return ne;
} else break; else if ("&" === _[ne]) {
const ee = validateAmpersand(_, ne);
if (-1 == ee) return getErrorObject("InvalidChar", "char '&' is not expected.", getLineNumberForPosition(_, ne));
ne = ee;
} else if (true === oe && !isWhiteSpace(_[ne])) return getErrorObject("InvalidXml", "Extra text at the end", getLineNumberForPosition(_, ne));
if ("<" === _[ne]) ne--;
}
} else {
if (isWhiteSpace(_[ne])) continue;
return getErrorObject("InvalidChar", "char '" + _[ne] + "' is not expected.", getLineNumberForPosition(_, ne));
}
var le;
if (!se) return getErrorObject("InvalidXml", "Start tag expected.", 1); else if (1 == re.length) return getErrorObject("InvalidTag", "Unclosed tag '" + re[0].tagName + "'.", getLineNumberForPosition(_, re[0].tagStartPos)); else if (re.length > 0) return getErrorObject("InvalidXml", "Invalid '" + JSON.stringify(re.map((_ => _.tagName)), null, 4).replace(/\r?\n/g, "") + "' found.", {
line: 1,
col: 1
});
return true;
};
function isWhiteSpace(_) {
return " " === _ || "\t" === _ || "\n" === _ || "\r" === _;
}
function readPI(_, ee) {
const ne = ee;
for (;ee < _.length; ee++) if ("?" == _[ee] || " " == _[ee]) {
const ie = _.substr(ne, ee - ne);
if (ee > 5 && "xml" === ie) return getErrorObject("InvalidXml", "XML declaration allowed only at the start of the document.", getLineNumberForPosition(_, ee)); else if ("?" == _[ee] && ">" == _[ee + 1]) {
ee++;
break;
} else continue;
}
return ee;
}
function readCommentAndCDATA(_, ee) {
if (_.length > ee + 5 && "-" === _[ee + 1] && "-" === _[ee + 2]) {
for (ee += 3; ee < _.length; ee++) if ("-" === _[ee] && "-" === _[ee + 1] && ">" === _[ee + 2]) {
ee += 2;
break;
}
} else if (_.length > ee + 8 && "D" === _[ee + 1] && "O" === _[ee + 2] && "C" === _[ee + 3] && "T" === _[ee + 4] && "Y" === _[ee + 5] && "P" === _[ee + 6] && "E" === _[ee + 7]) {
let ne = 1;
for (ee += 8; ee < _.length; ee++) if ("<" === _[ee]) ne++; else if (">" === _[ee]) {
ne--;
if (0 === ne) break;
}
} else if (_.length > ee + 9 && "[" === _[ee + 1] && "C" === _[ee + 2] && "D" === _[ee + 3] && "A" === _[ee + 4] && "T" === _[ee + 5] && "A" === _[ee + 6] && "[" === _[ee + 7]) for (ee += 8; ee < _.length; ee++) if ("]" === _[ee] && "]" === _[ee + 1] && ">" === _[ee + 2]) {
ee += 2;
break;
}
return ee;
}
function readAttributeStr(_, ee) {
let ne = "", ie = "", re = false;
for (;ee < _.length; ee++) {
if ('"' === _[ee] || "'" === _[ee]) if ("" === ie) ie = _[ee]; else if (ie !== _[ee]) ; else ie = ""; else if (">" === _[ee]) if ("" === ie) {
re = true;
break;
}
ne += _[ee];
}
if ("" !== ie) return false; else return {
value: ne,
index: ee,
tagClosed: re
};
}
var ie = new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?", "g");
function validateAttributeString(_, ne) {
const re = ee.getAllMatches(_, ie), se = {};
for (let _ = 0; _ < re.length; _++) {
if (0 === re[_][1].length) return getErrorObject("InvalidAttr", "Attribute '" + re[_][2] + "' has no space in starting.", getPositionFromMatch(re[_])); else if (void 0 !== re[_][3] && void 0 === re[_][4]) return getErrorObject("InvalidAttr", "Attribute '" + re[_][2] + "' is without value.", getPositionFromMatch(re[_])); else if (void 0 === re[_][3] && !ne.allowBooleanAttributes) return getErrorObject("InvalidAttr", "boolean attribute '" + re[_][2] + "' is not allowed.", getPositionFromMatch(re[_]));
const ee = re[_][2];
if (!validateAttrName(ee)) return getErrorObject("InvalidAttr", "Attribute '" + ee + "' is an invalid name.", getPositionFromMatch(re[_]));
if (!se.hasOwnProperty(ee)) se[ee] = 1; else return getErrorObject("InvalidAttr", "Attribute '" + ee + "' is repeated.", getPositionFromMatch(re[_]));
}
return true;
}
function validateAmpersand(_, ee) {
if (";" === _[++ee]) return -1;
if ("#" === _[ee]) return function validateNumberAmpersand(_, ee) {
let ne = /\d/;
if ("x" === _[ee]) {
ee++;
ne = /[\da-fA-F]/;
}
for (;ee < _.length; ee++) {
if (";" === _[ee]) return ee;
if (!_[ee].match(ne)) break;
}
return -1;
}(_, ++ee);
let ne = 0;
for (;ee < _.length; ee++, ne++) if (!(_[ee].match(/\w/) && ne < 20)) {
if (";" === _[ee]) break;
return -1;
}
return ee;
}
function getErrorObject(_, ee, ne) {
return {
err: {
code: _,
msg: ee,
line: ne.line || ne,
col: ne.col
}
};
}
function validateAttrName(_) {
return ee.isName(_);
}
function getLineNumberForPosition(_, ee) {
const ne = _.substring(0, ee).split(/\r?\n/);
return {
line: ne.length,
col: ne[ne.length - 1].length + 1
};
}
function getPositionFromMatch(_) {
return _.startIndex + _[1].length;
}
}
}), require_OptionsBuilder = __commonJS({
"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(_) {
var ee = {
preserveOrder: false,
attributeNamePrefix: "@_",
attributesGroupName: false,
textNodeName: "#text",
ignoreAttributes: true,
removeNSPrefix: false,
allowBooleanAttributes: false,
parseTagValue: true,
parseAttributeValue: false,
trimValues: true,
cdataPropName: false,
numberParseOptions: {
hex: true,
leadingZeros: true,
eNotation: true
},
tagValueProcessor: function(_, ee) {
return ee;
},
attributeValueProcessor: function(_, ee) {
return ee;
},
stopNodes: [],
alwaysCreateTextNode: false,
isArray: () => false,
commentPropName: false,
unpairedTags: [],
processEntities: true,
htmlEntities: false,
ignoreDeclaration: false,
ignorePiTags: false,
transformTagName: false,
transformAttributeName: false,
updateTag: function(_, ee, ne) {
return _;
}
};
_.buildOptions = function(_) {
return Object.assign({}, ee, _);
};
_.defaultOptions = ee;
}
}), require_xmlNode = __commonJS({
"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(_, ee) {
"use strict";
ee.exports = class {
constructor(_) {
this.tagname = _;
this.child = [];
this[":@"] = {};
}
add(_, ee) {
if ("__proto__" === _) _ = "#__proto__";
this.child.push({
[_]: ee
});
}
addChild(_) {
if ("__proto__" === _.tagname) _.tagname = "#__proto__";
if (_[":@"] && Object.keys(_[":@"]).length > 0) this.child.push({
[_.tagname]: _.child,
[":@"]: _[":@"]
}); else this.child.push({
[_.tagname]: _.child
});
}
};
}
}), require_DocTypeReader = __commonJS({
"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(_, ee) {
var ne = require_util();
function readEntityExp(_, ee) {
let ne = "";
for (;ee < _.length && "'" !== _[ee] && '"' !== _[ee]; ee++) ne += _[ee];
ne = ne.trim();
if (-1 !== ne.indexOf(" ")) throw new Error("External entites are not supported");
const ie = _[ee++];
let re = "";
for (;ee < _.length && _[ee] !== ie; ee++) re += _[ee];
return [ ne, re, ee ];
}
function isComment(_, ee) {
if ("!" === _[ee + 1] && "-" === _[ee + 2] && "-" === _[ee + 3]) return true; else return false;
}
function isEntity(_, ee) {
if ("!" === _[ee + 1] && "E" === _[ee + 2] && "N" === _[ee + 3] && "T" === _[ee + 4] && "I" === _[ee + 5] && "T" === _[ee + 6] && "Y" === _[ee + 7]) return true; else return false;
}
function isElement(_, ee) {
if ("!" === _[ee + 1] && "E" === _[ee + 2] && "L" === _[ee + 3] && "E" === _[ee + 4] && "M" === _[ee + 5] && "E" === _[ee + 6] && "N" === _[ee + 7] && "T" === _[ee + 8]) return true; else return false;
}
function isAttlist(_, ee) {
if ("!" === _[ee + 1] && "A" === _[ee + 2] && "T" === _[ee + 3] && "T" === _[ee + 4] && "L" === _[ee + 5] && "I" === _[ee + 6] && "S" === _[ee + 7] && "T" === _[ee + 8]) return true; else return false;
}
function isNotation(_, ee) {
if ("!" === _[ee + 1] && "N" === _[ee + 2] && "O" === _[ee + 3] && "T" === _[ee + 4] && "A" === _[ee + 5] && "T" === _[ee + 6] && "I" === _[ee + 7] && "O" === _[ee + 8] && "N" === _[ee + 9]) return true; else return false;
}
function validateEntityName(_) {
if (ne.isName(_)) return _; else throw new Error(`Invalid entity name ${_}`);
}
ee.exports = function readDocType(_, ee) {
const ne = {};
if ("O" === _[ee + 3] && "C" === _[ee + 4] && "T" === _[ee + 5] && "Y" === _[ee + 6] && "P" === _[ee + 7] && "E" === _[ee + 8]) {
ee += 9;
let ie = 1, re = false, se = false, oe = "";
for (;ee < _.length; ee++) if ("<" === _[ee] && !se) {
if (re && isEntity(_, ee)) {
ee += 7;
[entityName, val, ee] = readEntityExp(_, ee + 1);
if (-1 === val.indexOf("&")) ne[validateEntityName(entityName)] = {
regx: RegExp(`&${entityName};`, "g"),
val
};
} else if (re && isElement(_, ee)) ee += 8; else if (re && isAttlist(_, ee)) ee += 8; else if (re && isNotation(_, ee)) ee += 9; else if (isComment) se = true; else throw new Error("Invalid DOCTYPE");
ie++;
oe = "";
} else if (">" === _[ee]) {
if (se) {
if ("-" === _[ee - 1] && "-" === _[ee - 2]) {
se = false;
ie--;
}
} else ie--;
if (0 === ie) break;
} else if ("[" === _[ee]) re = true; else oe += _[ee];
if (0 !== ie) throw new Error("Unclosed DOCTYPE");
} else throw new Error("Invalid Tag instead of DOCTYPE");
return {
entities: ne,
i: ee
};
};
}
}), require_strnum = __commonJS({
"node_modules/strnum/strnum.js"(_, ee) {
var ne = /^[-+]?0x[a-fA-F0-9]+$/, ie = /^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;
if (!Number.parseInt && window.parseInt) Number.parseInt = window.parseInt;
if (!Number.parseFloat && window.parseFloat) Number.parseFloat = window.parseFloat;
var re = {
hex: true,
leadingZeros: true,
decimalPoint: ".",
eNotation: true
};
ee.exports = function toNumber(_, ee = {}) {
ee = Object.assign({}, re, ee);
if (!_ || "string" != typeof _) return _;
let se = _.trim();
if (void 0 !== ee.skipLike && ee.skipLike.test(se)) return _; else if (ee.hex && ne.test(se)) return Number.parseInt(se, 16); else {
const ne = ie.exec(se);
if (ne) {
const ie = ne[1], re = ne[2];
let oe = function trimZeros(_) {
if (_ && -1 !== _.indexOf(".")) {
if ("." === (_ = _.replace(/0+$/, ""))) _ = "0"; else if ("." === _[0]) _ = "0" + _; else if ("." === _[_.length - 1]) _ = _.substr(0, _.length - 1);
return _;
}
return _;
}(ne[3]);
const le = ne[4] || ne[6];
if (!ee.leadingZeros && re.length > 0 && ie && "." !== se[2]) return _; else if (!ee.leadingZeros && re.length > 0 && !ie && "." !== se[1]) return _; else {
const ne = Number(se), ue = "" + ne;
if (-1 !== ue.search(/[eE]/)) if (ee.eNotation) return ne; else return _; else if (le) if (ee.eNotation) return ne; else return _; else if (-1 !== se.indexOf(".")) if ("0" === ue && "" === oe) return ne; else if (ue === oe) return ne; else if (ie && ue === "-" + oe) return ne; else return _;
if (re) if (oe === ue) return ne; else if (ie + oe === ue) return ne; else return _;
if (se === ue) return ne; else if (se === ie + ue) return ne;
return _;
}
} else return _;
}
};
}
}), require_OrderedObjParser = __commonJS({
"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(_, ee) {
"use strict";
var ne = require_util(), ie = require_xmlNode(), re = require_DocTypeReader(), se = require_strnum();
"<((!\\[CDATA\\[([\\s\\S]*?)(]]>))|((NAME:)?(NAME))([^>]*)>|((\\/)(NAME)\\s*>))([^<]*)".replace(/NAME/g, ne.nameRegexp);
function addExternalEntities(_) {
const ee = Object.keys(_);
for (let ne = 0; ne < ee.length; ne++) {
const ie = ee[ne];
this.lastEntities[ie] = {
regex: new RegExp("&" + ie + ";", "g"),
val: _[ie]
};
}
}
function parseTextData(_, ee, ne, ie, re, se, oe) {
if (void 0 !== _) {
if (this.options.trimValues && !ie) _ = _.trim();
if (_.length > 0) {
if (!oe) _ = this.replaceEntitiesValue(_);
const ie = this.options.tagValueProcessor(ee, _, ne, re, se);
if (null == ie) return _; else if (typeof ie != typeof _ || ie !== _) return ie; else if (this.options.trimValues) return parseValue(_, this.options.parseTagValue, this.options.numberParseOptions); else if (_.trim() === _) return parseValue(_, this.options.parseTagValue, this.options.numberParseOptions); else return _;
}
}
}
function resolveNameSpace(_) {
if (this.options.removeNSPrefix) {
const ee = _.split(":"), ne = "/" === _.charAt(0) ? "/" : "";
if ("xmlns" === ee[0]) return "";
if (2 === ee.length) _ = ne + ee[1];
}
return _;
}
var oe = new RegExp("([^\\s=]+)\\s*(=\\s*(['\"])([\\s\\S]*?)\\3)?", "gm");
function buildAttributesMap(_, ee, ie) {
if (!this.options.ignoreAttributes && "string" == typeof _) {
const ie = ne.getAllMatches(_, oe), re = ie.length, se = {};
for (let _ = 0; _ < re; _++) {
const ne = this.resolveNameSpace(ie[_][1]);
let re = ie[_][4], oe = this.options.attributeNamePrefix + ne;
if (ne.length) {
if (this.options.transformAttributeName) oe = this.options.transformAttributeName(oe);
if ("__proto__" === oe) oe = "#__proto__";
if (void 0 !== re) {
if (this.options.trimValues) re = re.trim();
re = this.replaceEntitiesValue(re);
const _ = this.options.attributeValueProcessor(ne, re, ee);
if (null == _) se[oe] = re; else if (typeof _ != typeof re || _ !== re) se[oe] = _; else se[oe] = parseValue(re, this.options.parseAttributeValue, this.options.numberParseOptions);
} else if (this.options.allowBooleanAttributes) se[oe] = true;
}
}
if (!Object.keys(se).length) return;
if (this.options.attributesGroupName) {
const _ = {};
_[this.options.attributesGroupName] = se;
return _;
}
return se;
}
}
var parseXml = function(_) {
_ = _.replace(/\r\n?/g, "\n");
const ee = new ie("!xml");
let ne = ee, se = "", oe = "";
for (let le = 0; le < _.length; le++) if ("<" === _[le]) if ("/" === _[le + 1]) {
const ee = findClosingIndex(_, ">", le, "Closing Tag is not closed.");
let ie = _.substring(le + 2, ee).trim();
if (this.options.removeNSPrefix) {
const _ = ie.indexOf(":");
if (-1 !== _) ie = ie.substr(_ + 1);
}
if (this.options.transformTagName) ie = this.options.transformTagName(ie);
if (ne) se = this.saveTextToParentTag(se, ne, oe);
const re = oe.substring(oe.lastIndexOf(".") + 1);
if (ie && -1 !== this.options.unpairedTags.indexOf(ie)) throw new Error(`Unpaired tag can not be used as closing tag: ${ie}>`);
let ue = 0;
if (re && -1 !== this.options.unpairedTags.indexOf(re)) {
ue = oe.lastIndexOf(".", oe.lastIndexOf(".") - 1);
this.tagsNodeStack.pop();
} else ue = oe.lastIndexOf(".");
oe = oe.substring(0, ue);
ne = this.tagsNodeStack.pop();
se = "";
le = ee;
} else if ("?" === _[le + 1]) {
let ee = readTagExp(_, le, false, "?>");
if (!ee) throw new Error("Pi Tag is not closed.");
se = this.saveTextToParentTag(se, ne, oe);
if (this.options.ignoreDeclaration && "?xml" === ee.tagName || this.options.ignorePiTags) ; else {
const _ = new ie(ee.tagName);
_.add(this.options.textNodeName, "");
if (ee.tagName !== ee.tagExp && ee.attrExpPresent) _[":@"] = this.buildAttributesMap(ee.tagExp, oe, ee.tagName);
this.addChild(ne, _, oe);
}
le = ee.closeIndex + 1;
} else if ("!--" === _.substr(le + 1, 3)) {
const ee = findClosingIndex(_, "--\x3e", le + 4, "Comment is not closed.");
if (this.options.commentPropName) {
const ie = _.substring(le + 4, ee - 2);
se = this.saveTextToParentTag(se, ne, oe);
ne.add(this.options.commentPropName, [ {
[this.options.textNodeName]: ie
} ]);
}
le = ee;
} else if ("!D" === _.substr(le + 1, 2)) {
const ee = re(_, le);
this.docTypeEntities = ee.entities;
le = ee.i;
} else if ("![" === _.substr(le + 1, 2)) {
const ee = findClosingIndex(_, "]]>", le, "CDATA is not closed.") - 2, ie = _.substring(le + 9, ee);
se = this.saveTextToParentTag(se, ne, oe);
if (this.options.cdataPropName) ne.add(this.options.cdataPropName, [ {
[this.options.textNodeName]: ie
} ]); else {
let _ = this.parseTextData(ie, ne.tagname, oe, true, false, true);
if (null == _) _ = "";
ne.add(this.options.textNodeName, _);
}
le = ee + 2;
} else {
let re = readTagExp(_, le, this.options.removeNSPrefix), ue = re.tagName, de = re.tagExp, fe = re.attrExpPresent, he = re.closeIndex;
if (this.options.transformTagName) ue = this.options.transformTagName(ue);
if (ne && se) if ("!xml" !== ne.tagname) se = this.saveTextToParentTag(se, ne, oe, false);
const pe = ne;
if (pe && -1 !== this.options.unpairedTags.indexOf(pe.tagname)) {
ne = this.tagsNodeStack.pop();
oe = oe.substring(0, oe.lastIndexOf("."));
}
if (ue !== ee.tagname) oe += oe ? "." + ue : ue;
if (this.isItStopNode(this.options.stopNodes, oe, ue)) {
let ee = "";
if (de.length > 0 && de.lastIndexOf("/") === de.length - 1) le = re.closeIndex; else if (-1 !== this.options.unpairedTags.indexOf(ue)) le = re.closeIndex; else {
const ne = this.readStopNodeData(_, ue, he + 1);
if (!ne) throw new Error(`Unexpected end of ${ue}`);
le = ne.i;
ee = ne.tagContent;
}
const se = new ie(ue);
if (ue !== de && fe) se[":@"] = this.buildAttributesMap(de, oe, ue);
if (ee) ee = this.parseTextData(ee, ue, oe, true, fe, true, true);
oe = oe.substr(0, oe.lastIndexOf("."));
se.add(this.options.textNodeName, ee);
this.addChild(ne, se, oe);
} else {
if (de.length > 0 && de.lastIndexOf("/") === de.length - 1) {
if ("/" === ue[ue.length - 1]) {
ue = ue.substr(0, ue.length - 1);
de = ue;
} else de = de.substr(0, de.length - 1);
if (this.options.transformTagName) ue = this.options.transformTagName(ue);
const _ = new ie(ue);
if (ue !== de && fe) _[":@"] = this.buildAttributesMap(de, oe, ue);
this.addChild(ne, _, oe);
oe = oe.substr(0, oe.lastIndexOf("."));
} else {
const _ = new ie(ue);
this.tagsNodeStack.push(ne);
if (ue !== de && fe) _[":@"] = this.buildAttributesMap(de, oe, ue);
this.addChild(ne, _, oe);
ne = _;
}
se = "";
le = he;
}
} else se += _[le];
return ee.child;
};
function addChild(_, ee, ne) {
const ie = this.options.updateTag(ee.tagname, ne, ee[":@"]);
if (false === ie) ; else if ("string" == typeof ie) {
ee.tagname = ie;
_.addChild(ee);
} else _.addChild(ee);
}
var replaceEntitiesValue = function(_) {
if (this.options.processEntities) {
for (let ee in this.docTypeEntities) {
const ne = this.docTypeEntities[ee];
_ = _.replace(ne.regx, ne.val);
}
for (let ee in this.lastEntities) {
const ne = this.lastEntities[ee];
_ = _.replace(ne.regex, ne.val);
}
if (this.options.htmlEntities) for (let ee in this.htmlEntities) {
const ne = this.htmlEntities[ee];
_ = _.replace(ne.regex, ne.val);
}
_ = _.replace(this.ampEntity.regex, this.ampEntity.val);
}
return _;
};
function saveTextToParentTag(_, ee, ne, ie) {
if (_) {
if (void 0 === ie) ie = 0 === Object.keys(ee.child).length;
if (void 0 !== (_ = this.parseTextData(_, ee.tagname, ne, false, ee[":@"] ? 0 !== Object.keys(ee[":@"]).length : false, ie)) && "" !== _) ee.add(this.options.textNodeName, _);
_ = "";
}
return _;
}
function isItStopNode(_, ee, ne) {
const ie = "*." + ne;
for (const ne in _) {
const re = _[ne];
if (ie === re || ee === re) return true;
}
return false;
}
function findClosingIndex(_, ee, ne, ie) {
const re = _.indexOf(ee, ne);
if (-1 === re) throw new Error(ie); else return re + ee.length - 1;
}
function readTagExp(_, ee, ne, ie = ">") {
const re = function tagExpWithClosingIndex(_, ee, ne = ">") {
let ie, re = "";
for (let se = ee; se < _.length; se++) {
let ee = _[se];
if (ie) {
if (ee === ie) ie = "";
} else if ('"' === ee || "'" === ee) ie = ee; else if (ee === ne[0]) if (ne[1]) {
if (_[se + 1] === ne[1]) return {
data: re,
index: se
};
} else return {
data: re,
index: se
}; else if ("\t" === ee) ee = " ";
re += ee;
}
}(_, ee + 1, ie);
if (!re) return;
let se = re.data;
const oe = re.index, le = se.search(/\s/);
let ue = se, de = true;
if (-1 !== le) {
ue = se.substr(0, le).replace(/\s\s*$/, "");
se = se.substr(le + 1);
}
if (ne) {
const _ = ue.indexOf(":");
if (-1 !== _) {
ue = ue.substr(_ + 1);
de = ue !== re.data.substr(_ + 1);
}
}
return {
tagName: ue,
tagExp: se,
closeIndex: oe,
attrExpPresent: de
};
}
function readStopNodeData(_, ee, ne) {
const ie = ne;
let re = 1;
for (;ne < _.length; ne++) if ("<" === _[ne]) if ("/" === _[ne + 1]) {
const se = findClosingIndex(_, ">", ne, `${ee} is not closed`);
if (_.substring(ne + 2, se).trim() === ee) {
re--;
if (0 === re) return {
tagContent: _.substring(ie, ne),
i: se
};
}
ne = se;
} else if ("?" === _[ne + 1]) ne = findClosingIndex(_, "?>", ne + 1, "StopNode is not closed."); else if ("!--" === _.substr(ne + 1, 3)) ne = findClosingIndex(_, "--\x3e", ne + 3, "StopNode is not closed."); else if ("![" === _.substr(ne + 1, 2)) ne = findClosingIndex(_, "]]>", ne, "StopNode is not closed.") - 2; else {
const ie = readTagExp(_, ne, ">");
if (ie) {
if ((ie && ie.tagName) === ee && "/" !== ie.tagExp[ie.tagExp.length - 1]) re++;
ne = ie.closeIndex;
}
}
}
function parseValue(_, ee, ie) {
if (ee && "string" == typeof _) {
const ee = _.trim();
if ("true" === ee) return true; else if ("false" === ee) return false; else return se(_, ie);
} else if (ne.isExist(_)) return _; else return "";
}
ee.exports = class {
constructor(_) {
this.options = _;
this.currentNode = null;
this.tagsNodeStack = [];
this.docTypeEntities = {};
this.lastEntities = {
apos: {
regex: /&(apos|#39|#x27);/g,
val: "'"
},
gt: {
regex: /&(gt|#62|#x3E);/g,
val: ">"
},
lt: {
regex: /&(lt|#60|#x3C);/g,
val: "<"
},
quot: {
regex: /&(quot|#34|#x22);/g,
val: '"'
}
};
this.ampEntity = {
regex: /&(amp|#38|#x26);/g,
val: "&"
};
this.htmlEntities = {
space: {
regex: /&(nbsp|#160);/g,
val: " "
},
cent: {
regex: /&(cent|#162);/g,
val: "¢"
},
pound: {
regex: /&(pound|#163);/g,
val: "£"
},
yen: {
regex: /&(yen|#165);/g,
val: "¥"
},
euro: {
regex: /&(euro|#8364);/g,
val: "€"
},
copyright: {
regex: /&(copy|#169);/g,
val: "©"
},
reg: {
regex: /&(reg|#174);/g,
val: "®"
},
inr: {
regex: /&(inr|#8377);/g,
val: "₹"
}
};
this.addExternalEntities = addExternalEntities;
this.parseXml = parseXml;
this.parseTextData = parseTextData;
this.resolveNameSpace = resolveNameSpace;
this.buildAttributesMap = buildAttributesMap;
this.isItStopNode = isItStopNode;
this.replaceEntitiesValue = replaceEntitiesValue;
this.readStopNodeData = readStopNodeData;
this.saveTextToParentTag = saveTextToParentTag;
this.addChild = addChild;
}
};
}
}), require_node2json = __commonJS({
"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(_) {
"use strict";
function compress(_, ee, ne) {
let ie;
const re = {};
for (let se = 0; se < _.length; se++) {
const oe = _[se], le = propName(oe);
let ue = "";
if (void 0 === ne) ue = le; else ue = ne + "." + le;
if (le === ee.textNodeName) if (void 0 === ie) ie = oe[le]; else ie += "" + oe[le]; else if (void 0 === le) continue; else if (oe[le]) {
let _ = compress(oe[le], ee, ue);
const ne = isLeafTag(_, ee);
if (oe[":@"]) assignAttributes(_, oe[":@"], ue, ee); else if (1 === Object.keys(_).length && void 0 !== _[ee.textNodeName] && !ee.alwaysCreateTextNode) _ = _[ee.textNodeName]; else if (0 === Object.keys(_).length) if (ee.alwaysCreateTextNode) _[ee.textNodeName] = ""; else _ = "";
if (void 0 !== re[le] && re.hasOwnProperty(le)) {
if (!Array.isArray(re[le])) re[le] = [ re[le] ];
re[le].push(_);
} else if (ee.isArray(le, ue, ne)) re[le] = [ _ ]; else re[le] = _;
}
}
if ("string" == typeof ie) {
if (ie.length > 0) re[ee.textNodeName] = ie;
} else if (void 0 !== ie) re[ee.textNodeName] = ie;
return re;
}
function propName(_) {
const ee = Object.keys(_);
for (let _ = 0; _ < ee.length; _++) {
const ne = ee[_];
if (":@" !== ne) return ne;
}
}
function assignAttributes(_, ee, ne, ie) {
if (ee) {
const re = Object.keys(ee), se = re.length;
for (let oe = 0; oe < se; oe++) {
const se = re[oe];
if (ie.isArray(se, ne + "." + se, true, true)) _[se] = [ ee[se] ]; else _[se] = ee[se];
}
}
}
function isLeafTag(_, ee) {
const {textNodeName: ne} = ee, ie = Object.keys(_).length;
if (0 === ie) return true;
if (1 === ie && (_[ne] || "boolean" == typeof _[ne] || 0 === _[ne])) return true; else return false;
}
_.prettify = function prettify(_, ee) {
return compress(_, ee);
};
}
}), require_XMLParser = __commonJS({
"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(_, ee) {
var {buildOptions: ne} = require_OptionsBuilder(), ie = require_OrderedObjParser(), {prettify: re} = require_node2json(), se = require_validator();
ee.exports = class {
constructor(_) {
this.externalEntities = {};
this.options = ne(_);
}
parse(_, ee) {
if ("string" == typeof _) ; else if (_.toString) _ = _.toString(); else throw new Error("XML data is accepted in String or Bytes[] form.");
if (ee) {
if (true === ee) ee = {};
const ne = se.validate(_, ee);
if (true !== ne) throw Error(`${ne.err.msg}:${ne.err.line}:${ne.err.col}`);
}
const ne = new ie(this.options);
ne.addExternalEntities(this.externalEntities);
const oe = ne.parseXml(_);
if (this.options.preserveOrder || void 0 === oe) return oe; else return re(oe, this.options);
}
addEntity(_, ee) {
if (-1 !== ee.indexOf("&")) throw new Error("Entity value can't have '&'"); else if (-1 !== _.indexOf("&") || -1 !== _.indexOf(";")) throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '
'"); else if ("&" === ee) throw new Error("An entity with value '&' is not permitted"); else this.externalEntities[_] = ee;
}
};
}
}), require_orderedJs2Xml = __commonJS({
"node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js"(_, ee) {
function arrToStr(_, ee, ne, ie) {
let re = "", se = false;
for (let oe = 0; oe < _.length; oe++) {
const le = _[oe], ue = propName(le);
let de = "";
if (0 === ne.length) de = ue; else de = `${ne}.${ue}`;
if (ue === ee.textNodeName) {
let _ = le[ue];
if (!isStopNode(de, ee)) {
_ = ee.tagValueProcessor(ue, _);
_ = replaceEntitiesValue(_, ee);
}
if (se) re += ie;
re += _;
se = false;
continue;
} else if (ue === ee.cdataPropName) {
if (se) re += ie;
re += ``;
se = false;
continue;
} else if (ue === ee.commentPropName) {
re += ie + `\x3c!--${le[ue][0][ee.textNodeName]}--\x3e`;
se = true;
continue;
} else if ("?" === ue[0]) {
const _ = attr_to_str(le[":@"], ee), ne = "?xml" === ue ? "" : ie;
let oe = le[ue][0][ee.textNodeName];
oe = 0 !== oe.length ? " " + oe : "";
re += ne + `<${ue}${oe}${_}?>`;
se = true;
continue;
}
let fe = ie;
if ("" !== fe) fe += ee.indentBy;
const he = ie + `<${ue}${attr_to_str(le[":@"], ee)}`, pe = arrToStr(le[ue], ee, de, fe);
if (-1 !== ee.unpairedTags.indexOf(ue)) if (ee.suppressUnpairedNode) re += he + ">"; else re += he + "/>"; else if ((!pe || 0 === pe.length) && ee.suppressEmptyNode) re += he + "/>"; else if (pe && pe.endsWith(">")) re += he + `>${pe}${ie}${ue}>`; else {
re += he + ">";
if (pe && "" !== ie && (pe.includes("/>") || pe.includes(""))) re += ie + ee.indentBy + pe + ie; else re += pe;
re += `${ue}>`;
}
se = true;
}
return re;
}
function propName(_) {
const ee = Object.keys(_);
for (let _ = 0; _ < ee.length; _++) {
const ne = ee[_];
if (":@" !== ne) return ne;
}
}
function attr_to_str(_, ee) {
let ne = "";
if (_ && !ee.ignoreAttributes) for (let ie in _) {
let re = ee.attributeValueProcessor(ie, _[ie]);
re = replaceEntitiesValue(re, ee);
if (true === re && ee.suppressBooleanAttributes) ne += ` ${ie.substr(ee.attributeNamePrefix.length)}`; else ne += ` ${ie.substr(ee.attributeNamePrefix.length)}="${re}"`;
}
return ne;
}
function isStopNode(_, ee) {
let ne = (_ = _.substr(0, _.length - ee.textNodeName.length - 1)).substr(_.lastIndexOf(".") + 1);
for (let ie in ee.stopNodes) if (ee.stopNodes[ie] === _ || ee.stopNodes[ie] === "*." + ne) return true;
return false;
}
function replaceEntitiesValue(_, ee) {
if (_ && _.length > 0 && ee.processEntities) for (let ne = 0; ne < ee.entities.length; ne++) {
const ie = ee.entities[ne];
_ = _.replace(ie.regex, ie.val);
}
return _;
}
ee.exports = function toXml(_, ee) {
let ne = "";
if (ee.format && ee.indentBy.length > 0) ne = "\n";
return arrToStr(_, ee, "", ne);
};
}
}), require_json2xml = __commonJS({
"node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js"(_, ee) {
"use strict";
var ne = require_orderedJs2Xml(), ie = {
attributeNamePrefix: "@_",
attributesGroupName: false,
textNodeName: "#text",
ignoreAttributes: true,
cdataPropName: false,
format: false,
indentBy: " ",
suppressEmptyNode: false,
suppressUnpairedNode: true,
suppressBooleanAttributes: true,
tagValueProcessor: function(_, ee) {
return ee;
},
attributeValueProcessor: function(_, ee) {
return ee;
},
preserveOrder: false,
commentPropName: false,
unpairedTags: [],
entities: [ {
regex: new RegExp("&", "g"),
val: "&"
}, {
regex: new RegExp(">", "g"),
val: ">"
}, {
regex: new RegExp("<", "g"),
val: "<"
}, {
regex: new RegExp("'", "g"),
val: "'"
}, {
regex: new RegExp('"', "g"),
val: """
} ],
processEntities: true,
stopNodes: [],
oneListGroup: false
};
function Builder(_) {
this.options = Object.assign({}, ie, _);
if (this.options.ignoreAttributes || this.options.attributesGroupName) this.isAttribute = function() {
return false;
}; else {
this.attrPrefixLen = this.options.attributeNamePrefix.length;
this.isAttribute = isAttribute;
}
this.processTextOrObjNode = processTextOrObjNode;
if (this.options.format) {
this.indentate = indentate;
this.tagEndChar = ">\n";
this.newLine = "\n";
} else {
this.indentate = function() {
return "";
};
this.tagEndChar = ">";
this.newLine = "";
}
}
Builder.prototype.build = function(_) {
if (this.options.preserveOrder) return ne(_, this.options); else {
if (Array.isArray(_) && this.options.arrayNodeName && this.options.arrayNodeName.length > 1) _ = {
[this.options.arrayNodeName]: _
};
return this.j2x(_, 0).val;
}
};
Builder.prototype.j2x = function(_, ee) {
let ne = "", ie = "";
for (let re in _) if ("undefined" == typeof _[re]) ; else if (null === _[re]) if ("?" === re[0]) ie += this.indentate(ee) + "<" + re + "?" + this.tagEndChar; else ie += this.indentate(ee) + "<" + re + "/" + this.tagEndChar; else if (_[re] instanceof Date) ie += this.buildTextValNode(_[re], re, "", ee); else if ("object" != typeof _[re]) {
const se = this.isAttribute(re);
if (se) ne += this.buildAttrPairStr(se, "" + _[re]); else if (re === this.options.textNodeName) {
let ee = this.options.tagValueProcessor(re, "" + _[re]);
ie += this.replaceEntitiesValue(ee);
} else ie += this.buildTextValNode(_[re], re, "", ee);
} else if (Array.isArray(_[re])) {
const ne = _[re].length;
let se = "";
for (let oe = 0; oe < ne; oe++) {
const ne = _[re][oe];
if ("undefined" == typeof ne) ; else if (null === ne) if ("?" === re[0]) ie += this.indentate(ee) + "<" + re + "?" + this.tagEndChar; else ie += this.indentate(ee) + "<" + re + "/" + this.tagEndChar; else if ("object" == typeof ne) if (this.options.oneListGroup) se += this.j2x(ne, ee + 1).val; else se += this.processTextOrObjNode(ne, re, ee); else se += this.buildTextValNode(ne, re, "", ee);
}
if (this.options.oneListGroup) se = this.buildObjectNode(se, re, "", ee);
ie += se;
} else if (this.options.attributesGroupName && re === this.options.attributesGroupName) {
const ee = Object.keys(_[re]), ie = ee.length;
for (let se = 0; se < ie; se++) ne += this.buildAttrPairStr(ee[se], "" + _[re][ee[se]]);
} else ie += this.processTextOrObjNode(_[re], re, ee);
return {
attrStr: ne,
val: ie
};
};
Builder.prototype.buildAttrPairStr = function(_, ee) {
ee = this.options.attributeValueProcessor(_, "" + ee);
ee = this.replaceEntitiesValue(ee);
if (this.options.suppressBooleanAttributes && "true" === ee) return " " + _; else return " " + _ + '="' + ee + '"';
};
function processTextOrObjNode(_, ee, ne) {
const ie = this.j2x(_, ne + 1);
if (void 0 !== _[this.options.textNodeName] && 1 === Object.keys(_).length) return this.buildTextValNode(_[this.options.textNodeName], ee, ie.attrStr, ne); else return this.buildObjectNode(ie.val, ee, ie.attrStr, ne);
}
Builder.prototype.buildObjectNode = function(_, ee, ne, ie) {
if ("" === _) if ("?" === ee[0]) return this.indentate(ie) + "<" + ee + ne + "?" + this.tagEndChar; else return this.indentate(ie) + "<" + ee + ne + this.closeTag(ee) + this.tagEndChar; else {
let re = "" + ee + this.tagEndChar, se = "";
if ("?" === ee[0]) {
se = "?";
re = "";
}
if (ne && -1 === _.indexOf("<")) return this.indentate(ie) + "<" + ee + ne + se + ">" + _ + re; else if (false !== this.options.commentPropName && ee === this.options.commentPropName && 0 === se.length) return this.indentate(ie) + `\x3c!--${_}--\x3e` + this.newLine; else return this.indentate(ie) + "<" + ee + ne + se + this.tagEndChar + _ + this.indentate(ie) + re;
}
};
Builder.prototype.closeTag = function(_) {
let ee = "";
if (-1 !== this.options.unpairedTags.indexOf(_)) {
if (!this.options.suppressUnpairedNode) ee = "/";
} else if (this.options.suppressEmptyNode) ee = "/"; else ee = `>${_}`;
return ee;
};
Builder.prototype.buildTextValNode = function(_, ee, ne, ie) {
if (false !== this.options.cdataPropName && ee === this.options.cdataPropName) return this.indentate(ie) + `` + this.newLine; else if (false !== this.options.commentPropName && ee === this.options.commentPropName) return this.indentate(ie) + `\x3c!--${_}--\x3e` + this.newLine; else if ("?" === ee[0]) return this.indentate(ie) + "<" + ee + ne + "?" + this.tagEndChar; else {
let re = this.options.tagValueProcessor(ee, _);
re = this.replaceEntitiesValue(re);
if ("" === re) return this.indentate(ie) + "<" + ee + ne + this.closeTag(ee) + this.tagEndChar; else return this.indentate(ie) + "<" + ee + ne + ">" + re + "" + ee + this.tagEndChar;
}
};
Builder.prototype.replaceEntitiesValue = function(_) {
if (_ && _.length > 0 && this.options.processEntities) for (let ee = 0; ee < this.options.entities.length; ee++) {
const ne = this.options.entities[ee];
_ = _.replace(ne.regex, ne.val);
}
return _;
};
function indentate(_) {
return this.options.indentBy.repeat(_);
}
function isAttribute(_) {
if (_.startsWith(this.options.attributeNamePrefix)) return _.substr(this.attrPrefixLen); else return false;
}
ee.exports = Builder;
}
}), require_fxp = __commonJS({
"node_modules/fast-xml-parser/src/fxp.js"(_, ee) {
"use strict";
var ne = require_validator(), ie = require_XMLParser(), re = require_json2xml();
ee.exports = {
XMLParser: ie,
XMLValidator: ne,
XMLBuilder: re
};
}
}), tslib_es6_exports = {};
__export(tslib_es6_exports, {
__assign: () => __assign,
__asyncDelegator: () => __asyncDelegator,
__asyncGenerator: () => __asyncGenerator,
__asyncValues: () => __asyncValues,
__await: () => __await,
__awaiter: () => __awaiter,
__classPrivateFieldGet: () => __classPrivateFieldGet,
__classPrivateFieldSet: () => __classPrivateFieldSet,
__createBinding: () => __createBinding,
__decorate: () => __decorate,
__exportStar: () => __exportStar,
__extends: () => __extends,
__generator: () => __generator,
__importDefault: () => __importDefault,
__importStar: () => __importStar,
__makeTemplateObject: () => __makeTemplateObject,
__metadata: () => __metadata,
__param: () => __param,
__read: () => __read,
__rest: () => __rest,
__spread: () => __spread,
__spreadArrays: () => __spreadArrays,
__values: () => __values
});
function __extends(_, ee) {
extendStatics(_, ee);
function __() {
this.constructor = _;
}
_.prototype = null === ee ? Object.create(ee) : (__.prototype = ee.prototype, new __);
}
function __rest(_, ee) {
var ne = {};
for (var ie in _) if (Object.prototype.hasOwnProperty.call(_, ie) && ee.indexOf(ie) < 0) ne[ie] = _[ie];
if (null != _ && "function" == typeof Object.getOwnPropertySymbols) {
var re = 0;
for (ie = Object.getOwnPropertySymbols(_); re < ie.length; re++) if (ee.indexOf(ie[re]) < 0 && Object.prototype.propertyIsEnumerable.call(_, ie[re])) ne[ie[re]] = _[ie[re]];
}
return ne;
}
function __decorate(_, ee, ne, ie) {
var re, se = arguments.length, oe = se < 3 ? ee : null === ie ? ie = Object.getOwnPropertyDescriptor(ee, ne) : ie;
if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) oe = Reflect.decorate(_, ee, ne, ie); else for (var le = _.length - 1; le >= 0; le--) if (re = _[le]) oe = (se < 3 ? re(oe) : se > 3 ? re(ee, ne, oe) : re(ee, ne)) || oe;
return se > 3 && oe && Object.defineProperty(ee, ne, oe), oe;
}
function __param(_, ee) {
return function(ne, ie) {
ee(ne, ie, _);
};
}
function __metadata(_, ee) {
if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) return Reflect.metadata(_, ee);
}
function __awaiter(_, ee, ne, ie) {
return new (ne || (ne = Promise))((function(re, se) {
function fulfilled(_) {
try {
step(ie.next(_));
} catch (_) {
se(_);
}
}
function rejected(_) {
try {
step(ie["throw"](_));
} catch (_) {
se(_);
}
}
function step(_) {
_.done ? re(_.value) : function adopt(_) {
return _ instanceof ne ? _ : new ne((function(ee) {
ee(_);
}));
}(_.value).then(fulfilled, rejected);
}
step((ie = ie.apply(_, ee || [])).next());
}));
}
function __generator(_, ee) {
var ne, ie, re, se, oe = {
label: 0,
sent: function() {
if (1 & re[0]) throw re[1];
return re[1];
},
trys: [],
ops: []
};
return se = {
next: verb(0),
throw: verb(1),
return: verb(2)
}, "function" == typeof Symbol && (se[Symbol.iterator] = function() {
return this;
}), se;
function verb(se) {
return function(le) {
return function step(se) {
if (ne) throw new TypeError("Generator is already executing.");
for (;oe; ) try {
if (ne = 1, ie && (re = 2 & se[0] ? ie["return"] : se[0] ? ie["throw"] || ((re = ie["return"]) && re.call(ie),
0) : ie.next) && !(re = re.call(ie, se[1])).done) return re;
if (ie = 0, re) se = [ 2 & se[0], re.value ];
switch (se[0]) {
case 0:
case 1:
re = se;
break;
case 4:
oe.label++;
return {
value: se[1],
done: false
};
case 5:
oe.label++;
ie = se[1];
se = [ 0 ];
continue;
case 7:
se = oe.ops.pop();
oe.trys.pop();
continue;
default:
if (!(re = oe.trys, re = re.length > 0 && re[re.length - 1]) && (6 === se[0] || 2 === se[0])) {
oe = 0;
continue;
}
if (3 === se[0] && (!re || se[1] > re[0] && se[1] < re[3])) {
oe.label = se[1];
break;
}
if (6 === se[0] && oe.label < re[1]) {
oe.label = re[1];
re = se;
break;
}
if (re && oe.label < re[2]) {
oe.label = re[2];
oe.ops.push(se);
break;
}
if (re[2]) oe.ops.pop();
oe.trys.pop();
continue;
}
se = ee.call(_, oe);
} catch (_) {
se = [ 6, _ ];
ie = 0;
} finally {
ne = re = 0;
}
if (5 & se[0]) throw se[1];
return {
value: se[0] ? se[1] : void 0,
done: true
};
}([ se, le ]);
};
}
}
function __createBinding(_, ee, ne, ie) {
if (void 0 === ie) ie = ne;
_[ie] = ee[ne];
}
function __exportStar(_, ee) {
for (var ne in _) if ("default" !== ne && !ee.hasOwnProperty(ne)) ee[ne] = _[ne];
}
function __values(_) {
var ee = "function" == typeof Symbol && Symbol.iterator, ne = ee && _[ee], ie = 0;
if (ne) return ne.call(_);
if (_ && "number" == typeof _.length) return {
next: function() {
if (_ && ie >= _.length) _ = void 0;
return {
value: _ && _[ie++],
done: !_
};
}
};
throw new TypeError(ee ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(_, ee) {
var ne = "function" == typeof Symbol && _[Symbol.iterator];
if (!ne) return _;
var ie, re, se = ne.call(_), oe = [];
try {
for (;(void 0 === ee || ee-- > 0) && !(ie = se.next()).done; ) oe.push(ie.value);
} catch (_) {
re = {
error: _
};
} finally {
try {
if (ie && !ie.done && (ne = se["return"])) ne.call(se);
} finally {
if (re) throw re.error;
}
}
return oe;
}
function __spread() {
for (var _ = [], ee = 0; ee < arguments.length; ee++) _ = _.concat(__read(arguments[ee]));
return _;
}
function __spreadArrays() {
for (var _ = 0, ee = 0, ne = arguments.length; ee < ne; ee++) _ += arguments[ee].length;
var ie = Array(_), re = 0;
for (ee = 0; ee < ne; ee++) for (var se = arguments[ee], oe = 0, le = se.length; oe < le; oe++,
re++) ie[re] = se[oe];
return ie;
}
function __await(_) {
return this instanceof __await ? (this.v = _, this) : new __await(_);
}
function __asyncGenerator(_, ee, ne) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var ie, re = ne.apply(_, ee || []), se = [];
return ie = {}, verb("next"), verb("throw"), verb("return"), ie[Symbol.asyncIterator] = function() {
return this;
}, ie;
function verb(_) {
if (re[_]) ie[_] = function(ee) {
return new Promise((function(ne, ie) {
se.push([ _, ee, ne, ie ]) > 1 || resume(_, ee);
}));
};
}
function resume(_, ee) {
try {
(function step(_) {
_.value instanceof __await ? Promise.resolve(_.value.v).then(fulfill, reject) : settle(se[0][2], _);
})(re[_](ee));
} catch (_) {
settle(se[0][3], _);
}
}
function fulfill(_) {
resume("next", _);
}
function reject(_) {
resume("throw", _);
}
function settle(_, ee) {
if (_(ee), se.shift(), se.length) resume(se[0][0], se[0][1]);
}
}
function __asyncDelegator(_) {
var ee, ne;
return ee = {}, verb("next"), verb("throw", (function(_) {
throw _;
})), verb("return"), ee[Symbol.iterator] = function() {
return this;
}, ee;
function verb(ie, re) {
ee[ie] = _[ie] ? function(ee) {
return (ne = !ne) ? {
value: __await(_[ie](ee)),
done: "return" === ie
} : re ? re(ee) : ee;
} : re;
}
}
function __asyncValues(_) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var ee, ne = _[Symbol.asyncIterator];
return ne ? ne.call(_) : (_ = "function" == typeof __values ? __values(_) : _[Symbol.iterator](),
ee = {}, verb("next"), verb("throw"), verb("return"), ee[Symbol.asyncIterator] = function() {
return this;
}, ee);
function verb(ne) {
ee[ne] = _[ne] && function(ee) {
return new Promise((function(ie, re) {
(function settle(_, ee, ne, ie) {
Promise.resolve(ie).then((function(ee) {
_({
value: ee,
done: ne
});
}), ee);
})(ie, re, (ee = _[ne](ee)).done, ee.value);
}));
};
}
}
function __makeTemplateObject(_, ee) {
if (Object.defineProperty) Object.defineProperty(_, "raw", {
value: ee
}); else _.raw = ee;
return _;
}
function __importStar(_) {
if (_ && _.__esModule) return _;
var ee = {};
if (null != _) for (var ne in _) if (Object.hasOwnProperty.call(_, ne)) ee[ne] = _[ne];
ee.default = _;
return ee;
}
function __importDefault(_) {
return _ && _.__esModule ? _ : {
default: _
};
}
function __classPrivateFieldGet(_, ee) {
if (!ee.has(_)) throw new TypeError("attempted to get private field on non-instance");
return ee.get(_);
}
function __classPrivateFieldSet(_, ee, ne) {
if (!ee.has(_)) throw new TypeError("attempted to set private field on non-instance");
ee.set(_, ne);
return ne;
}
var fromUtf82, toUtf82, init_tslib_es6 = __esm({
"node_modules/@aws-crypto/sha1-browser/node_modules/tslib/tslib.es6.js"() {
extendStatics = function(_, ee) {
return (extendStatics = Object.setPrototypeOf || {
__proto__: []
} instanceof Array && function(_, ee) {
_.__proto__ = ee;
} || function(_, ee) {
for (var ne in ee) if (ee.hasOwnProperty(ne)) _[ne] = ee[ne];
})(_, ee);
};
__assign = function() {
__assign = Object.assign || function __assign8(_) {
for (var ee, ne = 1, ie = arguments.length; ne < ie; ne++) {
ee = arguments[ne];
for (var re in ee) if (Object.prototype.hasOwnProperty.call(ee, re)) _[re] = ee[re];
}
return _;
};
return __assign.apply(this, arguments);
};
}
}), require_isEmptyData = __commonJS({
"node_modules/@aws-crypto/sha1-browser/build/isEmptyData.js"(_) {
"use strict";
Object.defineProperty(_, "__esModule", {
value: true
});
_.isEmptyData = void 0;
_.isEmptyData = function isEmptyData2(_) {
if ("string" == typeof _) return 0 === _.length; else return 0 === _.byteLength;
};
}
}), require_constants = __commonJS({
"node_modules/@aws-crypto/sha1-browser/build/constants.js"(_) {
"use strict";
Object.defineProperty(_, "__esModule", {
value: true
});
_.EMPTY_DATA_SHA_1 = _.SHA_1_HMAC_ALGO = _.SHA_1_HASH = void 0;
_.SHA_1_HASH = {
name: "SHA-1"
};
_.SHA_1_HMAC_ALGO = {
name: "HMAC",
hash: _.SHA_1_HASH
};
_.EMPTY_DATA_SHA_1 = new Uint8Array([ 218, 57, 163, 238, 94, 107, 75, 13, 50, 85, 191, 239, 149, 96, 24, 144, 175, 216, 7, 9 ]);
}
}), init_pureJs = __esm({
"node_modules/@aws-sdk/util-utf8-browser/dist-es/pureJs.js"() {
fromUtf82 = _ => {
const ee = [];
for (let ne = 0, ie = _.length; ne < ie; ne++) {
const ie = _.charCodeAt(ne);
if (ie < 128) ee.push(ie); else if (ie < 2048) ee.push(ie >> 6 | 192, 63 & ie | 128); else if (ne + 1 < _.length && 55296 == (64512 & ie) && 56320 == (64512 & _.charCodeAt(ne + 1))) {
const re = 65536 + ((1023 & ie) << 10) + (1023 & _.charCodeAt(++ne));
ee.push(re >> 18 | 240, re >> 12 & 63 | 128, re >> 6 & 63 | 128, 63 & re | 128);
} else ee.push(ie >> 12 | 224, ie >> 6 & 63 | 128, 63 & ie | 128);
}
return Uint8Array.from(ee);
};
toUtf82 = _ => {
let ee = "";
for (let ne = 0, ie = _.length; ne < ie; ne++) {
const ie = _[ne];
if (ie < 128) ee += String.fromCharCode(ie); else if (192 <= ie && ie < 224) {
const re = _[++ne];
ee += String.fromCharCode((31 & ie) << 6 | 63 & re);
} else if (240 <= ie && ie < 365) {
const re = "%" + [ ie, _[++ne], _[++ne], _[++ne] ].map((_ => _.toString(16))).join("%");
ee += decodeURIComponent(re);
} else ee += String.fromCharCode((15 & ie) << 12 | (63 & _[++ne]) << 6 | 63 & _[++ne]);
}
return ee;
};
}
});
function fromUtf83(_) {
return (new TextEncoder).encode(_);
}
function toUtf83(_) {
return new TextDecoder("utf-8").decode(_);
}
var fromUtf84, toUtf84, init_whatwgEncodingApi = __esm({
"node_modules/@aws-sdk/util-utf8-browser/dist-es/whatwgEncodingApi.js"() {}
}), dist_es_exports = {};
__export(dist_es_exports, {
fromUtf8: () => fromUtf84,
toUtf8: () => toUtf84
});
var fallbackWindow, init_dist_es = __esm({
"node_modules/@aws-sdk/util-utf8-browser/dist-es/index.js"() {
init_pureJs();
init_whatwgEncodingApi();
fromUtf84 = _ => "function" == typeof TextEncoder ? fromUtf83(_) : fromUtf82(_);
toUtf84 = _ => "function" == typeof TextDecoder ? toUtf83(_) : toUtf82(_);
}
}), dist_es_exports2 = {};
__export(dist_es_exports2, {
locateWindow: () => locateWindow
});
function locateWindow() {
if ("undefined" != typeof window) return window; else if ("undefined" != typeof self) return self;
return fallbackWindow;
}
var extendStatics2, __assign2, init_dist_es2 = __esm({
"node_modules/@aws-sdk/util-locate-window/dist-es/index.js"() {
fallbackWindow = {};
}
}), require_ie11Sha1 = __commonJS({
"node_modules/@aws-crypto/sha1-browser/build/ie11Sha1.js"(_) {
"use strict";
Object.defineProperty(_, "__esModule", {
value: true
});
_.Sha1 = void 0;
var ee = require_isEmptyData(), ne = require_constants(), ie = (init_dist_es(),
__toCommonJS(dist_es_exports)), re = (init_dist_es2(), __toCommonJS(dist_es_exports2)), se = function() {
function Sha13(_) {
this.secret = _;
this.reset();
}
Sha13.prototype.update = function(_) {
var ne = this;
if (!(0, ee.isEmptyData)(_)) {
this.operation = this.operation.then((function(ee) {
ee.onerror = function() {
ne.operation = Promise.reject(new Error("Error encountered updating hash"));
};
ee.process(toArrayBufferView(_));
return ee;
}));
this.operation.catch((function() {}));
}
};
Sha13.prototype.digest = function() {
return this.operation.then((function(_) {
return new Promise((function(ee, ne) {
_.onerror = function() {
ne(new Error("Error encountered finalizing hash"));
};
_.oncomplete = function() {
if (_.result) ee(new Uint8Array(_.result));
ne(new Error("Error encountered finalizing hash"));
};
_.finish();
}));
}));
};
Sha13.prototype.reset = function() {
if (this.secret) {
this.operation = function getKeyPromise(_) {
return new Promise((function(ee, ie) {
var se = (0, re.locateWindow)().msCrypto.subtle.importKey("raw", toArrayBufferView(_), ne.SHA_1_HMAC_ALGO, false, [ "sign" ]);
se.oncomplete = function() {
if (se.result) ee(se.result);
ie(new Error("ImportKey completed without importing key."));
};
se.onerror = function() {
ie(new Error("ImportKey failed to import key."));
};
}));
}(this.secret).then((function(_) {
return (0, re.locateWindow)().msCrypto.subtle.sign(ne.SHA_1_HMAC_ALGO, _);
}));
this.operation.catch((function() {}));
} else this.operation = Promise.resolve((0, re.locateWindow)().msCrypto.subtle.digest("SHA-1"));
};
return Sha13;
}();
_.Sha1 = se;
function toArrayBufferView(_) {
if ("string" == typeof _) return (0, ie.fromUtf8)(_);
if (ArrayBuffer.isView(_)) return new Uint8Array(_.buffer, _.byteOffset, _.byteLength / Uint8Array.BYTES_PER_ELEMENT); else return new Uint8Array(_);
}
}
}), require_webCryptoSha1 = __commonJS({
"node_modules/@aws-crypto/sha1-browser/build/webCryptoSha1.js"(_) {
"use strict";
Object.defineProperty(_, "__esModule", {
value: true
});
_.Sha1 = void 0;
var ee = (init_dist_es(), __toCommonJS(dist_es_exports)), ne = require_isEmptyData(), ie = require_constants(), re = (init_dist_es2(),
__toCommonJS(dist_es_exports2)), se = function() {
function Sha13(_) {
this.toHash = new Uint8Array(0);
if (void 0 !== _) {
this.key = new Promise((function(ee, ne) {
(0, re.locateWindow)().crypto.subtle.importKey("raw", convertToBuffer2(_), ie.SHA_1_HMAC_ALGO, false, [ "sign" ]).then(ee, ne);
}));
this.key.catch((function() {}));
}
}
Sha13.prototype.update = function(_) {
if (!(0, ne.isEmptyData)(_)) {
var ee = convertToBuffer2(_), ie = new Uint8Array(this.toHash.byteLength + ee.byteLength);
ie.set(this.toHash, 0);
ie.set(ee, this.toHash.byteLength);
this.toHash = ie;
}
};
Sha13.prototype.digest = function() {
var _ = this;
if (this.key) return this.key.then((function(ee) {
return (0, re.locateWindow)().crypto.subtle.sign(ie.SHA_1_HMAC_ALGO, ee, _.toHash).then((function(_) {
return new Uint8Array(_);
}));
}));
if ((0, ne.isEmptyData)(this.toHash)) return Promise.resolve(ie.EMPTY_DATA_SHA_1); else return Promise.resolve().then((function() {
return (0, re.locateWindow)().crypto.subtle.digest(ie.SHA_1_HASH, _.toHash);
})).then((function(_) {
return Promise.resolve(new Uint8Array(_));
}));
};
Sha13.prototype.reset = function() {
this.toHash = new Uint8Array(0);
};
return Sha13;
}();
_.Sha1 = se;
function convertToBuffer2(_) {
if ("string" == typeof _) return (0, ee.fromUtf8)(_);
if (ArrayBuffer.isView(_)) return new Uint8Array(_.buffer, _.byteOffset, _.byteLength / Uint8Array.BYTES_PER_ELEMENT); else return new Uint8Array(_);
}
}
}), tslib_es6_exports2 = {};
__export(tslib_es6_exports2, {
__assign: () => __assign2,
__asyncDelegator: () => __asyncDelegator2,
__asyncGenerator: () => __asyncGenerator2,
__asyncValues: () => __asyncValues2,
__await: () => __await2,
__awaiter: () => __awaiter2,
__classPrivateFieldGet: () => __classPrivateFieldGet2,
__classPrivateFieldSet: () => __classPrivateFieldSet2,
__createBinding: () => __createBinding2,
__decorate: () => __decorate2,
__exportStar: () => __exportStar2,
__extends: () => __extends2,
__generator: () => __generator2,
__importDefault: () => __importDefault2,
__importStar: () => __importStar2,
__makeTemplateObject: () => __makeTemplateObject2,
__metadata: () => __metadata2,
__param: () => __param2,
__read: () => __read2,
__rest: () => __rest2,
__spread: () => __spread2,
__spreadArrays: () => __spreadArrays2,
__values: () => __values2
});
function __extends2(_, ee) {
extendStatics2(_, ee);
function __() {
this.constructor = _;
}
_.prototype = null === ee ? Object.create(ee) : (__.prototype = ee.prototype, new __);
}
function __rest2(_, ee) {
var ne = {};
for (var ie in _) if (Object.prototype.hasOwnProperty.call(_, ie) && ee.indexOf(ie) < 0) ne[ie] = _[ie];
if (null != _ && "function" == typeof Object.getOwnPropertySymbols) {
var re = 0;
for (ie = Object.getOwnPropertySymbols(_); re < ie.length; re++) if (ee.indexOf(ie[re]) < 0 && Object.prototype.propertyIsEnumerable.call(_, ie[re])) ne[ie[re]] = _[ie[re]];
}
return ne;
}
function __decorate2(_, ee, ne, ie) {
var re, se = arguments.length, oe = se < 3 ? ee : null === ie ? ie = Object.getOwnPropertyDescriptor(ee, ne) : ie;
if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) oe = Reflect.decorate(_, ee, ne, ie); else for (var le = _.length - 1; le >= 0; le--) if (re = _[le]) oe = (se < 3 ? re(oe) : se > 3 ? re(ee, ne, oe) : re(ee, ne)) || oe;
return se > 3 && oe && Object.defineProperty(ee, ne, oe), oe;
}
function __param2(_, ee) {
return function(ne, ie) {
ee(ne, ie, _);
};
}
function __metadata2(_, ee) {
if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) return Reflect.metadata(_, ee);
}
function __awaiter2(_, ee, ne, ie) {
return new (ne || (ne = Promise))((function(re, se) {
function fulfilled(_) {
try {
step(ie.next(_));
} catch (_) {
se(_);
}
}
function rejected(_) {
try {
step(ie["throw"](_));
} catch (_) {
se(_);
}
}
function step(_) {
_.done ? re(_.value) : function adopt(_) {
return _ instanceof ne ? _ : new ne((function(ee) {
ee(_);
}));
}(_.value).then(fulfilled, rejected);
}
step((ie = ie.apply(_, ee || [])).next());
}));
}
function __generator2(_, ee) {
var ne, ie, re, se, oe = {
label: 0,
sent: function() {
if (1 & re[0]) throw re[1];
return re[1];
},
trys: [],
ops: []
};
return se = {
next: verb(0),
throw: verb(1),
return: verb(2)
}, "function" == typeof Symbol && (se[Symbol.iterator] = function() {
return this;
}), se;
function verb(se) {
return function(le) {
return function step(se) {
if (ne) throw new TypeError("Generator is already executing.");
for (;oe; ) try {
if (ne = 1, ie && (re = 2 & se[0] ? ie["return"] : se[0] ? ie["throw"] || ((re = ie["return"]) && re.call(ie),
0) : ie.next) && !(re = re.call(ie, se[1])).done) return re;
if (ie = 0, re) se = [ 2 & se[0], re.value ];
switch (se[0]) {
case 0:
case 1:
re = se;
break;
case 4:
oe.label++;
return {
value: se[1],
done: false
};
case 5:
oe.label++;
ie = se[1];
se = [ 0 ];
continue;
case 7:
se = oe.ops.pop();
oe.trys.pop();
continue;
default:
if (!(re = oe.trys, re = re.length > 0 && re[re.length - 1]) && (6 === se[0] || 2 === se[0])) {
oe = 0;
continue;
}
if (3 === se[0] && (!re || se[1] > re[0] && se[1] < re[3])) {
oe.label = se[1];
break;
}
if (6 === se[0] && oe.label < re[1]) {
oe.label = re[1];
re = se;
break;
}
if (re && oe.label < re[2]) {
oe.label = re[2];
oe.ops.push(se);
break;
}
if (re[2]) oe.ops.pop();
oe.trys.pop();
continue;
}
se = ee.call(_, oe);
} catch (_) {
se = [ 6, _ ];
ie = 0;
} finally {
ne = re = 0;
}
if (5 & se[0]) throw se[1];
return {
value: se[0] ? se[1] : void 0,
done: true
};
}([ se, le ]);
};
}
}
function __createBinding2(_, ee, ne, ie) {
if (void 0 === ie) ie = ne;
_[ie] = ee[ne];
}
function __exportStar2(_, ee) {
for (var ne in _) if ("default" !== ne && !ee.hasOwnProperty(ne)) ee[ne] = _[ne];
}
function __values2(_) {
var ee = "function" == typeof Symbol && Symbol.iterator, ne = ee && _[ee], ie = 0;
if (ne) return ne.call(_);
if (_ && "number" == typeof _.length) return {
next: function() {
if (_ && ie >= _.length) _ = void 0;
return {
value: _ && _[ie++],
done: !_
};
}
};
throw new TypeError(ee ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read2(_, ee) {
var ne = "function" == typeof Symbol && _[Symbol.iterator];
if (!ne) return _;
var ie, re, se = ne.call(_), oe = [];
try {
for (;(void 0 === ee || ee-- > 0) && !(ie = se.next()).done; ) oe.push(ie.value);
} catch (_) {
re = {
error: _
};
} finally {
try {
if (ie && !ie.done && (ne = se["return"])) ne.call(se);
} finally {
if (re) throw re.error;
}
}
return oe;
}
function __spread2() {
for (var _ = [], ee = 0; ee < arguments.length; ee++) _ = _.concat(__read2(arguments[ee]));
return _;
}
function __spreadArrays2() {
for (var _ = 0, ee = 0, ne = arguments.length; ee < ne; ee++) _ += arguments[ee].length;
var ie = Array(_), re = 0;
for (ee = 0; ee < ne; ee++) for (var se = arguments[ee], oe = 0, le = se.length; oe < le; oe++,
re++) ie[re] = se[oe];
return ie;
}
function __await2(_) {
return this instanceof __await2 ? (this.v = _, this) : new __await2(_);
}
function __asyncGenerator2(_, ee, ne) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var ie, re = ne.apply(_, ee || []), se = [];
return ie = {}, verb("next"), verb("throw"), verb("return"), ie[Symbol.asyncIterator] = function() {
return this;
}, ie;
function verb(_) {
if (re[_]) ie[_] = function(ee) {
return new Promise((function(ne, ie) {
se.push([ _, ee, ne, ie ]) > 1 || resume(_, ee);
}));
};
}
function resume(_, ee) {
try {
(function step(_) {
_.value instanceof __await2 ? Promise.resolve(_.value.v).then(fulfill, reject) : settle(se[0][2], _);
})(re[_](ee));
} catch (_) {
settle(se[0][3], _);
}
}
function fulfill(_) {
resume("next", _);
}
function reject(_) {
resume("throw", _);
}
function settle(_, ee) {
if (_(ee), se.shift(), se.length) resume(se[0][0], se[0][1]);
}
}
function __asyncDelegator2(_) {
var ee, ne;
return ee = {}, verb("next"), verb("throw", (function(_) {
throw _;
})), verb("return"), ee[Symbol.iterator] = function() {
return this;
}, ee;
function verb(ie, re) {
ee[ie] = _[ie] ? function(ee) {
return (ne = !ne) ? {
value: __await2(_[ie](ee)),
done: "return" === ie
} : re ? re(ee) : ee;
} : re;
}
}
function __asyncValues2(_) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var ee, ne = _[Symbol.asyncIterator];
return ne ? ne.call(_) : (_ = "function" == typeof __values2 ? __values2(_) : _[Symbol.iterator](),
ee = {}, verb("next"), verb("throw"), verb("return"), ee[Symbol.asyncIterator] = function() {
return this;
}, ee);
function verb(ne) {
ee[ne] = _[ne] && function(ee) {
return new Promise((function(ie, re) {
(function settle(_, ee, ne, ie) {
Promise.resolve(ie).then((function(ee) {
_({
value: ee,
done: ne
});
}), ee);
})(ie, re, (ee = _[ne](ee)).done, ee.value);
}));
};
}
}
function __makeTemplateObject2(_, ee) {
if (Object.defineProperty) Object.defineProperty(_, "raw", {
value: ee
}); else _.raw = ee;
return _;
}
function __importStar2(_) {
if (_ && _.__esModule) return _;
var ee = {};
if (null != _) for (var ne in _) if (Object.hasOwnProperty.call(_, ne)) ee[ne] = _[ne];
ee.default = _;
return ee;
}
function __importDefault2(_) {
return _ && _.__esModule ? _ : {
default: _
};
}
function __classPrivateFieldGet2(_, ee) {
if (!ee.has(_)) throw new TypeError("attempted to get private field on non-instance");
return ee.get(_);
}
function __classPrivateFieldSet2(_, ee, ne) {
if (!ee.has(_)) throw new TypeError("attempted to set private field on non-instance");
ee.set(_, ne);
return ne;
}
var extendStatics3, __assign3, init_tslib_es62 = __esm({
"node_modules/@aws-crypto/supports-web-crypto/node_modules/tslib/tslib.es6.js"() {
extendStatics2 = function(_, ee) {
return (extendStatics2 = Object.setPrototypeOf || {
__proto__: []
} instanceof Array && function(_, ee) {
_.__proto__ = ee;
} || function(_, ee) {
for (var ne in ee) if (ee.hasOwnProperty(ne)) _[ne] = ee[ne];
})(_, ee);
};
__assign2 = function() {
__assign2 = Object.assign || function __assign8(_) {
for (var ee, ne = 1, ie = arguments.length; ne < ie; ne++) {
ee = arguments[ne];
for (var re in ee) if (Object.prototype.hasOwnProperty.call(ee, re)) _[re] = ee[re];
}
return _;
};
return __assign2.apply(this, arguments);
};
}
}), require_supportsWebCrypto = __commonJS({
"node_modules/@aws-crypto/supports-web-crypto/build/supportsWebCrypto.js"(_) {
"use strict";
Object.defineProperty(_, "__esModule", {
value: true
});
_.supportsZeroByteGCM = _.supportsSubtleCrypto = _.supportsSecureRandom = _.supportsWebCrypto = void 0;
var ee = (init_tslib_es62(), __toCommonJS(tslib_es6_exports2)), ne = [ "decrypt", "digest", "encrypt", "exportKey", "generateKey", "importKey", "sign", "verify" ];
_.supportsWebCrypto = function supportsWebCrypto(_) {
if (supportsSecureRandom(_) && "object" == typeof _.crypto.subtle) return supportsSubtleCrypto(_.crypto.subtle); else return false;
};
function supportsSecureRandom(_) {
if ("object" == typeof _ && "object" == typeof _.crypto) return "function" == typeof _.crypto.getRandomValues; else return false;
}
_.supportsSecureRandom = supportsSecureRandom;
function supportsSubtleCrypto(_) {
return _ && ne.every((function(ee) {
return "function" == typeof _[ee];
}));
}
_.supportsSubtleCrypto = supportsSubtleCrypto;
_.supportsZeroByteGCM = function supportsZeroByteGCM(_) {
return ee.__awaiter(this, void 0, void 0, (function() {
var ne;
return ee.__generator(this, (function(ee) {
switch (ee.label) {
case 0:
if (!supportsSubtleCrypto(_)) return [ 2, false ];
ee.label = 1;
case 1:
ee.trys.push([ 1, 4, , 5 ]);
return [ 4, _.generateKey({
name: "AES-GCM",
length: 128
}, false, [ "encrypt" ]) ];
case 2:
ne = ee.sent();
return [ 4, _.encrypt({
name: "AES-GCM",
iv: new Uint8Array(Array(12)),
additionalData: new Uint8Array(Array(16)),
tagLength: 128
}, ne, new Uint8Array(0)) ];
case 3:
return [ 2, 16 === ee.sent().byteLength ];
case 4:
ee.sent();
return [ 2, false ];
case 5:
return [ 2 ];
}
}));
}));
};
}
}), require_build = __commonJS({
"node_modules/@aws-crypto/supports-web-crypto/build/index.js"(_) {
"use strict";
Object.defineProperty(_, "__esModule", {
value: true
});
(init_tslib_es62(), __toCommonJS(tslib_es6_exports2)).__exportStar(require_supportsWebCrypto(), _);
}
}), tslib_es6_exports3 = {};
__export(tslib_es6_exports3, {
__assign: () => __assign3,
__asyncDelegator: () => __asyncDelegator3,
__asyncGenerator: () => __asyncGenerator3,
__asyncValues: () => __asyncValues3,
__await: () => __await3,
__awaiter: () => __awaiter3,
__classPrivateFieldGet: () => __classPrivateFieldGet3,
__classPrivateFieldSet: () => __classPrivateFieldSet3,
__createBinding: () => __createBinding3,
__decorate: () => __decorate3,
__exportStar: () => __exportStar3,
__extends: () => __extends3,
__generator: () => __generator3,
__importDefault: () => __importDefault3,
__importStar: () => __importStar3,
__makeTemplateObject: () => __makeTemplateObject3,
__metadata: () => __metadata3,
__param: () => __param3,
__read: () => __read3,
__rest: () => __rest3,
__spread: () => __spread3,
__spreadArrays: () => __spreadArrays3,
__values: () => __values3
});
function __extends3(_, ee) {
extendStatics3(_, ee);
function __() {
this.constructor = _;
}
_.prototype = null === ee ? Object.create(ee) : (__.prototype = ee.prototype, new __);
}
function __rest3(_, ee) {
var ne = {};
for (var ie in _) if (Object.prototype.hasOwnProperty.call(_, ie) && ee.indexOf(ie) < 0) ne[ie] = _[ie];
if (null != _ && "function" == typeof Object.getOwnPropertySymbols) {
var re = 0;
for (ie = Object.getOwnPropertySymbols(_); re < ie.length; re++) if (ee.indexOf(ie[re]) < 0 && Object.prototype.propertyIsEnumerable.call(_, ie[re])) ne[ie[re]] = _[ie[re]];
}
return ne;
}
function __decorate3(_, ee, ne, ie) {
var re, se = arguments.length, oe = se < 3 ? ee : null === ie ? ie = Object.getOwnPropertyDescriptor(ee, ne) : ie;
if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) oe = Reflect.decorate(_, ee, ne, ie); else for (var le = _.length - 1; le >= 0; le--) if (re = _[le]) oe = (se < 3 ? re(oe) : se > 3 ? re(ee, ne, oe) : re(ee, ne)) || oe;
return se > 3 && oe && Object.defineProperty(ee, ne, oe), oe;
}
function __param3(_, ee) {
return function(ne, ie) {
ee(ne, ie, _);
};
}
function __metadata3(_, ee) {
if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) return Reflect.metadata(_, ee);
}
function __awaiter3(_, ee, ne, ie) {
return new (ne || (ne = Promise))((function(re, se) {
function fulfilled(_) {
try {
step(ie.next(_));
} catch (_) {
se(_);
}
}
function rejected(_) {
try {
step(ie["throw"](_));
} catch (_) {
se(_);
}
}
function step(_) {
_.done ? re(_.value) : function adopt(_) {
return _ instanceof ne ? _ : new ne((function(ee) {
ee(_);
}));
}(_.value).then(fulfilled, rejected);
}
step((ie = ie.apply(_, ee || [])).next());
}));
}
function __generator3(_, ee) {
var ne, ie, re, se, oe = {
label: 0,
sent: function() {
if (1 & re[0]) throw re[1];
return re[1];
},
trys: [],
ops: []
};
return se = {
next: verb(0),
throw: verb(1),
return: verb(2)
}, "function" == typeof Symbol && (se[Symbol.iterator] = function() {
return this;
}), se;
function verb(se) {
return function(le) {
return function step(se) {
if (ne) throw new TypeError("Generator is already executing.");
for (;oe; ) try {
if (ne = 1, ie && (re = 2 & se[0] ? ie["return"] : se[0] ? ie["throw"] || ((re = ie["return"]) && re.call(ie),
0) : ie.next) && !(re = re.call(ie, se[1])).done) return re;
if (ie = 0, re) se = [ 2 & se[0], re.value ];
switch (se[0]) {
case 0:
case 1:
re = se;
break;
case 4:
oe.label++;
return {
value: se[1],
done: false
};
case 5:
oe.label++;
ie = se[1];
se = [ 0 ];
continue;
case 7:
se = oe.ops.pop();
oe.trys.pop();
continue;
default:
if (!(re = oe.trys, re = re.length > 0 && re[re.length - 1]) && (6 === se[0] || 2 === se[0])) {
oe = 0;
continue;
}
if (3 === se[0] && (!re || se[1] > re[0] && se[1] < re[3])) {
oe.label = se[1];
break;
}
if (6 === se[0] && oe.label < re[1]) {
oe.label = re[1];
re = se;
break;
}
if (re && oe.label < re[2]) {
oe.label = re[2];
oe.ops.push(se);
break;
}
if (re[2]) oe.ops.pop();
oe.trys.pop();
continue;
}
se = ee.call(_, oe);
} catch (_) {
se = [ 6, _ ];
ie = 0;
} finally {
ne = re = 0;
}
if (5 & se[0]) throw se[1];
return {
value: se[0] ? se[1] : void 0,
done: true
};
}([ se, le ]);
};
}
}
function __createBinding3(_, ee, ne, ie) {
if (void 0 === ie) ie = ne;
_[ie] = ee[ne];
}
function __exportStar3(_, ee) {
for (var ne in _) if ("default" !== ne && !ee.hasOwnProperty(ne)) ee[ne] = _[ne];
}
function __values3(_) {
var ee = "function" == typeof Symbol && Symbol.iterator, ne = ee && _[ee], ie = 0;
if (ne) return ne.call(_);
if (_ && "number" == typeof _.length) return {
next: function() {
if (_ && ie >= _.length) _ = void 0;
return {
value: _ && _[ie++],
done: !_
};
}
};
throw new TypeError(ee ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read3(_, ee) {
var ne = "function" == typeof Symbol && _[Symbol.iterator];
if (!ne) return _;
var ie, re, se = ne.call(_), oe = [];
try {
for (;(void 0 === ee || ee-- > 0) && !(ie = se.next()).done; ) oe.push(ie.value);
} catch (_) {
re = {
error: _
};
} finally {
try {
if (ie && !ie.done && (ne = se["return"])) ne.call(se);
} finally {
if (re) throw re.error;
}
}
return oe;
}
function __spread3() {
for (var _ = [], ee = 0; ee < arguments.length; ee++) _ = _.concat(__read3(arguments[ee]));
return _;
}
function __spreadArrays3() {
for (var _ = 0, ee = 0, ne = arguments.length; ee < ne; ee++) _ += arguments[ee].length;
var ie = Array(_), re = 0;
for (ee = 0; ee < ne; ee++) for (var se = arguments[ee], oe = 0, le = se.length; oe < le; oe++,
re++) ie[re] = se[oe];
return ie;
}
function __await3(_) {
return this instanceof __await3 ? (this.v = _, this) : new __await3(_);
}
function __asyncGenerator3(_, ee, ne) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var ie, re = ne.apply(_, ee || []), se = [];
return ie = {}, verb("next"), verb("throw"), verb("return"), ie[Symbol.asyncIterator] = function() {
return this;
}, ie;
function verb(_) {
if (re[_]) ie[_] = function(ee) {
return new Promise((function(ne, ie) {
se.push([ _, ee, ne, ie ]) > 1 || resume(_, ee);
}));
};
}
function resume(_, ee) {
try {
(function step(_) {
_.value instanceof __await3 ? Promise.resolve(_.value.v).then(fulfill, reject) : settle(se[0][2], _);
})(re[_](ee));
} catch (_) {
settle(se[0][3], _);
}
}
function fulfill(_) {
resume("next", _);
}
function reject(_) {
resume("throw", _);
}
function settle(_, ee) {
if (_(ee), se.shift(), se.length) resume(se[0][0], se[0][1]);
}
}
function __asyncDelegator3(_) {
var ee, ne;
return ee = {}, verb("next"), verb("throw", (function(_) {
throw _;
})), verb("return"), ee[Symbol.iterator] = function() {
return this;
}, ee;
function verb(ie, re) {
ee[ie] = _[ie] ? function(ee) {
return (ne = !ne) ? {
value: __await3(_[ie](ee)),
done: "return" === ie
} : re ? re(ee) : ee;
} : re;
}
}
function __asyncValues3(_) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var ee, ne = _[Symbol.asyncIterator];
return ne ? ne.call(_) : (_ = "function" == typeof __values3 ? __values3(_) : _[Symbol.iterator](),
ee = {}, verb("next"), verb("throw"), verb("return"), ee[Symbol.asyncIterator] = function() {
return this;
}, ee);
function verb(ne) {
ee[ne] = _[ne] && function(ee) {
return new Promise((function(ie, re) {
(function settle(_, ee, ne, ie) {
Promise.resolve(ie).then((function(ee) {
_({
value: ee,
done: ne
});
}), ee);
})(ie, re, (ee = _[ne](ee)).done, ee.value);
}));
};
}
}
function __makeTemplateObject3(_, ee) {
if (Object.defineProperty) Object.defineProperty(_, "raw", {
value: ee
}); else _.raw = ee;
return _;
}
function __importStar3(_) {
if (_ && _.__esModule) return _;
var ee = {};
if (null != _) for (var ne in _) if (Object.hasOwnProperty.call(_, ne)) ee[ne] = _[ne];
ee.default = _;
return ee;
}
function __importDefault3(_) {
return _ && _.__esModule ? _ : {
default: _
};
}
function __classPrivateFieldGet3(_, ee) {
if (!ee.has(_)) throw new TypeError("attempted to get private field on non-instance");
return ee.get(_);
}
function __classPrivateFieldSet3(_, ee, ne) {
if (!ee.has(_)) throw new TypeError("attempted to set private field on non-instance");
ee.set(_, ne);
return ne;
}
var extendStatics4, __assign4, init_tslib_es63 = __esm({
"node_modules/@aws-crypto/ie11-detection/node_modules/tslib/tslib.es6.js"() {
extendStatics3 = function(_, ee) {
return (extendStatics3 = Object.setPrototypeOf || {
__proto__: []
} instanceof Array && function(_, ee) {
_.__proto__ = ee;
} || function(_, ee) {
for (var ne in ee) if (ee.hasOwnProperty(ne)) _[ne] = ee[ne];
})(_, ee);
};
__assign3 = function() {
__assign3 = Object.assign || function __assign8(_) {
for (var ee, ne = 1, ie = arguments.length; ne < ie; ne++) {
ee = arguments[ne];
for (var re in ee) if (Object.prototype.hasOwnProperty.call(ee, re)) _[re] = ee[re];
}
return _;
};
return __assign3.apply(this, arguments);
};
}
}), require_CryptoOperation = __commonJS({
"node_modules/@aws-crypto/ie11-detection/build/CryptoOperation.js"(_) {
"use strict";
Object.defineProperty(_, "__esModule", {
value: true
});
}
}), require_Key = __commonJS({
"node_modules/@aws-crypto/ie11-detection/build/Key.js"(_) {
"use strict";
Object.defineProperty(_, "__esModule", {
value: true
});
}
}), require_KeyOperation = __commonJS({
"node_modules/@aws-crypto/ie11-detection/build/KeyOperation.js"(_) {
"use strict";
Object.defineProperty(_, "__esModule", {
value: true
});
}
}), require_MsSubtleCrypto = __commonJS({
"node_modules/@aws-crypto/ie11-detection/build/MsSubtleCrypto.js"(_) {
"use strict";
Object.defineProperty(_, "__esModule", {
value: true
});
}
}), require_MsWindow = __commonJS({
"node_modules/@aws-crypto/ie11-detection/build/MsWindow.js"(_) {
"use strict";
Object.defineProperty(_, "__esModule", {
value: true
});
_.isMsWindow = void 0;
var ee = [ "decrypt", "digest", "encrypt", "exportKey", "generateKey", "importKey", "sign", "verify" ];
_.isMsWindow = function isMsWindow(_) {
if (function quacksLikeAnMsWindow(_) {
return "MSInputMethodContext" in _ && "msCrypto" in _;
}(_) && void 0 !== _.msCrypto.subtle) {
var ne = _.msCrypto, ie = ne.getRandomValues, re = ne.subtle;
return ee.map((function(_) {
return re[_];
})).concat(ie).every((function(_) {
return "function" == typeof _;
}));
}
return false;
};
}
}), require_build2 = __commonJS({
"node_modules/@aws-crypto/ie11-detection/build/index.js"(_) {
"use strict";
Object.defineProperty(_, "__esModule", {
value: true
});
var ee = (init_tslib_es63(), __toCommonJS(tslib_es6_exports3));
ee.__exportStar(require_CryptoOperation(), _);
ee.__exportStar(require_Key(), _);
ee.__exportStar(require_KeyOperation(), _);
ee.__exportStar(require_MsSubtleCrypto(), _);
ee.__exportStar(require_MsWindow(), _);
}
}), require_convertToBuffer = __commonJS({
"node_modules/@aws-crypto/util/build/convertToBuffer.js"(_) {
"use strict";
Object.defineProperty(_, "__esModule", {
value: true
});
_.convertToBuffer = void 0;
var ee = (init_dist_es(), __toCommonJS(dist_es_exports)), ne = "undefined" != typeof Buffer && Buffer.from ? function(_) {
return Buffer.from(_, "utf8");
} : ee.fromUtf8;
_.convertToBuffer = function convertToBuffer2(_) {
if (_ instanceof Uint8Array) return _;
if ("string" == typeof _) return ne(_);
if (ArrayBuffer.isView(_)) return new Uint8Array(_.buffer, _.byteOffset, _.byteLength / Uint8Array.BYTES_PER_ELEMENT); else return new Uint8Array(_);
};
}
}), require_isEmptyData2 = __commonJS({
"node_modules/@aws-crypto/util/build/isEmptyData.js"(_) {
"use strict";
Object.defineProperty(_, "__esModule", {
value: true
});
_.isEmptyData = void 0;
_.isEmptyData = function isEmptyData2(_) {
if ("string" == typeof _) return 0 === _.length; else return 0 === _.byteLength;
};
}
}), require_numToUint8 = __commonJS({
"node_modules/@aws-crypto/util/build/numToUint8.js"(_) {
"use strict";
Object.defineProperty(_, "__esModule", {
value: true
});
_.numToUint8 = void 0;
_.numToUint8 = function numToUint8(_) {
return new Uint8Array([ (4278190080 & _) >> 24, (16711680 & _) >> 16, (65280 & _) >> 8, 255 & _ ]);
};
}
}), require_uint32ArrayFrom = __commonJS({
"node_modules/@aws-crypto/util/build/uint32ArrayFrom.js"(_) {
"use strict";
Object.defineProperty(_, "__esModule", {
value: true
});
_.uint32ArrayFrom = void 0;
_.uint32ArrayFrom = function uint32ArrayFrom(_) {
if (!Uint32Array.from) {
for (var ee = new Uint32Array(_.length), ne = 0; ne < _.length; ) {
ee[ne] = _[ne];
ne += 1;
}
return ee;
}
return Uint32Array.from(_);
};
}
}), require_build3 = __commonJS({
"node_modules/@aws-crypto/util/build/index.js"(_) {
"use strict";
Object.defineProperty(_, "__esModule", {
value: true
});
_.uint32ArrayFrom = _.numToUint8 = _.isEmptyData = _.convertToBuffer = void 0;
var ee = require_convertToBuffer();
Object.defineProperty(_, "convertToBuffer", {
enumerable: true,
get: function() {
return ee.convertToBuffer;
}
});
var ne = require_isEmptyData2();
Object.defineProperty(_, "isEmptyData", {
enumerable: true,
get: function() {
return ne.isEmptyData;
}
});
var ie = require_numToUint8();
Object.defineProperty(_, "numToUint8", {
enumerable: true,
get: function() {
return ie.numToUint8;
}
});
var re = require_uint32ArrayFrom();
Object.defineProperty(_, "uint32ArrayFrom", {
enumerable: true,
get: function() {
return re.uint32ArrayFrom;
}
});
}
}), require_crossPlatformSha1 = __commonJS({
"node_modules/@aws-crypto/sha1-browser/build/crossPlatformSha1.js"(_) {
"use strict";
Object.defineProperty(_, "__esModule", {
value: true
});
_.Sha1 = void 0;
var ee = require_ie11Sha1(), ne = require_webCryptoSha1(), ie = require_build(), re = require_build2(), se = (init_dist_es2(),
__toCommonJS(dist_es_exports2)), oe = require_build3(), le = function() {
function Sha13(_) {
if ((0, ie.supportsWebCrypto)((0, se.locateWindow)())) this.hash = new ne.Sha1(_); else if ((0,
re.isMsWindow)((0, se.locateWindow)())) this.hash = new ee.Sha1(_); else throw new Error("SHA1 not supported");
}
Sha13.prototype.update = function(_, ee) {
this.hash.update((0, oe.convertToBuffer)(_));
};
Sha13.prototype.digest = function() {
return this.hash.digest();
};
Sha13.prototype.reset = function() {
this.hash.reset();
};
return Sha13;
}();
_.Sha1 = le;
}
}), require_build4 = __commonJS({
"node_modules/@aws-crypto/sha1-browser/build/index.js"(_) {
"use strict";
Object.defineProperty(_, "__esModule", {
value: true
});
_.WebCryptoSha1 = _.Ie11Sha1 = void 0;
(init_tslib_es6(), __toCommonJS(tslib_es6_exports)).__exportStar(require_crossPlatformSha1(), _);
var ee = require_ie11Sha1();
Object.defineProperty(_, "Ie11Sha1", {
enumerable: true,
get: function() {
return ee.Sha1;
}
});
var ne = require_webCryptoSha1();
Object.defineProperty(_, "WebCryptoSha1", {
enumerable: true,
get: function() {
return ne.Sha1;
}
});
}
}), tslib_es6_exports4 = {};
__export(tslib_es6_exports4, {
__assign: () => __assign4,
__asyncDelegator: () => __asyncDelegator4,
__asyncGenerator: () => __asyncGenerator4,
__asyncValues: () => __asyncValues4,
__await: () => __await4,
__awaiter: () => __awaiter4,
__classPrivateFieldGet: () => __classPrivateFieldGet4,
__classPrivateFieldSet: () => __classPrivateFieldSet4,
__createBinding: () => __createBinding4,
__decorate: () => __decorate4,
__exportStar: () => __exportStar4,
__extends: () => __extends4,
__generator: () => __generator4,
__importDefault: () => __importDefault4,
__importStar: () => __importStar4,
__makeTemplateObject: () => __makeTemplateObject4,
__metadata: () => __metadata4,
__param: () => __param4,
__read: () => __read4,
__rest: () => __rest4,
__spread: () => __spread4,
__spreadArrays: () => __spreadArrays4,
__values: () => __values4
});
function __extends4(_, ee) {
extendStatics4(_, ee);
function __() {
this.constructor = _;
}
_.prototype = null === ee ? Object.create(ee) : (__.prototype = ee.prototype, new __);
}
function __rest4(_, ee) {
var ne = {};
for (var ie in _) if (Object.prototype.hasOwnProperty.call(_, ie) && ee.indexOf(ie) < 0) ne[ie] = _[ie];
if (null != _ && "function" == typeof Object.getOwnPropertySymbols) {
var re = 0;
for (ie = Object.getOwnPropertySymbols(_); re < ie.length; re++) if (ee.indexOf(ie[re]) < 0 && Object.prototype.propertyIsEnumerable.call(_, ie[re])) ne[ie[re]] = _[ie[re]];
}
return ne;
}
function __decorate4(_, ee, ne, ie) {
var re, se = arguments.length, oe = se < 3 ? ee : null === ie ? ie = Object.getOwnPropertyDescriptor(ee, ne) : ie;
if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) oe = Reflect.decorate(_, ee, ne, ie); else for (var le = _.length - 1; le >= 0; le--) if (re = _[le]) oe = (se < 3 ? re(oe) : se > 3 ? re(ee, ne, oe) : re(ee, ne)) || oe;
return se > 3 && oe && Object.defineProperty(ee, ne, oe), oe;
}
function __param4(_, ee) {
return function(ne, ie) {
ee(ne, ie, _);
};
}
function __metadata4(_, ee) {
if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) return Reflect.metadata(_, ee);
}
function __awaiter4(_, ee, ne, ie) {
return new (ne || (ne = Promise))((function(re, se) {
function fulfilled(_) {
try {
step(ie.next(_));
} catch (_) {
se(_);
}
}
function rejected(_) {
try {
step(ie["throw"](_));
} catch (_) {
se(_);
}
}
function step(_) {
_.done ? re(_.value) : function adopt(_) {
return _ instanceof ne ? _ : new ne((function(ee) {
ee(_);
}));
}(_.value).then(fulfilled, rejected);
}
step((ie = ie.apply(_, ee || [])).next());
}));
}
function __generator4(_, ee) {
var ne, ie, re, se, oe = {
label: 0,
sent: function() {
if (1 & re[0]) throw re[1];
return re[1];
},
trys: [],
ops: []
};
return se = {
next: verb(0),
throw: verb(1),
return: verb(2)
}, "function" == typeof Symbol && (se[Symbol.iterator] = function() {
return this;
}), se;
function verb(se) {
return function(le) {
return function step(se) {
if (ne) throw new TypeError("Generator is already executing.");
for (;oe; ) try {
if (ne = 1, ie && (re = 2 & se[0] ? ie["return"] : se[0] ? ie["throw"] || ((re = ie["return"]) && re.call(ie),
0) : ie.next) && !(re = re.call(ie, se[1])).done) return re;
if (ie = 0, re) se = [ 2 & se[0], re.value ];
switch (se[0]) {
case 0:
case 1:
re = se;
break;
case 4:
oe.label++;
return {
value: se[1],
done: false
};
case 5:
oe.label++;
ie = se[1];
se = [ 0 ];
continue;
case 7:
se = oe.ops.pop();
oe.trys.pop();
continue;
default:
if (!(re = oe.trys, re = re.length > 0 && re[re.length - 1]) && (6 === se[0] || 2 === se[0])) {
oe = 0;
continue;
}
if (3 === se[0] && (!re || se[1] > re[0] && se[1] < re[3])) {
oe.label = se[1];
break;
}
if (6 === se[0] && oe.label < re[1]) {
oe.label = re[1];
re = se;
break;
}
if (re && oe.label < re[2]) {
oe.label = re[2];
oe.ops.push(se);
break;
}
if (re[2]) oe.ops.pop();
oe.trys.pop();
continue;
}
se = ee.call(_, oe);
} catch (_) {
se = [ 6, _ ];
ie = 0;
} finally {
ne = re = 0;
}
if (5 & se[0]) throw se[1];
return {
value: se[0] ? se[1] : void 0,
done: true
};
}([ se, le ]);
};
}
}
function __createBinding4(_, ee, ne, ie) {
if (void 0 === ie) ie = ne;
_[ie] = ee[ne];
}
function __exportStar4(_, ee) {
for (var ne in _) if ("default" !== ne && !ee.hasOwnProperty(ne)) ee[ne] = _[ne];
}
function __values4(_) {
var ee = "function" == typeof Symbol && Symbol.iterator, ne = ee && _[ee], ie = 0;
if (ne) return ne.call(_);
if (_ && "number" == typeof _.length) return {
next: function() {
if (_ && ie >= _.length) _ = void 0;
return {
value: _ && _[ie++],
done: !_
};
}
};
throw new TypeError(ee ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read4(_, ee) {
var ne = "function" == typeof Symbol && _[Symbol.iterator];
if (!ne) return _;
var ie, re, se = ne.call(_), oe = [];
try {
for (;(void 0 === ee || ee-- > 0) && !(ie = se.next()).done; ) oe.push(ie.value);
} catch (_) {
re = {
error: _
};
} finally {
try {
if (ie && !ie.done && (ne = se["return"])) ne.call(se);
} finally {
if (re) throw re.error;
}
}
return oe;
}
function __spread4() {
for (var _ = [], ee = 0; ee < arguments.length; ee++) _ = _.concat(__read4(arguments[ee]));
return _;
}
function __spreadArrays4() {
for (var _ = 0, ee = 0, ne = arguments.length; ee < ne; ee++) _ += arguments[ee].length;
var ie = Array(_), re = 0;
for (ee = 0; ee < ne; ee++) for (var se = arguments[ee], oe = 0, le = se.length; oe < le; oe++,
re++) ie[re] = se[oe];
return ie;
}
function __await4(_) {
return this instanceof __await4 ? (this.v = _, this) : new __await4(_);
}
function __asyncGenerator4(_, ee, ne) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var ie, re = ne.apply(_, ee || []), se = [];
return ie = {}, verb("next"), verb("throw"), verb("return"), ie[Symbol.asyncIterator] = function() {
return this;
}, ie;
function verb(_) {
if (re[_]) ie[_] = function(ee) {
return new Promise((function(ne, ie) {
se.push([ _, ee, ne, ie ]) > 1 || resume(_, ee);
}));
};
}
function resume(_, ee) {
try {
(function step(_) {
_.value instanceof __await4 ? Promise.resolve(_.value.v).then(fulfill, reject) : settle(se[0][2], _);
})(re[_](ee));
} catch (_) {
settle(se[0][3], _);
}
}
function fulfill(_) {
resume("next", _);
}
function reject(_) {
resume("throw", _);
}
function settle(_, ee) {
if (_(ee), se.shift(), se.length) resume(se[0][0], se[0][1]);
}
}
function __asyncDelegator4(_) {
var ee, ne;
return ee = {}, verb("next"), verb("throw", (function(_) {
throw _;
})), verb("return"), ee[Symbol.iterator] = function() {
return this;
}, ee;
function verb(ie, re) {
ee[ie] = _[ie] ? function(ee) {
return (ne = !ne) ? {
value: __await4(_[ie](ee)),
done: "return" === ie
} : re ? re(ee) : ee;
} : re;
}
}
function __asyncValues4(_) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var ee, ne = _[Symbol.asyncIterator];
return ne ? ne.call(_) : (_ = "function" == typeof __values4 ? __values4(_) : _[Symbol.iterator](),
ee = {}, verb("next"), verb("throw"), verb("return"), ee[Symbol.asyncIterator] = function() {
return this;
}, ee);
function verb(ne) {
ee[ne] = _[ne] && function(ee) {
return new Promise((function(ie, re) {
(function settle(_, ee, ne, ie) {
Promise.resolve(ie).then((function(ee) {
_({
value: ee,
done: ne
});
}), ee);
})(ie, re, (ee = _[ne](ee)).done, ee.value);
}));
};
}
}
function __makeTemplateObject4(_, ee) {
if (Object.defineProperty) Object.defineProperty(_, "raw", {
value: ee
}); else _.raw = ee;
return _;
}
function __importStar4(_) {
if (_ && _.__esModule) return _;
var ee = {};
if (null != _) for (var ne in _) if (Object.hasOwnProperty.call(_, ne)) ee[ne] = _[ne];
ee.default = _;
return ee;
}
function __importDefault4(_) {
return _ && _.__esModule ? _ : {
default: _
};
}
function __classPrivateFieldGet4(_, ee) {
if (!ee.has(_)) throw new TypeError("attempted to get private field on non-instance");
return ee.get(_);
}
function __classPrivateFieldSet4(_, ee, ne) {
if (!ee.has(_)) throw new TypeError("attempted to set private field on non-instance");
ee.set(_, ne);
return ne;
}
var extendStatics5, __assign5, init_tslib_es64 = __esm({
"node_modules/@aws-crypto/sha256-browser/node_modules/tslib/tslib.es6.js"() {
extendStatics4 = function(_, ee) {
return (extendStatics4 = Object.setPrototypeOf || {
__proto__: []
} instanceof Array && function(_, ee) {
_.__proto__ = ee;
} || function(_, ee) {
for (var ne in ee) if (ee.hasOwnProperty(ne)) _[ne] = ee[ne];
})(_, ee);
};
__assign4 = function() {
__assign4 = Object.assign || function __assign8(_) {
for (var ee, ne = 1, ie = arguments.length; ne < ie; ne++) {
ee = arguments[ne];
for (var re in ee) if (Object.prototype.hasOwnProperty.call(ee, re)) _[re] = ee[re];
}
return _;
};
return __assign4.apply(this, arguments);
};
}
}), require_isEmptyData3 = __commonJS({
"node_modules/@aws-crypto/sha256-browser/build/isEmptyData.js"(_) {
"use strict";
Object.defineProperty(_, "__esModule", {
value: true
});
_.isEmptyData = void 0;
_.isEmptyData = function isEmptyData2(_) {
if ("string" == typeof _) return 0 === _.length; else return 0 === _.byteLength;
};
}
}), require_constants2 = __commonJS({
"node_modules/@aws-crypto/sha256-browser/build/constants.js"(_) {
"use strict";
Object.defineProperty(_, "__esModule", {
value: true
});
_.EMPTY_DATA_SHA_256 = _.SHA_256_HMAC_ALGO = _.SHA_256_HASH = void 0;
_.SHA_256_HASH = {
name: "SHA-256"
};
_.SHA_256_HMAC_ALGO = {
name: "HMAC",
hash: _.SHA_256_HASH
};
_.EMPTY_DATA_SHA_256 = new Uint8Array([ 227, 176, 196, 66, 152, 252, 28, 20, 154, 251, 244, 200, 153, 111, 185, 36, 39, 174, 65, 228, 100, 155, 147, 76, 164, 149, 153, 27, 120, 82, 184, 85 ]);
}
}), require_ie11Sha256 = __commonJS({
"node_modules/@aws-crypto/sha256-browser/build/ie11Sha256.js"(_) {
"use strict";
Object.defineProperty(_, "__esModule", {
value: true
});
_.Sha256 = void 0;
var ee = require_isEmptyData3(), ne = require_constants2(), ie = (init_dist_es(),
__toCommonJS(dist_es_exports)), re = (init_dist_es2(), __toCommonJS(dist_es_exports2)), se = function() {
function Sha2563(_) {
this.secret = _;
this.reset();
}
Sha2563.prototype.update = function(_) {
var ne = this;
if (!(0, ee.isEmptyData)(_)) {
this.operation = this.operation.then((function(ee) {
ee.onerror = function() {
ne.operation = Promise.reject(new Error("Error encountered updating hash"));
};
ee.process(toArrayBufferView(_));
return ee;
}));
this.operation.catch((function() {}));
}
};
Sha2563.prototype.digest = function() {
return this.operation.then((function(_) {
return new Promise((function(ee, ne) {
_.onerror = function() {
ne(new Error("Error encountered finalizing hash"));
};
_.oncomplete = function() {
if (_.result) ee(new Uint8Array(_.result));
ne(new Error("Error encountered finalizing hash"));
};
_.finish();
}));
}));
};
Sha2563.prototype.reset = function() {
if (this.secret) {
this.operation = function getKeyPromise(_) {
return new Promise((function(ee, ie) {
var se = (0, re.locateWindow)().msCrypto.subtle.importKey("raw", toArrayBufferView(_), ne.SHA_256_HMAC_ALGO, false, [ "sign" ]);
se.oncomplete = function() {
if (se.result) ee(se.result);
ie(new Error("ImportKey completed without importing key."));
};
se.onerror = function() {
ie(new Error("ImportKey failed to import key."));
};
}));
}(this.secret).then((function(_) {
return (0, re.locateWindow)().msCrypto.subtle.sign(ne.SHA_256_HMAC_ALGO, _);
}));
this.operation.catch((function() {}));
} else this.operation = Promise.resolve((0, re.locateWindow)().msCrypto.subtle.digest("SHA-256"));
};
return Sha2563;
}();
_.Sha256 = se;
function toArrayBufferView(_) {
if ("string" == typeof _) return (0, ie.fromUtf8)(_);
if (ArrayBuffer.isView(_)) return new Uint8Array(_.buffer, _.byteOffset, _.byteLength / Uint8Array.BYTES_PER_ELEMENT); else return new Uint8Array(_);
}
}
}), require_webCryptoSha256 = __commonJS({
"node_modules/@aws-crypto/sha256-browser/build/webCryptoSha256.js"(_) {
"use strict";
Object.defineProperty(_, "__esModule", {
value: true
});
_.Sha256 = void 0;
var ee = require_build3(), ne = require_constants2(), ie = (init_dist_es2(), __toCommonJS(dist_es_exports2)), re = function() {
function Sha2563(_) {
this.toHash = new Uint8Array(0);
this.secret = _;
this.reset();
}
Sha2563.prototype.update = function(_) {
if (!(0, ee.isEmptyData)(_)) {
var ne = (0, ee.convertToBuffer)(_), ie = new Uint8Array(this.toHash.byteLength + ne.byteLength);
ie.set(this.toHash, 0);
ie.set(ne, this.toHash.byteLength);
this.toHash = ie;
}
};
Sha2563.prototype.digest = function() {
var _ = this;
if (this.key) return this.key.then((function(ee) {
return (0, ie.locateWindow)().crypto.subtle.sign(ne.SHA_256_HMAC_ALGO, ee, _.toHash).then((function(_) {
return new Uint8Array(_);
}));
}));
if ((0, ee.isEmptyData)(this.toHash)) return Promise.resolve(ne.EMPTY_DATA_SHA_256); else return Promise.resolve().then((function() {
return (0, ie.locateWindow)().crypto.subtle.digest(ne.SHA_256_HASH, _.toHash);
})).then((function(_) {
return Promise.resolve(new Uint8Array(_));
}));
};
Sha2563.prototype.reset = function() {
var _ = this;
this.toHash = new Uint8Array(0);
if (this.secret && void 0 !== this.secret) {
this.key = new Promise((function(re, se) {
(0, ie.locateWindow)().crypto.subtle.importKey("raw", (0, ee.convertToBuffer)(_.secret), ne.SHA_256_HMAC_ALGO, false, [ "sign" ]).then(re, se);
}));
this.key.catch((function() {}));
}
};
return Sha2563;
}();
_.Sha256 = re;
}
}), tslib_es6_exports5 = {};
__export(tslib_es6_exports5, {
__assign: () => __assign5,
__asyncDelegator: () => __asyncDelegator5,
__asyncGenerator: () => __asyncGenerator5,
__asyncValues: () => __asyncValues5,
__await: () => __await5,
__awaiter: () => __awaiter5,
__classPrivateFieldGet: () => __classPrivateFieldGet5,
__classPrivateFieldSet: () => __classPrivateFieldSet5,
__createBinding: () => __createBinding5,
__decorate: () => __decorate5,
__exportStar: () => __exportStar5,
__extends: () => __extends5,
__generator: () => __generator5,
__importDefault: () => __importDefault5,
__importStar: () => __importStar5,
__makeTemplateObject: () => __makeTemplateObject5,
__metadata: () => __metadata5,
__param: () => __param5,
__read: () => __read5,
__rest: () => __rest5,
__spread: () => __spread5,
__spreadArrays: () => __spreadArrays5,
__values: () => __values5
});
function __extends5(_, ee) {
extendStatics5(_, ee);
function __() {
this.constructor = _;
}
_.prototype = null === ee ? Object.create(ee) : (__.prototype = ee.prototype, new __);
}
function __rest5(_, ee) {
var ne = {};
for (var ie in _) if (Object.prototype.hasOwnProperty.call(_, ie) && ee.indexOf(ie) < 0) ne[ie] = _[ie];
if (null != _ && "function" == typeof Object.getOwnPropertySymbols) {
var re = 0;
for (ie = Object.getOwnPropertySymbols(_); re < ie.length; re++) if (ee.indexOf(ie[re]) < 0 && Object.prototype.propertyIsEnumerable.call(_, ie[re])) ne[ie[re]] = _[ie[re]];
}
return ne;
}
function __decorate5(_, ee, ne, ie) {
var re, se = arguments.length, oe = se < 3 ? ee : null === ie ? ie = Object.getOwnPropertyDescriptor(ee, ne) : ie;
if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) oe = Reflect.decorate(_, ee, ne, ie); else for (var le = _.length - 1; le >= 0; le--) if (re = _[le]) oe = (se < 3 ? re(oe) : se > 3 ? re(ee, ne, oe) : re(ee, ne)) || oe;
return se > 3 && oe && Object.defineProperty(ee, ne, oe), oe;
}
function __param5(_, ee) {
return function(ne, ie) {
ee(ne, ie, _);
};
}
function __metadata5(_, ee) {
if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) return Reflect.metadata(_, ee);
}
function __awaiter5(_, ee, ne, ie) {
return new (ne || (ne = Promise))((function(re, se) {
function fulfilled(_) {
try {
step(ie.next(_));
} catch (_) {
se(_);
}
}
function rejected(_) {
try {
step(ie["throw"](_));
} catch (_) {
se(_);
}
}
function step(_) {
_.done ? re(_.value) : function adopt(_) {
return _ instanceof ne ? _ : new ne((function(ee) {
ee(_);
}));
}(_.value).then(fulfilled, rejected);
}
step((ie = ie.apply(_, ee || [])).next());
}));
}
function __generator5(_, ee) {
var ne, ie, re, se, oe = {
label: 0,
sent: function() {
if (1 & re[0]) throw re[1];
return re[1];
},
trys: [],
ops: []
};
return se = {
next: verb(0),
throw: verb(1),
return: verb(2)
}, "function" == typeof Symbol && (se[Symbol.iterator] = function() {
return this;
}), se;
function verb(se) {
return function(le) {
return function step(se) {
if (ne) throw new TypeError("Generator is already executing.");
for (;oe; ) try {
if (ne = 1, ie && (re = 2 & se[0] ? ie["return"] : se[0] ? ie["throw"] || ((re = ie["return"]) && re.call(ie),
0) : ie.next) && !(re = re.call(ie, se[1])).done) return re;
if (ie = 0, re) se = [ 2 & se[0], re.value ];
switch (se[0]) {
case 0:
case 1:
re = se;
break;
case 4:
oe.label++;
return {
value: se[1],
done: false
};
case 5:
oe.label++;
ie = se[1];
se = [ 0 ];
continue;
case 7:
se = oe.ops.pop();
oe.trys.pop();
continue;
default:
if (!(re = oe.trys, re = re.length > 0 && re[re.length - 1]) && (6 === se[0] || 2 === se[0])) {
oe = 0;
continue;
}
if (3 === se[0] && (!re || se[1] > re[0] && se[1] < re[3])) {
oe.label = se[1];
break;
}
if (6 === se[0] && oe.label < re[1]) {
oe.label = re[1];
re = se;
break;
}
if (re && oe.label < re[2]) {
oe.label = re[2];
oe.ops.push(se);
break;
}
if (re[2]) oe.ops.pop();
oe.trys.pop();
continue;
}
se = ee.call(_, oe);
} catch (_) {
se = [ 6, _ ];
ie = 0;
} finally {
ne = re = 0;
}
if (5 & se[0]) throw se[1];
return {
value: se[0] ? se[1] : void 0,
done: true
};
}([ se, le ]);
};
}
}
function __createBinding5(_, ee, ne, ie) {
if (void 0 === ie) ie = ne;
_[ie] = ee[ne];
}
function __exportStar5(_, ee) {
for (var ne in _) if ("default" !== ne && !ee.hasOwnProperty(ne)) ee[ne] = _[ne];
}
function __values5(_) {
var ee = "function" == typeof Symbol && Symbol.iterator, ne = ee && _[ee], ie = 0;
if (ne) return ne.call(_);
if (_ && "number" == typeof _.length) return {
next: function() {
if (_ && ie >= _.length) _ = void 0;
return {
value: _ && _[ie++],
done: !_
};
}
};
throw new TypeError(ee ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read5(_, ee) {
var ne = "function" == typeof Symbol && _[Symbol.iterator];
if (!ne) return _;
var ie, re, se = ne.call(_), oe = [];
try {
for (;(void 0 === ee || ee-- > 0) && !(ie = se.next()).done; ) oe.push(ie.value);
} catch (_) {
re = {
error: _
};
} finally {
try {
if (ie && !ie.done && (ne = se["return"])) ne.call(se);
} finally {
if (re) throw re.error;
}
}
return oe;
}
function __spread5() {
for (var _ = [], ee = 0; ee < arguments.length; ee++) _ = _.concat(__read5(arguments[ee]));
return _;
}
function __spreadArrays5() {
for (var _ = 0, ee = 0, ne = arguments.length; ee < ne; ee++) _ += arguments[ee].length;
var ie = Array(_), re = 0;
for (ee = 0; ee < ne; ee++) for (var se = arguments[ee], oe = 0, le = se.length; oe < le; oe++,
re++) ie[re] = se[oe];
return ie;
}
function __await5(_) {
return this instanceof __await5 ? (this.v = _, this) : new __await5(_);
}
function __asyncGenerator5(_, ee, ne) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var ie, re = ne.apply(_, ee || []), se = [];
return ie = {}, verb("next"), verb("throw"), verb("return"), ie[Symbol.asyncIterator] = function() {
return this;
}, ie;
function verb(_) {
if (re[_]) ie[_] = function(ee) {
return new Promise((function(ne, ie) {
se.push([ _, ee, ne, ie ]) > 1 || resume(_, ee);
}));
};
}
function resume(_, ee) {
try {
(function step(_) {
_.value instanceof __await5 ? Promise.resolve(_.value.v).then(fulfill, reject) : settle(se[0][2], _);
})(re[_](ee));
} catch (_) {
settle(se[0][3], _);
}
}
function fulfill(_) {
resume("next", _);
}
function reject(_) {
resume("throw", _);
}
function settle(_, ee) {
if (_(ee), se.shift(), se.length) resume(se[0][0], se[0][1]);
}
}
function __asyncDelegator5(_) {
var ee, ne;
return ee = {}, verb("next"), verb("throw", (function(_) {
throw _;
})), verb("return"), ee[Symbol.iterator] = function() {
return this;
}, ee;
function verb(ie, re) {
ee[ie] = _[ie] ? function(ee) {
return (ne = !ne) ? {
value: __await5(_[ie](ee)),
done: "return" === ie
} : re ? re(ee) : ee;
} : re;
}
}
function __asyncValues5(_) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var ee, ne = _[Symbol.asyncIterator];
return ne ? ne.call(_) : (_ = "function" == typeof __values5 ? __values5(_) : _[Symbol.iterator](),
ee = {}, verb("next"), verb("throw"), verb("return"), ee[Symbol.asyncIterator] = function() {
return this;
}, ee);
function verb(ne) {
ee[ne] = _[ne] && function(ee) {
return new Promise((function(ie, re) {
(function settle(_, ee, ne, ie) {
Promise.resolve(ie).then((function(ee) {
_({
value: ee,
done: ne
});
}), ee);
})(ie, re, (ee = _[ne](ee)).done, ee.value);
}));
};
}
}
function __makeTemplateObject5(_, ee) {
if (Object.defineProperty) Object.defineProperty(_, "raw", {
value: ee
}); else _.raw = ee;
return _;
}
function __importStar5(_) {
if (_ && _.__esModule) return _;
var ee = {};
if (null != _) for (var ne in _) if (Object.hasOwnProperty.call(_, ne)) ee[ne] = _[ne];
ee.default = _;
return ee;
}
function __importDefault5(_) {
return _ && _.__esModule ? _ : {
default: _
};
}
function __classPrivateFieldGet5(_, ee) {
if (!ee.has(_)) throw new TypeError("attempted to get private field on non-instance");
return ee.get(_);
}
function __classPrivateFieldSet5(_, ee, ne) {
if (!ee.has(_)) throw new TypeError("attempted to set private field on non-instance");
ee.set(_, ne);
return ne;
}
var extendStatics6, __assign6, init_tslib_es65 = __esm({
"node_modules/@aws-crypto/sha256-js/node_modules/tslib/tslib.es6.js"() {
extendStatics5 = function(_, ee) {
return (extendStatics5 = Object.setPrototypeOf || {
__proto__: []
} instanceof Array && function(_, ee) {
_.__proto__ = ee;
} || function(_, ee) {
for (var ne in ee) if (ee.hasOwnProperty(ne)) _[ne] = ee[ne];
})(_, ee);
};
__assign5 = function() {
__assign5 = Object.assign || function __assign8(_) {
for (var ee, ne = 1, ie = arguments.length; ne < ie; ne++) {
ee = arguments[ne];
for (var re in ee) if (Object.prototype.hasOwnProperty.call(ee, re)) _[re] = ee[re];
}
return _;
};
return __assign5.apply(this, arguments);
};
}
}), require_constants3 = __commonJS({
"node_modules/@aws-crypto/sha256-js/build/constants.js"(_) {
"use strict";
Object.defineProperty(_, "__esModule", {
value: true
});
_.MAX_HASHABLE_LENGTH = _.INIT = _.KEY = _.DIGEST_LENGTH = _.BLOCK_SIZE = void 0;
_.BLOCK_SIZE = 64;
_.DIGEST_LENGTH = 32;
_.KEY = new Uint32Array([ 1116352408, 1899447441, 3049323471, 3921009573, 961987163, 1508970993, 2453635748, 2870763221, 3624381080, 310598401, 607225278, 1426881987, 1925078388, 2162078206, 2614888103, 3248222580, 3835390401, 4022224774, 264347078, 604807628, 770255983, 1249150122, 1555081692, 1996064986, 2554220882, 2821834349, 2952996808, 3210313671, 3336571891, 3584528711, 113926993, 338241895, 666307205, 773529912, 1294757372, 1396182291, 1695183700, 1986661051, 2177026350, 2456956037, 2730485921, 2820302411, 3259730800, 3345764771, 3516065817, 3600352804, 4094571909, 275423344, 430227734, 506948616, 659060556, 883997877, 958139571, 1322822218, 1537002063, 1747873779, 1955562222, 2024104815, 2227730452, 2361852424, 2428436474, 2756734187, 3204031479, 3329325298 ]);
_.INIT = [ 1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225 ];
_.MAX_HASHABLE_LENGTH = Math.pow(2, 53) - 1;
}
}), require_RawSha256 = __commonJS({
"node_modules/@aws-crypto/sha256-js/build/RawSha256.js"(_) {
"use strict";
Object.defineProperty(_, "__esModule", {
value: true
});
_.RawSha256 = void 0;
var ee = require_constants3(), ne = function() {
function RawSha2562() {
this.state = Int32Array.from(ee.INIT);
this.temp = new Int32Array(64);
this.buffer = new Uint8Array(64);
this.bufferLength = 0;
this.bytesHashed = 0;
this.finished = false;
}
RawSha2562.prototype.update = function(_) {
if (this.finished) throw new Error("Attempted to update an already finished hash.");
var ne = 0, ie = _.byteLength;
this.bytesHashed += ie;
if (8 * this.bytesHashed > ee.MAX_HASHABLE_LENGTH) throw new Error("Cannot hash more than 2^53 - 1 bits");
for (;ie > 0; ) {
this.buffer[this.bufferLength++] = _[ne++];
ie--;
if (this.bufferLength === ee.BLOCK_SIZE) {
this.hashBuffer();
this.bufferLength = 0;
}
}
};
RawSha2562.prototype.digest = function() {
if (!this.finished) {
var _ = 8 * this.bytesHashed, ne = new DataView(this.buffer.buffer, this.buffer.byteOffset, this.buffer.byteLength), ie = this.bufferLength;
ne.setUint8(this.bufferLength++, 128);
if (ie % ee.BLOCK_SIZE >= ee.BLOCK_SIZE - 8) {
for (var re = this.bufferLength; re < ee.BLOCK_SIZE; re++) ne.setUint8(re, 0);
this.hashBuffer();
this.bufferLength = 0;
}
for (re = this.bufferLength; re < ee.BLOCK_SIZE - 8; re++) ne.setUint8(re, 0);
ne.setUint32(ee.BLOCK_SIZE - 8, Math.floor(_ / 4294967296), true);
ne.setUint32(ee.BLOCK_SIZE - 4, _);
this.hashBuffer();
this.finished = true;
}
var se = new Uint8Array(ee.DIGEST_LENGTH);
for (re = 0; re < 8; re++) {
se[4 * re] = this.state[re] >>> 24 & 255;
se[4 * re + 1] = this.state[re] >>> 16 & 255;
se[4 * re + 2] = this.state[re] >>> 8 & 255;
se[4 * re + 3] = this.state[re] >>> 0 & 255;
}
return se;
};
RawSha2562.prototype.hashBuffer = function() {
for (var _ = this.buffer, ne = this.state, ie = ne[0], re = ne[1], se = ne[2], oe = ne[3], le = ne[4], ue = ne[5], de = ne[6], fe = ne[7], he = 0; he < ee.BLOCK_SIZE; he++) {
if (he < 16) this.temp[he] = (255 & _[4 * he]) << 24 | (255 & _[4 * he + 1]) << 16 | (255 & _[4 * he + 2]) << 8 | 255 & _[4 * he + 3]; else {
var pe = this.temp[he - 2], ge = (pe >>> 17 | pe << 15) ^ (pe >>> 19 | pe << 13) ^ pe >>> 10, me = ((pe = this.temp[he - 15]) >>> 7 | pe << 25) ^ (pe >>> 18 | pe << 14) ^ pe >>> 3;
this.temp[he] = (ge + this.temp[he - 7] | 0) + (me + this.temp[he - 16] | 0);
}
var ye = (((le >>> 6 | le << 26) ^ (le >>> 11 | le << 21) ^ (le >>> 25 | le << 7)) + (le & ue ^ ~le & de) | 0) + (fe + (ee.KEY[he] + this.temp[he] | 0) | 0) | 0, ve = ((ie >>> 2 | ie << 30) ^ (ie >>> 13 | ie << 19) ^ (ie >>> 22 | ie << 10)) + (ie & re ^ ie & se ^ re & se) | 0;
fe = de;
de = ue;
ue = le;
le = oe + ye | 0;
oe = se;
se = re;
re = ie;
ie = ye + ve | 0;
}
ne[0] += ie;
ne[1] += re;
ne[2] += se;
ne[3] += oe;
ne[4] += le;
ne[5] += ue;
ne[6] += de;
ne[7] += fe;
};
return RawSha2562;
}();
_.RawSha256 = ne;
}
}), require_jsSha256 = __commonJS({
"node_modules/@aws-crypto/sha256-js/build/jsSha256.js"(_) {
"use strict";
Object.defineProperty(_, "__esModule", {
value: true
});
_.Sha256 = void 0;
var ee = (init_tslib_es65(), __toCommonJS(tslib_es6_exports5)), ne = require_constants3(), ie = require_RawSha256(), re = require_build3(), se = function() {
function Sha2563(_) {
this.secret = _;
this.hash = new ie.RawSha256;
this.reset();
}
Sha2563.prototype.update = function(_) {
if (!(0, re.isEmptyData)(_) && !this.error) try {
this.hash.update((0, re.convertToBuffer)(_));
} catch (_) {
this.error = _;
}
};
Sha2563.prototype.digestSync = function() {
if (this.error) throw this.error;
if (this.outer) {
if (!this.outer.finished) this.outer.update(this.hash.digest());
return this.outer.digest();
}
return this.hash.digest();
};
Sha2563.prototype.digest = function() {
return ee.__awaiter(this, void 0, void 0, (function() {
return ee.__generator(this, (function(_) {
return [ 2, this.digestSync() ];
}));
}));
};
Sha2563.prototype.reset = function() {
this.hash = new ie.RawSha256;
if (this.secret) {
this.outer = new ie.RawSha256;
var _ = function bufferFromSecret(_) {
var ee = (0, re.convertToBuffer)(_);
if (ee.byteLength > ne.BLOCK_SIZE) {
var se = new ie.RawSha256;
se.update(ee);
ee = se.digest();
}
var oe = new Uint8Array(ne.BLOCK_SIZE);
oe.set(ee);
return oe;
}(this.secret), ee = new Uint8Array(ne.BLOCK_SIZE);
ee.set(_);
for (var se = 0; se < ne.BLOCK_SIZE; se++) {
_[se] ^= 54;
ee[se] ^= 92;
}
this.hash.update(_);
this.outer.update(ee);
for (se = 0; se < _.byteLength; se++) _[se] = 0;
}
};
return Sha2563;
}();
_.Sha256 = se;
}
}), require_build5 = __commonJS({
"node_modules/@aws-crypto/sha256-js/build/index.js"(_) {
"use strict";
Object.defineProperty(_, "__esModule", {
value: true
});
(init_tslib_es65(), __toCommonJS(tslib_es6_exports5)).__exportStar(require_jsSha256(), _);
}
}), require_crossPlatformSha256 = __commonJS({
"node_modules/@aws-crypto/sha256-browser/build/crossPlatformSha256.js"(_) {
"use strict";
Object.defineProperty(_, "__esModule", {
value: true
});
_.Sha256 = void 0;
var ee = require_ie11Sha256(), ne = require_webCryptoSha256(), ie = require_build5(), re = require_build(), se = require_build2(), oe = (init_dist_es2(),
__toCommonJS(dist_es_exports2)), le = require_build3(), ue = function() {
function Sha2563(_) {
if ((0, re.supportsWebCrypto)((0, oe.locateWindow)())) this.hash = new ne.Sha256(_); else if ((0,
se.isMsWindow)((0, oe.locateWindow)())) this.hash = new ee.Sha256(_); else this.hash = new ie.Sha256(_);
}
Sha2563.prototype.update = function(_, ee) {
this.hash.update((0, le.convertToBuffer)(_));
};
Sha2563.prototype.digest = function() {
return this.hash.digest();
};
Sha2563.prototype.reset = function() {
this.hash.reset();
};
return Sha2563;
}();
_.Sha256 = ue;
}
}), require_build6 = __commonJS({
"node_modules/@aws-crypto/sha256-browser/build/index.js"(_) {
"use strict";
Object.defineProperty(_, "__esModule", {
value: true
});
_.WebCryptoSha256 = _.Ie11Sha256 = void 0;
(init_tslib_es64(), __toCommonJS(tslib_es6_exports4)).__exportStar(require_crossPlatformSha256(), _);
var ee = require_ie11Sha256();
Object.defineProperty(_, "Ie11Sha256", {
enumerable: true,
get: function() {
return ee.Sha256;
}
});
var ne = require_webCryptoSha256();
Object.defineProperty(_, "WebCryptoSha256", {
enumerable: true,
get: function() {
return ne.Sha256;
}
});
}
}), require_es5 = __commonJS({
"node_modules/bowser/es5.js"(_, ee) {
ne = _, ie = function() {
return function(_) {
var ee = {};
function r2(ne) {
if (ee[ne]) return ee[ne].exports;
var ie = ee[ne] = {
i: ne,
l: false,
exports: {}
};
return _[ne].call(ie.exports, ie, ie.exports, r2), ie.l = true, ie.exports;
}
return r2.m = _, r2.c = ee, r2.d = function(_, ee, ne) {
r2.o(_, ee) || Object.defineProperty(_, ee, {
enumerable: true,
get: ne
});
}, r2.r = function(_) {
"undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(_, Symbol.toStringTag, {
value: "Module"
}), Object.defineProperty(_, "__esModule", {
value: true
});
}, r2.t = function(_, ee) {
if (1 & ee && (_ = r2(_)), 8 & ee) return _;
if (4 & ee && "object" == typeof _ && _ && _.__esModule) return _;
var ne = Object.create(null);
if (r2.r(ne), Object.defineProperty(ne, "default", {
enumerable: true,
value: _
}), 2 & ee && "string" != typeof _) for (var ie in _) r2.d(ne, ie, (function(ee) {
return _[ee];
}).bind(null, ie));
return ne;
}, r2.n = function(_) {
var ee = _ && _.__esModule ? function() {
return _.default;
} : function() {
return _;
};
return r2.d(ee, "a", ee), ee;
}, r2.o = function(_, ee) {
return Object.prototype.hasOwnProperty.call(_, ee);
}, r2.p = "", r2(r2.s = 90);
}({
17: function(_, ee, ne) {
"use strict";
ee.__esModule = true, ee.default = void 0;
var ie = ne(18), re = function() {
function e5() {}
return e5.getFirstMatch = function(_, ee) {
var ne = ee.match(_);
return ne && ne.length > 0 && ne[1] || "";
}, e5.getSecondMatch = function(_, ee) {
var ne = ee.match(_);
return ne && ne.length > 1 && ne[2] || "";
}, e5.matchAndReturnConst = function(_, ee, ne) {
if (_.test(ee)) return ne;
}, e5.getWindowsVersionName = function(_) {
switch (_) {
case "NT":
return "NT";
case "XP":
return "XP";
case "NT 5.0":
return "2000";
case "NT 5.1":
return "XP";
case "NT 5.2":
return "2003";
case "NT 6.0":
return "Vista";
case "NT 6.1":
return "7";
case "NT 6.2":
return "8";
case "NT 6.3":
return "8.1";
case "NT 10.0":
return "10";
default:
return;
}
}, e5.getMacOSVersionName = function(_) {
var ee = _.split(".").splice(0, 2).map((function(_) {
return parseInt(_, 10) || 0;
}));
if (ee.push(0), 10 === ee[0]) switch (ee[1]) {
case 5:
return "Leopard";
case 6:
return "Snow Leopard";
case 7:
return "Lion";
case 8:
return "Mountain Lion";
case 9:
return "Mavericks";
case 10:
return "Yosemite";
case 11:
return "El Capitan";
case 12:
return "Sierra";
case 13:
return "High Sierra";
case 14:
return "Mojave";
case 15:
return "Catalina";
default:
return;
}
}, e5.getAndroidVersionName = function(_) {
var ee = _.split(".").splice(0, 2).map((function(_) {
return parseInt(_, 10) || 0;
}));
if (ee.push(0), !(1 === ee[0] && ee[1] < 5)) return 1 === ee[0] && ee[1] < 6 ? "Cupcake" : 1 === ee[0] && ee[1] >= 6 ? "Donut" : 2 === ee[0] && ee[1] < 2 ? "Eclair" : 2 === ee[0] && 2 === ee[1] ? "Froyo" : 2 === ee[0] && ee[1] > 2 ? "Gingerbread" : 3 === ee[0] ? "Honeycomb" : 4 === ee[0] && ee[1] < 1 ? "Ice Cream Sandwich" : 4 === ee[0] && ee[1] < 4 ? "Jelly Bean" : 4 === ee[0] && ee[1] >= 4 ? "KitKat" : 5 === ee[0] ? "Lollipop" : 6 === ee[0] ? "Marshmallow" : 7 === ee[0] ? "Nougat" : 8 === ee[0] ? "Oreo" : 9 === ee[0] ? "Pie" : void 0;
}, e5.getVersionPrecision = function(_) {
return _.split(".").length;
}, e5.compareVersions = function(_, ee, ne) {
void 0 === ne && (ne = false);
var ie = e5.getVersionPrecision(_), re = e5.getVersionPrecision(ee), se = Math.max(ie, re), oe = 0, le = e5.map([ _, ee ], (function(_) {
var ee = se - e5.getVersionPrecision(_), ne = _ + new Array(ee + 1).join(".0");
return e5.map(ne.split("."), (function(_) {
return new Array(20 - _.length).join("0") + _;
})).reverse();
}));
for (ne && (oe = se - Math.min(ie, re)), se -= 1; se >= oe; ) {
if (le[0][se] > le[1][se]) return 1;
if (le[0][se] === le[1][se]) {
if (se === oe) return 0;
se -= 1;
} else if (le[0][se] < le[1][se]) return -1;
}
}, e5.map = function(_, ee) {
var ne, ie = [];
if (Array.prototype.map) return Array.prototype.map.call(_, ee);
for (ne = 0; ne < _.length; ne += 1) ie.push(ee(_[ne]));
return ie;
}, e5.find = function(_, ee) {
var ne, ie;
if (Array.prototype.find) return Array.prototype.find.call(_, ee);
for (ne = 0, ie = _.length; ne < ie; ne += 1) {
var re = _[ne];
if (ee(re, ne)) return re;
}
}, e5.assign = function(_) {
for (var ee, ne, ie = _, re = arguments.length, se = new Array(re > 1 ? re - 1 : 0), oe = 1; oe < re; oe++) se[oe - 1] = arguments[oe];
if (Object.assign) return Object.assign.apply(Object, [ _ ].concat(se));
var o2 = function() {
var _ = se[ee];
"object" == typeof _ && null !== _ && Object.keys(_).forEach((function(ee) {
ie[ee] = _[ee];
}));
};
for (ee = 0, ne = se.length; ee < ne; ee += 1) o2();
return _;
}, e5.getBrowserAlias = function(_) {
return ie.BROWSER_ALIASES_MAP[_];
}, e5.getBrowserTypeByAlias = function(_) {
return ie.BROWSER_MAP[_] || "";
}, e5;
}();
ee.default = re, _.exports = ee.default;
},
18: function(_, ee, ne) {
"use strict";
ee.__esModule = true, ee.ENGINE_MAP = ee.OS_MAP = ee.PLATFORMS_MAP = ee.BROWSER_MAP = ee.BROWSER_ALIASES_MAP = void 0;
ee.BROWSER_ALIASES_MAP = {
"Amazon Silk": "amazon_silk",
"Android Browser": "android",
Bada: "bada",
BlackBerry: "blackberry",
Chrome: "chrome",
Chromium: "chromium",
Electron: "electron",
Epiphany: "epiphany",
Firefox: "firefox",
Focus: "focus",
Generic: "generic",
"Google Search": "google_search",
Googlebot: "googlebot",
"Internet Explorer": "ie",
"K-Meleon": "k_meleon",
Maxthon: "maxthon",
"Microsoft Edge": "edge",
"MZ Browser": "mz",
"NAVER Whale Browser": "naver",
Opera: "opera",
"Opera Coast": "opera_coast",
PhantomJS: "phantomjs",
Puffin: "puffin",
QupZilla: "qupzilla",
QQ: "qq",
QQLite: "qqlite",
Safari: "safari",
Sailfish: "sailfish",
"Samsung Internet for Android": "samsung_internet",
SeaMonkey: "seamonkey",
Sleipnir: "sleipnir",
Swing: "swing",
Tizen: "tizen",
"UC Browser": "uc",
Vivaldi: "vivaldi",
"WebOS Browser": "webos",
WeChat: "wechat",
"Yandex Browser": "yandex",
Roku: "roku"
};
ee.BROWSER_MAP = {
amazon_silk: "Amazon Silk",
android: "Android Browser",
bada: "Bada",
blackberry: "BlackBerry",
chrome: "Chrome",
chromium: "Chromium",
electron: "Electron",
epiphany: "Epiphany",
firefox: "Firefox",
focus: "Focus",
generic: "Generic",
googlebot: "Googlebot",
google_search: "Google Search",
ie: "Internet Explorer",
k_meleon: "K-Meleon",
maxthon: "Maxthon",
edge: "Microsoft Edge",
mz: "MZ Browser",
naver: "NAVER Whale Browser",
opera: "Opera",
opera_coast: "Opera Coast",
phantomjs: "PhantomJS",
puffin: "Puffin",
qupzilla: "QupZilla",
qq: "QQ Browser",
qqlite: "QQ Browser Lite",
safari: "Safari",
sailfish: "Sailfish",
samsung_internet: "Samsung Internet for Android",
seamonkey: "SeaMonkey",
sleipnir: "Sleipnir",
swing: "Swing",
tizen: "Tizen",
uc: "UC Browser",
vivaldi: "Vivaldi",
webos: "WebOS Browser",
wechat: "WeChat",
yandex: "Yandex Browser"
};
ee.PLATFORMS_MAP = {
tablet: "tablet",
mobile: "mobile",
desktop: "desktop",
tv: "tv"
};
ee.OS_MAP = {
WindowsPhone: "Windows Phone",
Windows: "Windows",
MacOS: "macOS",
iOS: "iOS",
Android: "Android",
WebOS: "WebOS",
BlackBerry: "BlackBerry",
Bada: "Bada",
Tizen: "Tizen",
Linux: "Linux",
ChromeOS: "Chrome OS",
PlayStation4: "PlayStation 4",
Roku: "Roku"
};
ee.ENGINE_MAP = {
EdgeHTML: "EdgeHTML",
Blink: "Blink",
Trident: "Trident",
Presto: "Presto",
Gecko: "Gecko",
WebKit: "WebKit"
};
},
90: function(_, ee, ne) {
"use strict";
ee.__esModule = true, ee.default = void 0;
var ie, re = (ie = ne(91)) && ie.__esModule ? ie : {
default: ie
}, se = ne(18), oe = function() {
function e5() {}
var _;
return e5.getParser = function(_, ee) {
if (void 0 === ee && (ee = false), "string" != typeof _) throw new Error("UserAgent should be a string");
return new re.default(_, ee);
}, e5.parse = function(_) {
return new re.default(_).getResult();
}, (_ = [ {
key: "BROWSER_MAP",
get: function() {
return se.BROWSER_MAP;
}
}, {
key: "ENGINE_MAP",
get: function() {
return se.ENGINE_MAP;
}
}, {
key: "OS_MAP",
get: function() {
return se.OS_MAP;
}
}, {
key: "PLATFORMS_MAP",
get: function() {
return se.PLATFORMS_MAP;
}
} ]) && function a3(_, ee) {
for (var ne = 0; ne < ee.length; ne++) {
var ie = ee[ne];
ie.enumerable = ie.enumerable || false, ie.configurable = true, "value" in ie && (ie.writable = true),
Object.defineProperty(_, ie.key, ie);
}
}(e5, _), e5;
}();
ee.default = oe, _.exports = ee.default;
},
91: function(_, ee, ne) {
"use strict";
ee.__esModule = true, ee.default = void 0;
var ie = u2(ne(92)), re = u2(ne(93)), se = u2(ne(94)), oe = u2(ne(95)), le = u2(ne(17));
function u2(_) {
return _ && _.__esModule ? _ : {
default: _
};
}
var ue = function() {
function e5(_, ee) {
if (void 0 === ee && (ee = false), null == _ || "" === _) throw new Error("UserAgent parameter can't be empty");
this._ua = _, this.parsedResult = {}, true !== ee && this.parse();
}
var _ = e5.prototype;
return _.getUA = function() {
return this._ua;
}, _.test = function(_) {
return _.test(this._ua);
}, _.parseBrowser = function() {
var _ = this;
this.parsedResult.browser = {};
var ee = le.default.find(ie.default, (function(ee) {
if ("function" == typeof ee.test) return ee.test(_);
if (ee.test instanceof Array) return ee.test.some((function(ee) {
return _.test(ee);
}));
throw new Error("Browser's test function is not valid");
}));
return ee && (this.parsedResult.browser = ee.describe(this.getUA())), this.parsedResult.browser;
}, _.getBrowser = function() {
return this.parsedResult.browser ? this.parsedResult.browser : this.parseBrowser();
}, _.getBrowserName = function(_) {
return _ ? String(this.getBrowser().name).toLowerCase() || "" : this.getBrowser().name || "";
}, _.getBrowserVersion = function() {
return this.getBrowser().version;
}, _.getOS = function() {
return this.parsedResult.os ? this.parsedResult.os : this.parseOS();
}, _.parseOS = function() {
var _ = this;
this.parsedResult.os = {};
var ee = le.default.find(re.default, (function(ee) {
if ("function" == typeof ee.test) return ee.test(_);
if (ee.test instanceof Array) return ee.test.some((function(ee) {
return _.test(ee);
}));
throw new Error("Browser's test function is not valid");
}));
return ee && (this.parsedResult.os = ee.describe(this.getUA())), this.parsedResult.os;
}, _.getOSName = function(_) {
var ee = this.getOS().name;
return _ ? String(ee).toLowerCase() || "" : ee || "";
}, _.getOSVersion = function() {
return this.getOS().version;
}, _.getPlatform = function() {
return this.parsedResult.platform ? this.parsedResult.platform : this.parsePlatform();
}, _.getPlatformType = function(_) {
void 0 === _ && (_ = false);
var ee = this.getPlatform().type;
return _ ? String(ee).toLowerCase() || "" : ee || "";
}, _.parsePlatform = function() {
var _ = this;
this.parsedResult.platform = {};
var ee = le.default.find(se.default, (function(ee) {
if ("function" == typeof ee.test) return ee.test(_);
if (ee.test instanceof Array) return ee.test.some((function(ee) {
return _.test(ee);
}));
throw new Error("Browser's test function is not valid");
}));
return ee && (this.parsedResult.platform = ee.describe(this.getUA())), this.parsedResult.platform;
}, _.getEngine = function() {
return this.parsedResult.engine ? this.parsedResult.engine : this.parseEngine();
}, _.getEngineName = function(_) {
return _ ? String(this.getEngine().name).toLowerCase() || "" : this.getEngine().name || "";
}, _.parseEngine = function() {
var _ = this;
this.parsedResult.engine = {};
var ee = le.default.find(oe.default, (function(ee) {
if ("function" == typeof ee.test) return ee.test(_);
if (ee.test instanceof Array) return ee.test.some((function(ee) {
return _.test(ee);
}));
throw new Error("Browser's test function is not valid");
}));
return ee && (this.parsedResult.engine = ee.describe(this.getUA())), this.parsedResult.engine;
}, _.parse = function() {
return this.parseBrowser(), this.parseOS(), this.parsePlatform(), this.parseEngine(),
this;
}, _.getResult = function() {
return le.default.assign({}, this.parsedResult);
}, _.satisfies = function(_) {
var ee = this, ne = {}, ie = 0, re = {}, se = 0;
if (Object.keys(_).forEach((function(ee) {
var oe = _[ee];
"string" == typeof oe ? (re[ee] = oe, se += 1) : "object" == typeof oe && (ne[ee] = oe,
ie += 1);
})), ie > 0) {
var oe = Object.keys(ne), ue = le.default.find(oe, (function(_) {
return ee.isOS(_);
}));
if (ue) {
var de = this.satisfies(ne[ue]);
if (void 0 !== de) return de;
}
var fe = le.default.find(oe, (function(_) {
return ee.isPlatform(_);
}));
if (fe) {
var he = this.satisfies(ne[fe]);
if (void 0 !== he) return he;
}
}
if (se > 0) {
var pe = Object.keys(re), ge = le.default.find(pe, (function(_) {
return ee.isBrowser(_, true);
}));
if (void 0 !== ge) return this.compareVersion(re[ge]);
}
}, _.isBrowser = function(_, ee) {
void 0 === ee && (ee = false);
var ne = this.getBrowserName().toLowerCase(), ie = _.toLowerCase(), re = le.default.getBrowserTypeByAlias(ie);
return ee && re && (ie = re.toLowerCase()), ie === ne;
}, _.compareVersion = function(_) {
var ee = [ 0 ], ne = _, ie = false, re = this.getBrowserVersion();
if ("string" == typeof re) return ">" === _[0] || "<" === _[0] ? (ne = _.substr(1),
"=" === _[1] ? (ie = true, ne = _.substr(2)) : ee = [], ">" === _[0] ? ee.push(1) : ee.push(-1)) : "=" === _[0] ? ne = _.substr(1) : "~" === _[0] && (ie = true,
ne = _.substr(1)), ee.indexOf(le.default.compareVersions(re, ne, ie)) > -1;
}, _.isOS = function(_) {
return this.getOSName(true) === String(_).toLowerCase();
}, _.isPlatform = function(_) {
return this.getPlatformType(true) === String(_).toLowerCase();
}, _.isEngine = function(_) {
return this.getEngineName(true) === String(_).toLowerCase();
}, _.is = function(_, ee) {
return void 0 === ee && (ee = false), this.isBrowser(_, ee) || this.isOS(_) || this.isPlatform(_);
}, _.some = function(_) {
var ee = this;
return void 0 === _ && (_ = []), _.some((function(_) {
return ee.is(_);
}));
}, e5;
}();
ee.default = ue, _.exports = ee.default;
},
92: function(_, ee, ne) {
"use strict";
ee.__esModule = true, ee.default = void 0;
var ie, re = (ie = ne(17)) && ie.__esModule ? ie : {
default: ie
}, se = /version\/(\d+(\.?_?\d+)+)/i, oe = [ {
test: [ /googlebot/i ],
describe: function(_) {
var ee = {
name: "Googlebot"
}, ne = re.default.getFirstMatch(/googlebot\/(\d+(\.\d+))/i, _) || re.default.getFirstMatch(se, _);
return ne && (ee.version = ne), ee;
}
}, {
test: [ /opera/i ],
describe: function(_) {
var ee = {
name: "Opera"
}, ne = re.default.getFirstMatch(se, _) || re.default.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i, _);
return ne && (ee.version = ne), ee;
}
}, {
test: [ /opr\/|opios/i ],
describe: function(_) {
var ee = {
name: "Opera"
}, ne = re.default.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i, _) || re.default.getFirstMatch(se, _);
return ne && (ee.version = ne), ee;
}
}, {
test: [ /SamsungBrowser/i ],
describe: function(_) {
var ee = {
name: "Samsung Internet for Android"
}, ne = re.default.getFirstMatch(se, _) || re.default.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i, _);
return ne && (ee.version = ne), ee;
}
}, {
test: [ /Whale/i ],
describe: function(_) {
var ee = {
name: "NAVER Whale Browser"
}, ne = re.default.getFirstMatch(se, _) || re.default.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i, _);
return ne && (ee.version = ne), ee;
}
}, {
test: [ /MZBrowser/i ],
describe: function(_) {
var ee = {
name: "MZ Browser"
}, ne = re.default.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i, _) || re.default.getFirstMatch(se, _);
return ne && (ee.version = ne), ee;
}
}, {
test: [ /focus/i ],
describe: function(_) {
var ee = {
name: "Focus"
}, ne = re.default.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i, _) || re.default.getFirstMatch(se, _);
return ne && (ee.version = ne), ee;
}
}, {
test: [ /swing/i ],
describe: function(_) {
var ee = {
name: "Swing"
}, ne = re.default.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i, _) || re.default.getFirstMatch(se, _);
return ne && (ee.version = ne), ee;
}
}, {
test: [ /coast/i ],
describe: function(_) {
var ee = {
name: "Opera Coast"
}, ne = re.default.getFirstMatch(se, _) || re.default.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i, _);
return ne && (ee.version = ne), ee;
}
}, {
test: [ /opt\/\d+(?:.?_?\d+)+/i ],
describe: function(_) {
var ee = {
name: "Opera Touch"
}, ne = re.default.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i, _) || re.default.getFirstMatch(se, _);
return ne && (ee.version = ne), ee;
}
}, {
test: [ /yabrowser/i ],
describe: function(_) {
var ee = {
name: "Yandex Browser"
}, ne = re.default.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i, _) || re.default.getFirstMatch(se, _);
return ne && (ee.version = ne), ee;
}
}, {
test: [ /ucbrowser/i ],
describe: function(_) {
var ee = {
name: "UC Browser"
}, ne = re.default.getFirstMatch(se, _) || re.default.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i, _);
return ne && (ee.version = ne), ee;
}
}, {
test: [ /Maxthon|mxios/i ],
describe: function(_) {
var ee = {
name: "Maxthon"
}, ne = re.default.getFirstMatch(se, _) || re.default.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i, _);
return ne && (ee.version = ne), ee;
}
}, {
test: [ /epiphany/i ],
describe: function(_) {
var ee = {
name: "Epiphany"
}, ne = re.default.getFirstMatch(se, _) || re.default.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i, _);
return ne && (ee.version = ne), ee;
}
}, {
test: [ /puffin/i ],
describe: function(_) {
var ee = {
name: "Puffin"
}, ne = re.default.getFirstMatch(se, _) || re.default.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i, _);
return ne && (ee.version = ne), ee;
}
}, {
test: [ /sleipnir/i ],
describe: function(_) {
var ee = {
name: "Sleipnir"
}, ne = re.default.getFirstMatch(se, _) || re.default.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i, _);
return ne && (ee.version = ne), ee;
}
}, {
test: [ /k-meleon/i ],
describe: function(_) {
var ee = {
name: "K-Meleon"
}, ne = re.default.getFirstMatch(se, _) || re.default.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i, _);
return ne && (ee.version = ne), ee;
}
}, {
test: [ /micromessenger/i ],
describe: function(_) {
var ee = {
name: "WeChat"
}, ne = re.default.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i, _) || re.default.getFirstMatch(se, _);
return ne && (ee.version = ne), ee;
}
}, {
test: [ /qqbrowser/i ],
describe: function(_) {
var ee = {
name: /qqbrowserlite/i.test(_) ? "QQ Browser Lite" : "QQ Browser"
}, ne = re.default.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i, _) || re.default.getFirstMatch(se, _);
return ne && (ee.version = ne), ee;
}
}, {
test: [ /msie|trident/i ],
describe: function(_) {
var ee = {
name: "Internet Explorer"
}, ne = re.default.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i, _);
return ne && (ee.version = ne), ee;
}
}, {
test: [ /\sedg\//i ],
describe: function(_) {
var ee = {
name: "Microsoft Edge"
}, ne = re.default.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i, _);
return ne && (ee.version = ne), ee;
}
}, {
test: [ /edg([ea]|ios)/i ],
describe: function(_) {
var ee = {
name: "Microsoft Edge"
}, ne = re.default.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i, _);
return ne && (ee.version = ne), ee;
}
}, {
test: [ /vivaldi/i ],
describe: function(_) {
var ee = {
name: "Vivaldi"
}, ne = re.default.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i, _);
return ne && (ee.version = ne), ee;
}
}, {
test: [ /seamonkey/i ],
describe: function(_) {
var ee = {
name: "SeaMonkey"
}, ne = re.default.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i, _);
return ne && (ee.version = ne), ee;
}
}, {
test: [ /sailfish/i ],
describe: function(_) {
var ee = {
name: "Sailfish"
}, ne = re.default.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i, _);
return ne && (ee.version = ne), ee;
}
}, {
test: [ /silk/i ],
describe: function(_) {
var ee = {
name: "Amazon Silk"
}, ne = re.default.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i, _);
return ne && (ee.version = ne), ee;
}
}, {
test: [ /phantom/i ],
describe: function(_) {
var ee = {
name: "PhantomJS"
}, ne = re.default.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i, _);
return ne && (ee.version = ne), ee;
}
}, {
test: [ /slimerjs/i ],
describe: function(_) {
var ee = {
name: "SlimerJS"
}, ne = re.default.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i, _);
return ne && (ee.version = ne), ee;
}
}, {
test: [ /blackberry|\bbb\d+/i, /rim\stablet/i ],
describe: function(_) {
var ee = {
name: "BlackBerry"
}, ne = re.default.getFirstMatch(se, _) || re.default.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i, _);
return ne && (ee.version = ne), ee;
}
}, {
test: [ /(web|hpw)[o0]s/i ],
describe: function(_) {
var ee = {
name: "WebOS Browser"
}, ne = re.default.getFirstMatch(se, _) || re.default.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i, _);
return ne && (ee.version = ne), ee;
}
}, {
test: [ /bada/i ],
describe: function(_) {
var ee = {
name: "Bada"
}, ne = re.default.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i, _);
return ne && (ee.version = ne), ee;
}
}, {
test: [ /tizen/i ],
describe: function(_) {
var ee = {
name: "Tizen"
}, ne = re.default.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i, _) || re.default.getFirstMatch(se, _);
return ne && (ee.version = ne), ee;
}
}, {
test: [ /qupzilla/i ],
describe: function(_) {
var ee = {
name: "QupZilla"
}, ne = re.default.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i, _) || re.default.getFirstMatch(se, _);
return ne && (ee.version = ne), ee;
}
}, {
test: [ /firefox|iceweasel|fxios/i ],
describe: function(_) {
var ee = {
name: "Firefox"
}, ne = re.default.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i, _);
return ne && (ee.version = ne), ee;
}
}, {
test: [ /electron/i ],
describe: function(_) {
var ee = {
name: "Electron"
}, ne = re.default.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i, _);
return ne && (ee.version = ne), ee;
}
}, {
test: [ /MiuiBrowser/i ],
describe: function(_) {
var ee = {
name: "Miui"
}, ne = re.default.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i, _);
return ne && (ee.version = ne), ee;
}
}, {
test: [ /chromium/i ],
describe: function(_) {
var ee = {
name: "Chromium"
}, ne = re.default.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i, _) || re.default.getFirstMatch(se, _);
return ne && (ee.version = ne), ee;
}
}, {
test: [ /chrome|crios|crmo/i ],
describe: function(_) {
var ee = {
name: "Chrome"
}, ne = re.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i, _);
return ne && (ee.version = ne), ee;
}
}, {
test: [ /GSA/i ],
describe: function(_) {
var ee = {
name: "Google Search"
}, ne = re.default.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i, _);
return ne && (ee.version = ne), ee;
}
}, {
test: function(_) {
var ee = !_.test(/like android/i), ne = _.test(/android/i);
return ee && ne;
},
describe: function(_) {
var ee = {
name: "Android Browser"
}, ne = re.default.getFirstMatch(se, _);
return ne && (ee.version = ne), ee;
}
}, {
test: [ /playstation 4/i ],
describe: function(_) {
var ee = {
name: "PlayStation 4"
}, ne = re.default.getFirstMatch(se, _);
return ne && (ee.version = ne), ee;
}
}, {
test: [ /safari|applewebkit/i ],
describe: function(_) {
var ee = {
name: "Safari"
}, ne = re.default.getFirstMatch(se, _);
return ne && (ee.version = ne), ee;
}
}, {
test: [ /.*/i ],
describe: function(_) {
var ee = -1 !== _.search("\\(") ? /^(.*)\/(.*)[ \t]\((.*)/ : /^(.*)\/(.*) /;
return {
name: re.default.getFirstMatch(ee, _),
version: re.default.getSecondMatch(ee, _)
};
}
} ];
ee.default = oe, _.exports = ee.default;
},
93: function(_, ee, ne) {
"use strict";
ee.__esModule = true, ee.default = void 0;
var ie, re = (ie = ne(17)) && ie.__esModule ? ie : {
default: ie
}, se = ne(18), oe = [ {
test: [ /Roku\/DVP/ ],
describe: function(_) {
var ee = re.default.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i, _);
return {
name: se.OS_MAP.Roku,
version: ee
};
}
}, {
test: [ /windows phone/i ],
describe: function(_) {
var ee = re.default.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i, _);
return {
name: se.OS_MAP.WindowsPhone,
version: ee
};
}
}, {
test: [ /windows /i ],
describe: function(_) {
var ee = re.default.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i, _), ne = re.default.getWindowsVersionName(ee);
return {
name: se.OS_MAP.Windows,
version: ee,
versionName: ne
};
}
}, {
test: [ /Macintosh(.*?) FxiOS(.*?)\// ],
describe: function(_) {
var ee = {
name: se.OS_MAP.iOS
}, ne = re.default.getSecondMatch(/(Version\/)(\d[\d.]+)/, _);
return ne && (ee.version = ne), ee;
}
}, {
test: [ /macintosh/i ],
describe: function(_) {
var ee = re.default.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i, _).replace(/[_\s]/g, "."), ne = re.default.getMacOSVersionName(ee), ie = {
name: se.OS_MAP.MacOS,
version: ee
};
return ne && (ie.versionName = ne), ie;
}
}, {
test: [ /(ipod|iphone|ipad)/i ],
describe: function(_) {
var ee = re.default.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i, _).replace(/[_\s]/g, ".");
return {
name: se.OS_MAP.iOS,
version: ee
};
}
}, {
test: function(_) {
var ee = !_.test(/like android/i), ne = _.test(/android/i);
return ee && ne;
},
describe: function(_) {
var ee = re.default.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i, _), ne = re.default.getAndroidVersionName(ee), ie = {
name: se.OS_MAP.Android,
version: ee
};
return ne && (ie.versionName = ne), ie;
}
}, {
test: [ /(web|hpw)[o0]s/i ],
describe: function(_) {
var ee = re.default.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i, _), ne = {
name: se.OS_MAP.WebOS
};
return ee && ee.length && (ne.version = ee), ne;
}
}, {
test: [ /blackberry|\bbb\d+/i, /rim\stablet/i ],
describe: function(_) {
var ee = re.default.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i, _) || re.default.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i, _) || re.default.getFirstMatch(/\bbb(\d+)/i, _);
return {
name: se.OS_MAP.BlackBerry,
version: ee
};
}
}, {
test: [ /bada/i ],
describe: function(_) {
var ee = re.default.getFirstMatch(/bada\/(\d+(\.\d+)*)/i, _);
return {
name: se.OS_MAP.Bada,
version: ee
};
}
}, {
test: [ /tizen/i ],
describe: function(_) {
var ee = re.default.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i, _);
return {
name: se.OS_MAP.Tizen,
version: ee
};
}
}, {
test: [ /linux/i ],
describe: function() {
return {
name: se.OS_MAP.Linux
};
}
}, {
test: [ /CrOS/ ],
describe: function() {
return {
name: se.OS_MAP.ChromeOS
};
}
}, {
test: [ /PlayStation 4/ ],
describe: function(_) {
var ee = re.default.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i, _);
return {
name: se.OS_MAP.PlayStation4,
version: ee
};
}
} ];
ee.default = oe, _.exports = ee.default;
},
94: function(_, ee, ne) {
"use strict";
ee.__esModule = true, ee.default = void 0;
var ie, re = (ie = ne(17)) && ie.__esModule ? ie : {
default: ie
}, se = ne(18), oe = [ {
test: [ /googlebot/i ],
describe: function() {
return {
type: "bot",
vendor: "Google"
};
}
}, {
test: [ /huawei/i ],
describe: function(_) {
var ee = re.default.getFirstMatch(/(can-l01)/i, _) && "Nova", ne = {
type: se.PLATFORMS_MAP.mobile,
vendor: "Huawei"
};
return ee && (ne.model = ee), ne;
}
}, {
test: [ /nexus\s*(?:7|8|9|10).*/i ],
describe: function() {
return {
type: se.PLATFORMS_MAP.tablet,
vendor: "Nexus"
};
}
}, {
test: [ /ipad/i ],
describe: function() {
return {
type: se.PLATFORMS_MAP.tablet,
vendor: "Apple",
model: "iPad"
};
}
}, {
test: [ /Macintosh(.*?) FxiOS(.*?)\// ],
describe: function() {
return {
type: se.PLATFORMS_MAP.tablet,
vendor: "Apple",
model: "iPad"
};
}
}, {
test: [ /kftt build/i ],
describe: function() {
return {
type: se.PLATFORMS_MAP.tablet,
vendor: "Amazon",
model: "Kindle Fire HD 7"
};
}
}, {
test: [ /silk/i ],
describe: function() {
return {
type: se.PLATFORMS_MAP.tablet,
vendor: "Amazon"
};
}
}, {
test: [ /tablet(?! pc)/i ],
describe: function() {
return {
type: se.PLATFORMS_MAP.tablet
};
}
}, {
test: function(_) {
var ee = _.test(/ipod|iphone/i), ne = _.test(/like (ipod|iphone)/i);
return ee && !ne;
},
describe: function(_) {
var ee = re.default.getFirstMatch(/(ipod|iphone)/i, _);
return {
type: se.PLATFORMS_MAP.mobile,
vendor: "Apple",
model: ee
};
}
}, {
test: [ /nexus\s*[0-6].*/i, /galaxy nexus/i ],
describe: function() {
return {
type: se.PLATFORMS_MAP.mobile,
vendor: "Nexus"
};
}
}, {
test: [ /[^-]mobi/i ],
describe: function() {
return {
type: se.PLATFORMS_MAP.mobile
};
}
}, {
test: function(_) {
return "blackberry" === _.getBrowserName(true);
},
describe: function() {
return {
type: se.PLATFORMS_MAP.mobile,
vendor: "BlackBerry"
};
}
}, {
test: function(_) {
return "bada" === _.getBrowserName(true);
},
describe: function() {
return {
type: se.PLATFORMS_MAP.mobile
};
}
}, {
test: function(_) {
return "windows phone" === _.getBrowserName();
},
describe: function() {
return {
type: se.PLATFORMS_MAP.mobile,
vendor: "Microsoft"
};
}
}, {
test: function(_) {
var ee = Number(String(_.getOSVersion()).split(".")[0]);
return "android" === _.getOSName(true) && ee >= 3;
},
describe: function() {
return {
type: se.PLATFORMS_MAP.tablet
};
}
}, {
test: function(_) {
return "android" === _.getOSName(true);
},
describe: function() {
return {
type: se.PLATFORMS_MAP.mobile
};
}
}, {
test: function(_) {
return "macos" === _.getOSName(true);
},
describe: function() {
return {
type: se.PLATFORMS_MAP.desktop,
vendor: "Apple"
};
}
}, {
test: function(_) {
return "windows" === _.getOSName(true);
},
describe: function() {
return {
type: se.PLATFORMS_MAP.desktop
};
}
}, {
test: function(_) {
return "linux" === _.getOSName(true);
},
describe: function() {
return {
type: se.PLATFORMS_MAP.desktop
};
}
}, {
test: function(_) {
return "playstation 4" === _.getOSName(true);
},
describe: function() {
return {
type: se.PLATFORMS_MAP.tv
};
}
}, {
test: function(_) {
return "roku" === _.getOSName(true);
},
describe: function() {
return {
type: se.PLATFORMS_MAP.tv
};
}
} ];
ee.default = oe, _.exports = ee.default;
},
95: function(_, ee, ne) {
"use strict";
ee.__esModule = true, ee.default = void 0;
var ie, re = (ie = ne(17)) && ie.__esModule ? ie : {
default: ie
}, se = ne(18), oe = [ {
test: function(_) {
return "microsoft edge" === _.getBrowserName(true);
},
describe: function(_) {
if (/\sedg\//i.test(_)) return {
name: se.ENGINE_MAP.Blink
};
var ee = re.default.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i, _);
return {
name: se.ENGINE_MAP.EdgeHTML,
version: ee
};
}
}, {
test: [ /trident/i ],
describe: function(_) {
var ee = {
name: se.ENGINE_MAP.Trident
}, ne = re.default.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i, _);
return ne && (ee.version = ne), ee;
}
}, {
test: function(_) {
return _.test(/presto/i);
},
describe: function(_) {
var ee = {
name: se.ENGINE_MAP.Presto
}, ne = re.default.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i, _);
return ne && (ee.version = ne), ee;
}
}, {
test: function(_) {
var ee = _.test(/gecko/i), ne = _.test(/like gecko/i);
return ee && !ne;
},
describe: function(_) {
var ee = {
name: se.ENGINE_MAP.Gecko
}, ne = re.default.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i, _);
return ne && (ee.version = ne), ee;
}
}, {
test: [ /(apple)?webkit\/537\.36/i ],
describe: function() {
return {
name: se.ENGINE_MAP.Blink
};
}
}, {
test: [ /(apple)?webkit/i ],
describe: function(_) {
var ee = {
name: se.ENGINE_MAP.WebKit
}, ne = re.default.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i, _);
return ne && (ee.version = ne), ee;
}
} ];
ee.default = oe, _.exports = ee.default;
}
});
}, "object" == typeof _ && "object" == typeof ee ? ee.exports = ie() : "function" == typeof define && define.amd ? define([], ie) : "object" == typeof _ ? _.bowser = ie() : ne.bowser = ie();
var ne, ie;
}
}), tslib_es6_exports6 = {};
__export(tslib_es6_exports6, {
__assign: () => __assign6,
__asyncDelegator: () => __asyncDelegator6,
__asyncGenerator: () => __asyncGenerator6,
__asyncValues: () => __asyncValues6,
__await: () => __await6,
__awaiter: () => __awaiter6,
__classPrivateFieldGet: () => __classPrivateFieldGet6,
__classPrivateFieldSet: () => __classPrivateFieldSet6,
__createBinding: () => __createBinding6,
__decorate: () => __decorate6,
__exportStar: () => __exportStar6,
__extends: () => __extends6,
__generator: () => __generator6,
__importDefault: () => __importDefault6,
__importStar: () => __importStar6,
__makeTemplateObject: () => __makeTemplateObject6,
__metadata: () => __metadata6,
__param: () => __param6,
__read: () => __read6,
__rest: () => __rest6,
__spread: () => __spread6,
__spreadArrays: () => __spreadArrays6,
__values: () => __values6
});
function __extends6(_, ee) {
extendStatics6(_, ee);
function __() {
this.constructor = _;
}
_.prototype = null === ee ? Object.create(ee) : (__.prototype = ee.prototype, new __);
}
function __rest6(_, ee) {
var ne = {};
for (var ie in _) if (Object.prototype.hasOwnProperty.call(_, ie) && ee.indexOf(ie) < 0) ne[ie] = _[ie];
if (null != _ && "function" == typeof Object.getOwnPropertySymbols) {
var re = 0;
for (ie = Object.getOwnPropertySymbols(_); re < ie.length; re++) if (ee.indexOf(ie[re]) < 0 && Object.prototype.propertyIsEnumerable.call(_, ie[re])) ne[ie[re]] = _[ie[re]];
}
return ne;
}
function __decorate6(_, ee, ne, ie) {
var re, se = arguments.length, oe = se < 3 ? ee : null === ie ? ie = Object.getOwnPropertyDescriptor(ee, ne) : ie;
if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) oe = Reflect.decorate(_, ee, ne, ie); else for (var le = _.length - 1; le >= 0; le--) if (re = _[le]) oe = (se < 3 ? re(oe) : se > 3 ? re(ee, ne, oe) : re(ee, ne)) || oe;
return se > 3 && oe && Object.defineProperty(ee, ne, oe), oe;
}
function __param6(_, ee) {
return function(ne, ie) {
ee(ne, ie, _);
};
}
function __metadata6(_, ee) {
if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) return Reflect.metadata(_, ee);
}
function __awaiter6(_, ee, ne, ie) {
return new (ne || (ne = Promise))((function(re, se) {
function fulfilled(_) {
try {
step(ie.next(_));
} catch (_) {
se(_);
}
}
function rejected(_) {
try {
step(ie["throw"](_));
} catch (_) {
se(_);
}
}
function step(_) {
_.done ? re(_.value) : function adopt(_) {
return _ instanceof ne ? _ : new ne((function(ee) {
ee(_);
}));
}(_.value).then(fulfilled, rejected);
}
step((ie = ie.apply(_, ee || [])).next());
}));
}
function __generator6(_, ee) {
var ne, ie, re, se, oe = {
label: 0,
sent: function() {
if (1 & re[0]) throw re[1];
return re[1];
},
trys: [],
ops: []
};
return se = {
next: verb(0),
throw: verb(1),
return: verb(2)
}, "function" == typeof Symbol && (se[Symbol.iterator] = function() {
return this;
}), se;
function verb(se) {
return function(le) {
return function step(se) {
if (ne) throw new TypeError("Generator is already executing.");
for (;oe; ) try {
if (ne = 1, ie && (re = 2 & se[0] ? ie["return"] : se[0] ? ie["throw"] || ((re = ie["return"]) && re.call(ie),
0) : ie.next) && !(re = re.call(ie, se[1])).done) return re;
if (ie = 0, re) se = [ 2 & se[0], re.value ];
switch (se[0]) {
case 0:
case 1:
re = se;
break;
case 4:
oe.label++;
return {
value: se[1],
done: false
};
case 5:
oe.label++;
ie = se[1];
se = [ 0 ];
continue;
case 7:
se = oe.ops.pop();
oe.trys.pop();
continue;
default:
if (!(re = oe.trys, re = re.length > 0 && re[re.length - 1]) && (6 === se[0] || 2 === se[0])) {
oe = 0;
continue;
}
if (3 === se[0] && (!re || se[1] > re[0] && se[1] < re[3])) {
oe.label = se[1];
break;
}
if (6 === se[0] && oe.label < re[1]) {
oe.label = re[1];
re = se;
break;
}
if (re && oe.label < re[2]) {
oe.label = re[2];
oe.ops.push(se);
break;
}
if (re[2]) oe.ops.pop();
oe.trys.pop();
continue;
}
se = ee.call(_, oe);
} catch (_) {
se = [ 6, _ ];
ie = 0;
} finally {
ne = re = 0;
}
if (5 & se[0]) throw se[1];
return {
value: se[0] ? se[1] : void 0,
done: true
};
}([ se, le ]);
};
}
}
function __createBinding6(_, ee, ne, ie) {
if (void 0 === ie) ie = ne;
_[ie] = ee[ne];
}
function __exportStar6(_, ee) {
for (var ne in _) if ("default" !== ne && !ee.hasOwnProperty(ne)) ee[ne] = _[ne];
}
function __values6(_) {
var ee = "function" == typeof Symbol && Symbol.iterator, ne = ee && _[ee], ie = 0;
if (ne) return ne.call(_);
if (_ && "number" == typeof _.length) return {
next: function() {
if (_ && ie >= _.length) _ = void 0;
return {
value: _ && _[ie++],
done: !_
};
}
};
throw new TypeError(ee ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read6(_, ee) {
var ne = "function" == typeof Symbol && _[Symbol.iterator];
if (!ne) return _;
var ie, re, se = ne.call(_), oe = [];
try {
for (;(void 0 === ee || ee-- > 0) && !(ie = se.next()).done; ) oe.push(ie.value);
} catch (_) {
re = {
error: _
};
} finally {
try {
if (ie && !ie.done && (ne = se["return"])) ne.call(se);
} finally {
if (re) throw re.error;
}
}
return oe;
}
function __spread6() {
for (var _ = [], ee = 0; ee < arguments.length; ee++) _ = _.concat(__read6(arguments[ee]));
return _;
}
function __spreadArrays6() {
for (var _ = 0, ee = 0, ne = arguments.length; ee < ne; ee++) _ += arguments[ee].length;
var ie = Array(_), re = 0;
for (ee = 0; ee < ne; ee++) for (var se = arguments[ee], oe = 0, le = se.length; oe < le; oe++,
re++) ie[re] = se[oe];
return ie;
}
function __await6(_) {
return this instanceof __await6 ? (this.v = _, this) : new __await6(_);
}
function __asyncGenerator6(_, ee, ne) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var ie, re = ne.apply(_, ee || []), se = [];
return ie = {}, verb("next"), verb("throw"), verb("return"), ie[Symbol.asyncIterator] = function() {
return this;
}, ie;
function verb(_) {
if (re[_]) ie[_] = function(ee) {
return new Promise((function(ne, ie) {
se.push([ _, ee, ne, ie ]) > 1 || resume(_, ee);
}));
};
}
function resume(_, ee) {
try {
(function step(_) {
_.value instanceof __await6 ? Promise.resolve(_.value.v).then(fulfill, reject) : settle(se[0][2], _);
})(re[_](ee));
} catch (_) {
settle(se[0][3], _);
}
}
function fulfill(_) {
resume("next", _);
}
function reject(_) {
resume("throw", _);
}
function settle(_, ee) {
if (_(ee), se.shift(), se.length) resume(se[0][0], se[0][1]);
}
}
function __asyncDelegator6(_) {
var ee, ne;
return ee = {}, verb("next"), verb("throw", (function(_) {
throw _;
})), verb("return"), ee[Symbol.iterator] = function() {
return this;
}, ee;
function verb(ie, re) {
ee[ie] = _[ie] ? function(ee) {
return (ne = !ne) ? {
value: __await6(_[ie](ee)),
done: "return" === ie
} : re ? re(ee) : ee;
} : re;
}
}
function __asyncValues6(_) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var ee, ne = _[Symbol.asyncIterator];
return ne ? ne.call(_) : (_ = "function" == typeof __values6 ? __values6(_) : _[Symbol.iterator](),
ee = {}, verb("next"), verb("throw"), verb("return"), ee[Symbol.asyncIterator] = function() {
return this;
}, ee);
function verb(ne) {
ee[ne] = _[ne] && function(ee) {
return new Promise((function(ie, re) {
(function settle(_, ee, ne, ie) {
Promise.resolve(ie).then((function(ee) {
_({
value: ee,
done: ne
});
}), ee);
})(ie, re, (ee = _[ne](ee)).done, ee.value);
}));
};
}
}
function __makeTemplateObject6(_, ee) {
if (Object.defineProperty) Object.defineProperty(_, "raw", {
value: ee
}); else _.raw = ee;
return _;
}
function __importStar6(_) {
if (_ && _.__esModule) return _;
var ee = {};
if (null != _) for (var ne in _) if (Object.hasOwnProperty.call(_, ne)) ee[ne] = _[ne];
ee.default = _;
return ee;
}
function __importDefault6(_) {
return _ && _.__esModule ? _ : {
default: _
};
}
function __classPrivateFieldGet6(_, ee) {
if (!ee.has(_)) throw new TypeError("attempted to get private field on non-instance");
return ee.get(_);
}
function __classPrivateFieldSet6(_, ee, ne) {
if (!ee.has(_)) throw new TypeError("attempted to set private field on non-instance");
ee.set(_, ne);
return ne;
}
var extendStatics7, __assign7, init_tslib_es66 = __esm({
"node_modules/@aws-crypto/crc32/node_modules/tslib/tslib.es6.js"() {
extendStatics6 = function(_, ee) {
return (extendStatics6 = Object.setPrototypeOf || {
__proto__: []
} instanceof Array && function(_, ee) {
_.__proto__ = ee;
} || function(_, ee) {
for (var ne in ee) if (ee.hasOwnProperty(ne)) _[ne] = ee[ne];
})(_, ee);
};
__assign6 = function() {
__assign6 = Object.assign || function __assign8(_) {
for (var ee, ne = 1, ie = arguments.length; ne < ie; ne++) {
ee = arguments[ne];
for (var re in ee) if (Object.prototype.hasOwnProperty.call(ee, re)) _[re] = ee[re];
}
return _;
};
return __assign6.apply(this, arguments);
};
}
}), require_aws_crc32 = __commonJS({
"node_modules/@aws-crypto/crc32/build/aws_crc32.js"(_) {
"use strict";
Object.defineProperty(_, "__esModule", {
value: true
});
_.AwsCrc32 = void 0;
var ee = (init_tslib_es66(), __toCommonJS(tslib_es6_exports6)), ne = require_build3(), ie = require_build7(), re = function() {
function AwsCrc323() {
this.crc32 = new ie.Crc32;
}
AwsCrc323.prototype.update = function(_) {
if (!(0, ne.isEmptyData)(_)) this.crc32.update((0, ne.convertToBuffer)(_));
};
AwsCrc323.prototype.digest = function() {
return ee.__awaiter(this, void 0, void 0, (function() {
return ee.__generator(this, (function(_) {
return [ 2, (0, ne.numToUint8)(this.crc32.digest()) ];
}));
}));
};
AwsCrc323.prototype.reset = function() {
this.crc32 = new ie.Crc32;
};
return AwsCrc323;
}();
_.AwsCrc32 = re;
}
}), require_build7 = __commonJS({
"node_modules/@aws-crypto/crc32/build/index.js"(_) {
"use strict";
Object.defineProperty(_, "__esModule", {
value: true
});
_.AwsCrc32 = _.Crc32 = _.crc32 = void 0;
var ee = (init_tslib_es66(), __toCommonJS(tslib_es6_exports6)), ne = require_build3();
_.crc32 = function crc32(_) {
return (new ie).update(_).digest();
};
var ie = function() {
function Crc324() {
this.checksum = 4294967295;
}
Crc324.prototype.update = function(_) {
var ne, ie;
try {
for (var se = ee.__values(_), oe = se.next(); !oe.done; oe = se.next()) {
var le = oe.value;
this.checksum = this.checksum >>> 8 ^ re[255 & (this.checksum ^ le)];
}
} catch (_) {
ne = {
error: _
};
} finally {
try {
if (oe && !oe.done && (ie = se.return)) ie.call(se);
} finally {
if (ne) throw ne.error;
}
}
return this;
};
Crc324.prototype.digest = function() {
return (4294967295 ^ this.checksum) >>> 0;
};
return Crc324;
}();
_.Crc32 = ie;
var re = (0, ne.uint32ArrayFrom)([ 0, 1996959894, 3993919788, 2567524794, 124634137, 1886057615, 3915621685, 2657392035, 249268274, 2044508324, 3772115230, 2547177864, 162941995, 2125561021, 3887607047, 2428444049, 498536548, 1789927666, 4089016648, 2227061214, 450548861, 1843258603, 4107580753, 2211677639, 325883990, 1684777152, 4251122042, 2321926636, 335633487, 1661365465, 4195302755, 2366115317, 997073096, 1281953886, 3579855332, 2724688242, 1006888145, 1258607687, 3524101629, 2768942443, 901097722, 1119000684, 3686517206, 2898065728, 853044451, 1172266101, 3705015759, 2882616665, 651767980, 1373503546, 3369554304, 3218104598, 565507253, 1454621731, 3485111705, 3099436303, 671266974, 1594198024, 3322730930, 2970347812, 795835527, 1483230225, 3244367275, 3060149565, 1994146192, 31158534, 2563907772, 4023717930, 1907459465, 112637215, 2680153253, 3904427059, 2013776290, 251722036, 2517215374, 3775830040, 2137656763, 141376813, 2439277719, 3865271297, 1802195444, 476864866, 2238001368, 4066508878, 1812370925, 453092731, 2181625025, 4111451223, 1706088902, 314042704, 2344532202, 4240017532, 1658658271, 366619977, 2362670323, 4224994405, 1303535960, 984961486, 2747007092, 3569037538, 1256170817, 1037604311, 2765210733, 3554079995, 1131014506, 879679996, 2909243462, 3663771856, 1141124467, 855842277, 2852801631, 3708648649, 1342533948, 654459306, 3188396048, 3373015174, 1466479909, 544179635, 3110523913, 3462522015, 1591671054, 702138776, 2966460450, 3352799412, 1504918807, 783551873, 3082640443, 3233442989, 3988292384, 2596254646, 62317068, 1957810842, 3939845945, 2647816111, 81470997, 1943803523, 3814918930, 2489596804, 225274430, 2053790376, 3826175755, 2466906013, 167816743, 2097651377, 4027552580, 2265490386, 503444072, 1762050814, 4150417245, 2154129355, 426522225, 1852507879, 4275313526, 2312317920, 282753626, 1742555852, 4189708143, 2394877945, 397917763, 1622183637, 3604390888, 2714866558, 953729732, 1340076626, 3518719985, 2797360999, 1068828381, 1219638859, 3624741850, 2936675148, 906185462, 1090812512, 3747672003, 2825379669, 829329135, 1181335161, 3412177804, 3160834842, 628085408, 1382605366, 3423369109, 3138078467, 570562233, 1426400815, 3317316542, 2998733608, 733239954, 1555261956, 3268935591, 3050360625, 752459403, 1541320221, 2607071920, 3965973030, 1969922972, 40735498, 2617837225, 3943577151, 1913087877, 83908371, 2512341634, 3803740692, 2075208622, 213261112, 2463272603, 3855990285, 2094854071, 198958881, 2262029012, 4057260610, 1759359992, 534414190, 2176718541, 4139329115, 1873836001, 414664567, 2282248934, 4279200368, 1711684554, 285281116, 2405801727, 4167216745, 1634467795, 376229701, 2685067896, 3608007406, 1308918612, 956543938, 2808555105, 3495958263, 1231636301, 1047427035, 2932959818, 3654703836, 1088359270, 936918e3, 2847714899, 3736837829, 1202900863, 817233897, 3183342108, 3401237130, 1404277552, 615818150, 3134207493, 3453421203, 1423857449, 601450431, 3009837614, 3294710456, 1567103746, 711928724, 3020668471, 3272380065, 1510334235, 755167117 ]), se = require_aws_crc32();
Object.defineProperty(_, "AwsCrc32", {
enumerable: true,
get: function() {
return se.AwsCrc32;
}
});
}
}), tslib_es6_exports7 = {};
__export(tslib_es6_exports7, {
__assign: () => __assign7,
__asyncDelegator: () => __asyncDelegator7,
__asyncGenerator: () => __asyncGenerator7,
__asyncValues: () => __asyncValues7,
__await: () => __await7,
__awaiter: () => __awaiter7,
__classPrivateFieldGet: () => __classPrivateFieldGet7,
__classPrivateFieldSet: () => __classPrivateFieldSet7,
__createBinding: () => __createBinding7,
__decorate: () => __decorate7,
__exportStar: () => __exportStar7,
__extends: () => __extends7,
__generator: () => __generator7,
__importDefault: () => __importDefault7,
__importStar: () => __importStar7,
__makeTemplateObject: () => __makeTemplateObject7,
__metadata: () => __metadata7,
__param: () => __param7,
__read: () => __read7,
__rest: () => __rest7,
__spread: () => __spread7,
__spreadArrays: () => __spreadArrays7,
__values: () => __values7
});
function __extends7(_, ee) {
extendStatics7(_, ee);
function __() {
this.constructor = _;
}
_.prototype = null === ee ? Object.create(ee) : (__.prototype = ee.prototype, new __);
}
function __rest7(_, ee) {
var ne = {};
for (var ie in _) if (Object.prototype.hasOwnProperty.call(_, ie) && ee.indexOf(ie) < 0) ne[ie] = _[ie];
if (null != _ && "function" == typeof Object.getOwnPropertySymbols) {
var re = 0;
for (ie = Object.getOwnPropertySymbols(_); re < ie.length; re++) if (ee.indexOf(ie[re]) < 0 && Object.prototype.propertyIsEnumerable.call(_, ie[re])) ne[ie[re]] = _[ie[re]];
}
return ne;
}
function __decorate7(_, ee, ne, ie) {
var re, se = arguments.length, oe = se < 3 ? ee : null === ie ? ie = Object.getOwnPropertyDescriptor(ee, ne) : ie;
if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) oe = Reflect.decorate(_, ee, ne, ie); else for (var le = _.length - 1; le >= 0; le--) if (re = _[le]) oe = (se < 3 ? re(oe) : se > 3 ? re(ee, ne, oe) : re(ee, ne)) || oe;
return se > 3 && oe && Object.defineProperty(ee, ne, oe), oe;
}
function __param7(_, ee) {
return function(ne, ie) {
ee(ne, ie, _);
};
}
function __metadata7(_, ee) {
if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) return Reflect.metadata(_, ee);
}
function __awaiter7(_, ee, ne, ie) {
return new (ne || (ne = Promise))((function(re, se) {
function fulfilled(_) {
try {
step(ie.next(_));
} catch (_) {
se(_);
}
}
function rejected(_) {
try {
step(ie["throw"](_));
} catch (_) {
se(_);
}
}
function step(_) {
_.done ? re(_.value) : function adopt(_) {
return _ instanceof ne ? _ : new ne((function(ee) {
ee(_);
}));
}(_.value).then(fulfilled, rejected);
}
step((ie = ie.apply(_, ee || [])).next());
}));
}
function __generator7(_, ee) {
var ne, ie, re, se, oe = {
label: 0,
sent: function() {
if (1 & re[0]) throw re[1];
return re[1];
},
trys: [],
ops: []
};
return se = {
next: verb(0),
throw: verb(1),
return: verb(2)
}, "function" == typeof Symbol && (se[Symbol.iterator] = function() {
return this;
}), se;
function verb(se) {
return function(le) {
return function step(se) {
if (ne) throw new TypeError("Generator is already executing.");
for (;oe; ) try {
if (ne = 1, ie && (re = 2 & se[0] ? ie["return"] : se[0] ? ie["throw"] || ((re = ie["return"]) && re.call(ie),
0) : ie.next) && !(re = re.call(ie, se[1])).done) return re;
if (ie = 0, re) se = [ 2 & se[0], re.value ];
switch (se[0]) {
case 0:
case 1:
re = se;
break;
case 4:
oe.label++;
return {
value: se[1],
done: false
};
case 5:
oe.label++;
ie = se[1];
se = [ 0 ];
continue;
case 7:
se = oe.ops.pop();
oe.trys.pop();
continue;
default:
if (!(re = oe.trys, re = re.length > 0 && re[re.length - 1]) && (6 === se[0] || 2 === se[0])) {
oe = 0;
continue;
}
if (3 === se[0] && (!re || se[1] > re[0] && se[1] < re[3])) {
oe.label = se[1];
break;
}
if (6 === se[0] && oe.label < re[1]) {
oe.label = re[1];
re = se;
break;
}
if (re && oe.label < re[2]) {
oe.label = re[2];
oe.ops.push(se);
break;
}
if (re[2]) oe.ops.pop();
oe.trys.pop();
continue;
}
se = ee.call(_, oe);
} catch (_) {
se = [ 6, _ ];
ie = 0;
} finally {
ne = re = 0;
}
if (5 & se[0]) throw se[1];
return {
value: se[0] ? se[1] : void 0,
done: true
};
}([ se, le ]);
};
}
}
function __createBinding7(_, ee, ne, ie) {
if (void 0 === ie) ie = ne;
_[ie] = ee[ne];
}
function __exportStar7(_, ee) {
for (var ne in _) if ("default" !== ne && !ee.hasOwnProperty(ne)) ee[ne] = _[ne];
}
function __values7(_) {
var ee = "function" == typeof Symbol && Symbol.iterator, ne = ee && _[ee], ie = 0;
if (ne) return ne.call(_);
if (_ && "number" == typeof _.length) return {
next: function() {
if (_ && ie >= _.length) _ = void 0;
return {
value: _ && _[ie++],
done: !_
};
}
};
throw new TypeError(ee ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read7(_, ee) {
var ne = "function" == typeof Symbol && _[Symbol.iterator];
if (!ne) return _;
var ie, re, se = ne.call(_), oe = [];
try {
for (;(void 0 === ee || ee-- > 0) && !(ie = se.next()).done; ) oe.push(ie.value);
} catch (_) {
re = {
error: _
};
} finally {
try {
if (ie && !ie.done && (ne = se["return"])) ne.call(se);
} finally {
if (re) throw re.error;
}
}
return oe;
}
function __spread7() {
for (var _ = [], ee = 0; ee < arguments.length; ee++) _ = _.concat(__read7(arguments[ee]));
return _;
}
function __spreadArrays7() {
for (var _ = 0, ee = 0, ne = arguments.length; ee < ne; ee++) _ += arguments[ee].length;
var ie = Array(_), re = 0;
for (ee = 0; ee < ne; ee++) for (var se = arguments[ee], oe = 0, le = se.length; oe < le; oe++,
re++) ie[re] = se[oe];
return ie;
}
function __await7(_) {
return this instanceof __await7 ? (this.v = _, this) : new __await7(_);
}
function __asyncGenerator7(_, ee, ne) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var ie, re = ne.apply(_, ee || []), se = [];
return ie = {}, verb("next"), verb("throw"), verb("return"), ie[Symbol.asyncIterator] = function() {
return this;
}, ie;
function verb(_) {
if (re[_]) ie[_] = function(ee) {
return new Promise((function(ne, ie) {
se.push([ _, ee, ne, ie ]) > 1 || resume(_, ee);
}));
};
}
function resume(_, ee) {
try {
(function step(_) {
_.value instanceof __await7 ? Promise.resolve(_.value.v).then(fulfill, reject) : settle(se[0][2], _);
})(re[_](ee));
} catch (_) {
settle(se[0][3], _);
}
}
function fulfill(_) {
resume("next", _);
}
function reject(_) {
resume("throw", _);
}
function settle(_, ee) {
if (_(ee), se.shift(), se.length) resume(se[0][0], se[0][1]);
}
}
function __asyncDelegator7(_) {
var ee, ne;
return ee = {}, verb("next"), verb("throw", (function(_) {
throw _;
})), verb("return"), ee[Symbol.iterator] = function() {
return this;
}, ee;
function verb(ie, re) {
ee[ie] = _[ie] ? function(ee) {
return (ne = !ne) ? {
value: __await7(_[ie](ee)),
done: "return" === ie
} : re ? re(ee) : ee;
} : re;
}
}
function __asyncValues7(_) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var ee, ne = _[Symbol.asyncIterator];
return ne ? ne.call(_) : (_ = "function" == typeof __values7 ? __values7(_) : _[Symbol.iterator](),
ee = {}, verb("next"), verb("throw"), verb("return"), ee[Symbol.asyncIterator] = function() {
return this;
}, ee);
function verb(ne) {
ee[ne] = _[ne] && function(ee) {
return new Promise((function(ie, re) {
(function settle(_, ee, ne, ie) {
Promise.resolve(ie).then((function(ee) {
_({
value: ee,
done: ne
});
}), ee);
})(ie, re, (ee = _[ne](ee)).done, ee.value);
}));
};
}
}
function __makeTemplateObject7(_, ee) {
if (Object.defineProperty) Object.defineProperty(_, "raw", {
value: ee
}); else _.raw = ee;
return _;
}
function __importStar7(_) {
if (_ && _.__esModule) return _;
var ee = {};
if (null != _) for (var ne in _) if (Object.hasOwnProperty.call(_, ne)) ee[ne] = _[ne];
ee.default = _;
return ee;
}
function __importDefault7(_) {
return _ && _.__esModule ? _ : {
default: _
};
}
function __classPrivateFieldGet7(_, ee) {
if (!ee.has(_)) throw new TypeError("attempted to get private field on non-instance");
return ee.get(_);
}
function __classPrivateFieldSet7(_, ee, ne) {
if (!ee.has(_)) throw new TypeError("attempted to set private field on non-instance");
ee.set(_, ne);
return ne;
}
var init_tslib_es67 = __esm({
"node_modules/@aws-crypto/crc32c/node_modules/tslib/tslib.es6.js"() {
extendStatics7 = function(_, ee) {
return (extendStatics7 = Object.setPrototypeOf || {
__proto__: []
} instanceof Array && function(_, ee) {
_.__proto__ = ee;
} || function(_, ee) {
for (var ne in ee) if (ee.hasOwnProperty(ne)) _[ne] = ee[ne];
})(_, ee);
};
__assign7 = function() {
__assign7 = Object.assign || function __assign8(_) {
for (var ee, ne = 1, ie = arguments.length; ne < ie; ne++) {
ee = arguments[ne];
for (var re in ee) if (Object.prototype.hasOwnProperty.call(ee, re)) _[re] = ee[re];
}
return _;
};
return __assign7.apply(this, arguments);
};
}
}), require_aws_crc32c = __commonJS({
"node_modules/@aws-crypto/crc32c/build/aws_crc32c.js"(_) {
"use strict";
Object.defineProperty(_, "__esModule", {
value: true
});
_.AwsCrc32c = void 0;
var ee = (init_tslib_es67(), __toCommonJS(tslib_es6_exports7)), ne = require_build3(), ie = require_build8(), re = function() {
function AwsCrc32c3() {
this.crc32c = new ie.Crc32c;
}
AwsCrc32c3.prototype.update = function(_) {
if (!(0, ne.isEmptyData)(_)) this.crc32c.update((0, ne.convertToBuffer)(_));
};
AwsCrc32c3.prototype.digest = function() {
return ee.__awaiter(this, void 0, void 0, (function() {
return ee.__generator(this, (function(_) {
return [ 2, (0, ne.numToUint8)(this.crc32c.digest()) ];
}));
}));
};
AwsCrc32c3.prototype.reset = function() {
this.crc32c = new ie.Crc32c;
};
return AwsCrc32c3;
}();
_.AwsCrc32c = re;
}
}), require_build8 = __commonJS({
"node_modules/@aws-crypto/crc32c/build/index.js"(_) {
"use strict";
Object.defineProperty(_, "__esModule", {
value: true
});
_.AwsCrc32c = _.Crc32c = _.crc32c = void 0;
var ee = (init_tslib_es67(), __toCommonJS(tslib_es6_exports7)), ne = require_build3();
_.crc32c = function crc32c(_) {
return (new ie).update(_).digest();
};
var ie = function() {
function Crc32c2() {
this.checksum = 4294967295;
}
Crc32c2.prototype.update = function(_) {
var ne, ie;
try {
for (var se = ee.__values(_), oe = se.next(); !oe.done; oe = se.next()) {
var le = oe.value;
this.checksum = this.checksum >>> 8 ^ re[255 & (this.checksum ^ le)];
}
} catch (_) {
ne = {
error: _
};
} finally {
try {
if (oe && !oe.done && (ie = se.return)) ie.call(se);
} finally {
if (ne) throw ne.error;
}
}
return this;
};
Crc32c2.prototype.digest = function() {
return (4294967295 ^ this.checksum) >>> 0;
};
return Crc32c2;
}();
_.Crc32c = ie;
var re = (0, ne.uint32ArrayFrom)([ 0, 4067132163, 3778769143, 324072436, 3348797215, 904991772, 648144872, 3570033899, 2329499855, 2024987596, 1809983544, 2575936315, 1296289744, 3207089363, 2893594407, 1578318884, 274646895, 3795141740, 4049975192, 51262619, 3619967088, 632279923, 922689671, 3298075524, 2592579488, 1760304291, 2075979607, 2312596564, 1562183871, 2943781820, 3156637768, 1313733451, 549293790, 3537243613, 3246849577, 871202090, 3878099393, 357341890, 102525238, 4101499445, 2858735121, 1477399826, 1264559846, 3107202533, 1845379342, 2677391885, 2361733625, 2125378298, 820201905, 3263744690, 3520608582, 598981189, 4151959214, 85089709, 373468761, 3827903834, 3124367742, 1213305469, 1526817161, 2842354314, 2107672161, 2412447074, 2627466902, 1861252501, 1098587580, 3004210879, 2688576843, 1378610760, 2262928035, 1955203488, 1742404180, 2511436119, 3416409459, 969524848, 714683780, 3639785095, 205050476, 4266873199, 3976438427, 526918040, 1361435347, 2739821008, 2954799652, 1114974503, 2529119692, 1691668175, 2005155131, 2247081528, 3690758684, 697762079, 986182379, 3366744552, 476452099, 3993867776, 4250756596, 255256311, 1640403810, 2477592673, 2164122517, 1922457750, 2791048317, 1412925310, 1197962378, 3037525897, 3944729517, 427051182, 170179418, 4165941337, 746937522, 3740196785, 3451792453, 1070968646, 1905808397, 2213795598, 2426610938, 1657317369, 3053634322, 1147748369, 1463399397, 2773627110, 4215344322, 153784257, 444234805, 3893493558, 1021025245, 3467647198, 3722505002, 797665321, 2197175160, 1889384571, 1674398607, 2443626636, 1164749927, 3070701412, 2757221520, 1446797203, 137323447, 4198817972, 3910406976, 461344835, 3484808360, 1037989803, 781091935, 3705997148, 2460548119, 1623424788, 1939049696, 2180517859, 1429367560, 2807687179, 3020495871, 1180866812, 410100952, 3927582683, 4182430767, 186734380, 3756733383, 763408580, 1053836080, 3434856499, 2722870694, 1344288421, 1131464017, 2971354706, 1708204729, 2545590714, 2229949006, 1988219213, 680717673, 3673779818, 3383336350, 1002577565, 4010310262, 493091189, 238226049, 4233660802, 2987750089, 1082061258, 1395524158, 2705686845, 1972364758, 2279892693, 2494862625, 1725896226, 952904198, 3399985413, 3656866545, 731699698, 4283874585, 222117402, 510512622, 3959836397, 3280807620, 837199303, 582374963, 3504198960, 68661723, 4135334616, 3844915500, 390545967, 1230274059, 3141532936, 2825850620, 1510247935, 2395924756, 2091215383, 1878366691, 2644384480, 3553878443, 565732008, 854102364, 3229815391, 340358836, 3861050807, 4117890627, 119113024, 1493875044, 2875275879, 3090270611, 1247431312, 2660249211, 1828433272, 2141937292, 2378227087, 3811616794, 291187481, 34330861, 4032846830, 615137029, 3603020806, 3314634738, 939183345, 1776939221, 2609017814, 2295496738, 2058945313, 2926798794, 1545135305, 1330124605, 3173225534, 4084100981, 17165430, 307568514, 3762199681, 888469610, 3332340585, 3587147933, 665062302, 2042050490, 2346497209, 2559330125, 1793573966, 3190661285, 1279665062, 1595330642, 2910671697 ]), se = require_aws_crc32c();
Object.defineProperty(_, "AwsCrc32c", {
enumerable: true,
get: function() {
return se.AwsCrc32c;
}
});
}
}), main_exports = {};
__export(main_exports, {
default: () => ObsidianLiveSyncPlugin
});
module.exports = __toCommonJS(main_exports);
var MAX_DOC_SIZE_BIN = 102400, VER = 10, LEAF_WAIT_TIMEOUT = 9e4, REPLICATION_BUSY_TIMEOUT = 3e6, LOG_LEVEL_DEBUG = -1, LOG_LEVEL_VERBOSE = 1, LOG_LEVEL_INFO = 10, LOG_LEVEL_NOTICE = 100, LOG_LEVEL_URGENT = 1e3, CANCELLED = Symbol("cancelled"), AUTO_MERGED = Symbol("auto_merged"), NOT_CONFLICTED = Symbol("not_conflicted"), MISSING_OR_ERROR = Symbol("missing_or_error"), LEAVE_TO_SUBSEQUENT = Symbol("leave_to_subsequent_proc"), TIME_ARGUMENT_INFINITY = Symbol("infinity"), RESULT_TIMED_OUT = Symbol("timed out"), RESULT_NOT_FOUND = Symbol("NotFound"), VERSIONINFO_DOCID = "obsydian_livesync_version", MILSTONE_DOCID = "_local/obsydian_livesync_milestone", NODEINFO_DOCID = "_local/obsydian_livesync_nodeinfo", MODE_SELECTIVE = 0, MODE_AUTOMATIC = 1, MODE_PAUSED = 2, REMOTE_COUCHDB = "", REMOTE_MINIO = "MINIO", DEFAULT_SETTINGS = {
remoteType: REMOTE_COUCHDB,
useCustomRequestHandler: false,
couchDB_URI: "",
couchDB_USER: "",
couchDB_PASSWORD: "",
couchDB_DBNAME: "",
liveSync: false,
syncOnSave: false,
syncOnStart: false,
savingDelay: 200,
lessInformationInLog: false,
gcDelay: 300,
versionUpFlash: "",
minimumChunkSize: 20,
longLineThreshold: 250,
showVerboseLog: false,
suspendFileWatching: false,
trashInsteadDelete: true,
periodicReplication: false,
periodicReplicationInterval: 60,
syncOnFileOpen: false,
encrypt: false,
passphrase: "",
usePathObfuscation: false,
doNotDeleteFolder: false,
resolveConflictsByNewerFile: false,
batchSave: false,
batchSaveMinimumDelay: 5,
batchSaveMaximumDelay: 60,
deviceAndVaultName: "",
usePluginSettings: false,
showOwnPlugins: false,
showStatusOnEditor: true,
showStatusOnStatusbar: true,
showOnlyIconsOnEditor: false,
usePluginSync: false,
autoSweepPlugins: false,
autoSweepPluginsPeriodic: false,
notifyPluginOrSettingUpdated: false,
checkIntegrityOnSave: false,
batch_size: 25,
batches_limit: 25,
useHistory: false,
disableRequestURI: false,
skipOlderFilesOnSync: true,
checkConflictOnlyOnOpen: false,
showMergeDialogOnlyOnActive: false,
syncInternalFiles: false,
syncInternalFilesBeforeReplication: false,
syncInternalFilesIgnorePatterns: "\\/node_modules\\/, \\/\\.git\\/, \\/obsidian-livesync\\/",
syncInternalFilesInterval: 60,
additionalSuffixOfDatabaseName: "",
ignoreVersionCheck: false,
lastReadUpdates: 0,
deleteMetadataOfDeletedFiles: false,
syncIgnoreRegEx: "",
syncOnlyRegEx: "",
customChunkSize: 0,
readChunksOnline: true,
watchInternalFileChanges: true,
automaticallyDeleteMetadataOfDeletedFiles: 0,
disableMarkdownAutoMerge: false,
writeDocumentsIfConflicted: false,
useDynamicIterationCount: false,
syncAfterMerge: false,
configPassphraseStore: "",
encryptedPassphrase: "",
encryptedCouchDBConnection: "",
permitEmptyPassphrase: false,
useIndexedDBAdapter: true,
useTimeouts: false,
writeLogToTheFile: false,
doNotPaceReplication: false,
hashCacheMaxCount: 300,
hashCacheMaxAmount: 50,
concurrencyOfReadChunksOnline: 40,
minimumIntervalOfReadChunksOnline: 50,
hashAlg: "xxhash64",
suspendParseReplicationResult: false,
doNotSuspendOnFetching: false,
useIgnoreFiles: false,
ignoreFiles: ".gitignore",
syncOnEditorSave: false,
pluginSyncExtendedSetting: {},
syncMaxSizeInMB: 50,
settingSyncFile: "",
writeCredentialsForSettingSync: false,
notifyAllSettingSyncFile: false,
isConfigured: void 0,
settingVersion: 0,
enableCompression: false,
accessKey: "",
bucket: "",
endpoint: "",
region: "auto",
secretKey: "",
useEden: false,
maxChunksInEden: 10,
maxTotalLengthInEden: 1024,
maxAgeInEden: 10,
disableCheckingConfigMismatch: false,
displayLanguage: "",
enableChunkSplitterV2: false,
disableWorkerForGeneratingChunks: false,
processSmallFilesInUIThread: false
}, PREFERRED_SETTING_CLOUDANT = {
syncMaxSizeInMB: 50,
customChunkSize: 0,
concurrencyOfReadChunksOnline: 100,
minimumIntervalOfReadChunksOnline: 333
}, PREFERRED_SETTING_SELF_HOSTED = {
...PREFERRED_SETTING_CLOUDANT,
customChunkSize: 50,
concurrencyOfReadChunksOnline: 30,
minimumIntervalOfReadChunksOnline: 25
}, PREFERRED_JOURNAL_SYNC = {
...PREFERRED_SETTING_CLOUDANT,
customChunkSize: 10,
concurrencyOfReadChunksOnline: 30,
minimumIntervalOfReadChunksOnline: 25
}, TweakValuesShouldMatchedTemplate = {
minimumChunkSize: 20,
longLineThreshold: 250,
encrypt: false,
usePathObfuscation: false,
enableCompression: false,
useEden: false,
customChunkSize: 0,
useDynamicIterationCount: false,
hashAlg: "xxhash64",
enableChunkSplitterV2: true
}, TweakValuesRecommendedTemplate = {
maxChunksInEden: 10,
maxTotalLengthInEden: 1024,
maxAgeInEden: 10,
useIgnoreFiles: false,
useCustomRequestHandler: false,
batch_size: 25,
batches_limit: 25,
useIndexedDBAdapter: true,
useTimeouts: false,
readChunksOnline: true,
hashCacheMaxCount: 300,
hashCacheMaxAmount: 50,
concurrencyOfReadChunksOnline: 40,
minimumIntervalOfReadChunksOnline: 50,
ignoreFiles: ".gitignore",
syncMaxSizeInMB: 50,
enableChunkSplitterV2: true
}, configurationNames = {
minimumChunkSize: {
name: "Minimum Chunk Size (Not Configurable from the UI Now)."
},
longLineThreshold: {
name: "Longest chunk line threshold value (Not Configurable from the UI Now)."
},
encrypt: {
name: "End-to-End Encryption",
desc: "Encrypt contents on the remote database. If you use the plugin's synchronization feature, enabling this is recommend."
},
usePathObfuscation: {
name: "Path Obfuscation"
},
enableCompression: {
name: "Data Compression",
status: "EXPERIMENTAL"
},
useEden: {
name: "Incubate Chunks in Document",
desc: "If enabled, newly created chunks are temporarily kept within the document, and graduated to become independent chunks once stabilised.",
status: "BETA"
},
customChunkSize: {
name: "Enhance chunk size"
},
useDynamicIterationCount: {
name: "Use dynamic iteration count",
status: "EXPERIMENTAL"
},
hashAlg: {
name: "The Hash algorithm for chunk IDs",
status: "EXPERIMENTAL"
},
enableChunkSplitterV2: {
name: "Use splitting-limit-capped chunk splitter",
desc: "If enabled, chunks will be split into no more than 100 items. However, dedupe is slightly weaker."
}
};
function statusDisplay(_) {
if (!_) return "";
if ("EXPERIMENTAL" == _) return " (Experimental)";
if ("ALPHA" == _) return " (Alpha)";
if ("BETA" == _) return " (Beta)"; else return ` (${_})`;
}
function confName(_, ee = "") {
var ne, ie;
if (_ in configurationNames) return `${null == (ne = configurationNames[_]) ? void 0 : ne.name}${statusDisplay(null == (ie = configurationNames[_]) ? void 0 : ie.status)}`; else return `${ee || ""}`;
}
var TweakValuesTemplate = {
...TweakValuesRecommendedTemplate,
...TweakValuesShouldMatchedTemplate
}, PREFIXMD_LOGFILE = "LIVESYNC_LOG_", FLAGMD_REDFLAG = "redflag.md", FLAGMD_REDFLAG2 = "redflag2.md", FLAGMD_REDFLAG2_HR = "flag_rebuild.md", FLAGMD_REDFLAG3 = "redflag3.md", FLAGMD_REDFLAG3_HR = "flag_fetch.md", SYNCINFO_ID = "syncinfo", SALT_OF_PASSPHRASE = "rHGMPtr6oWw7VSa3W3wpa8fT8U", PREFIX_OBFUSCATED = "f:", PREFIX_CHUNK = "h:", PREFIX_ENCRYPTED_CHUNK = "h:+", import_obsidian = require("obsidian"), import_obsidian2 = require("obsidian"), import_diff_match_patch = __toESM(require_diff_match_patch(), 1), normalizePath = import_obsidian2.normalizePath, PERIODIC_PLUGIN_SWEEP = 60, CHeader = "h:", PSCHeader = "ps:", ICHeader = "i:", ICHeaderEnd = "i;", ICHeaderLength = ICHeader.length, ICXHeader = "ix:", configURIBase = "obsidian://setuplivesync?settings=", LEVEL_INFO = LOG_LEVEL_INFO, defaultLoggerEnv = {
minLogLevel: LOG_LEVEL_INFO
}, defaultLogger = function defaultLogger2(_, ee = LEVEL_INFO, ne) {
if (ee < defaultLoggerEnv.minLogLevel) return;
const ie = (new Date).toLocaleString(), re = "string" == typeof _ ? _ : _ instanceof Error ? `${_.name}:${_.message}` : JSON.stringify(_, null, 2);
if (_ instanceof Error) console.dir(_.stack);
const se = `${ie}\t${ee}\t${re}`;
console.log(se);
}, _logger = defaultLogger;
function setGlobalLogFunction(_) {
_logger = _;
}
function Logger(_, ee, ne) {
_logger(_, ee, ne);
}
var _root, _hasMagic, _uflag, _parts, _parent, _parentIndex, _negs, _filledNegs, _options, _toString, _emptyExt, _fillNegs, fillNegs_fn, _parseAST, parseAST_fn, _partsToRegExp, partsToRegExp_fn, _parseGlob, parseGlob_fn, LRUCache = class {
constructor(_, ee, ne = false) {
this.cache = new Map([]);
this.revCache = new Map([]);
this.maxCache = 200;
this.maxCachedLength = 5e7;
this.cachedLength = 0;
this.enableReversed = true;
this.maxCache = _ || 200;
this.maxCachedLength = 1e6 * (ee || 1);
this.enableReversed = !ne;
Logger(`Cache initialized ${this.maxCache} / ${this.maxCachedLength}`, LOG_LEVEL_VERBOSE);
}
clear() {
this.cache.clear();
this.revCache.clear();
}
has(_) {
return this.cache.has(_);
}
get(_) {
const ee = this.cache.get(_);
if (ee) {
this.cache.delete(_);
this.cache.set(_, ee);
if (this.enableReversed) {
this.revCache.delete(ee);
this.revCache.set(ee, _);
}
}
return ee;
}
revGet(_) {
const ee = this.revCache.get(_);
if (ee) {
this.cache.delete(ee);
this.revCache.delete(_);
this.cache.set(ee, _);
this.revCache.set(_, ee);
}
return ee;
}
set(_, ee) {
this.cache.set(_, ee);
if (this.enableReversed) this.revCache.set(ee, _);
this.cachedLength += `${ee}`.length;
if (this.cache.size > this.maxCache || this.cachedLength > this.maxCachedLength) for (const [_, ee] of this.cache) {
this.cache.delete(_);
if (this.enableReversed) this.revCache.delete(ee);
this.cachedLength -= `${ee}`.length;
if (this.cache.size <= this.maxCache && this.cachedLength <= this.maxCachedLength) break;
}
}
}, import_brace_expansion = __toESM(require_brace_expansion(), 1), MAX_PATTERN_LENGTH = 65536, assertValidPattern = _ => {
if ("string" != typeof _) throw new TypeError("invalid pattern");
if (_.length > MAX_PATTERN_LENGTH) throw new TypeError("pattern is too long");
}, posixClasses = {
"[:alnum:]": [ "\\p{L}\\p{Nl}\\p{Nd}", true ],
"[:alpha:]": [ "\\p{L}\\p{Nl}", true ],
"[:ascii:]": [ "\\x00-\\x7f", false ],
"[:blank:]": [ "\\p{Zs}\\t", true ],
"[:cntrl:]": [ "\\p{Cc}", true ],
"[:digit:]": [ "\\p{Nd}", true ],
"[:graph:]": [ "\\p{Z}\\p{C}", true, true ],
"[:lower:]": [ "\\p{Ll}", true ],
"[:print:]": [ "\\p{C}", true ],
"[:punct:]": [ "\\p{P}", true ],
"[:space:]": [ "\\p{Z}\\t\\r\\n\\v\\f", true ],
"[:upper:]": [ "\\p{Lu}", true ],
"[:word:]": [ "\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}", true ],
"[:xdigit:]": [ "A-Fa-f0-9", false ]
}, braceEscape = _ => _.replace(/[[\]\\-]/g, "\\$&"), regexpEscape = _ => _.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), rangesToString = _ => _.join(""), parseClass = (_, ee) => {
const ne = ee;
if ("[" !== _.charAt(ne)) throw new Error("not in a brace expression");
const ie = [], re = [];
let se = ne + 1, oe = false, le = false, ue = false, de = false, fe = ne, he = "";
e: for (;se < _.length; ) {
const ee = _.charAt(se);
if ("!" !== ee && "^" !== ee || se !== ne + 1) {
if ("]" === ee && oe && !ue) {
fe = se + 1;
break;
}
oe = true;
if ("\\" === ee) if (!ue) {
ue = true;
se++;
continue;
}
if ("[" === ee && !ue) for (const [ee, [oe, ue, de]] of Object.entries(posixClasses)) if (_.startsWith(ee, se)) {
if (he) return [ "$.", false, _.length - ne, true ];
se += ee.length;
if (de) re.push(oe); else ie.push(oe);
le = le || ue;
continue e;
}
ue = false;
if (!he) if (!_.startsWith("-]", se + 1)) if (!_.startsWith("-", se + 1)) {
ie.push(braceEscape(ee));
se++;
} else {
he = ee;
se += 2;
} else {
ie.push(braceEscape(ee + "-"));
se += 2;
} else {
if (ee > he) ie.push(braceEscape(he) + "-" + braceEscape(ee)); else if (ee === he) ie.push(braceEscape(ee));
he = "";
se++;
}
} else {
de = true;
se++;
}
}
if (fe < se) return [ "", false, 0, false ];
if (!ie.length && !re.length) return [ "$.", false, _.length - ne, true ];
if (0 === re.length && 1 === ie.length && /^\\?.$/.test(ie[0]) && !de) {
const _ = 2 === ie[0].length ? ie[0].slice(-1) : ie[0];
return [ regexpEscape(_), false, fe - ne, false ];
}
const pe = "[" + (de ? "^" : "") + rangesToString(ie) + "]", ge = "[" + (de ? "" : "^") + rangesToString(re) + "]";
return [ ie.length && re.length ? "(" + pe + "|" + ge + ")" : ie.length ? pe : ge, le, fe - ne, true ];
}, unescape2 = (_, {windowsPathsNoEscape: ee = false} = {}) => ee ? _.replace(/\[([^\/\\])\]/g, "$1") : _.replace(/((?!\\).|^)\[([^\/\\])\]/g, "$1$2").replace(/\\([^\/])/g, "$1"), types = new Set([ "!", "?", "+", "*", "@" ]), isExtglobType = _ => types.has(_), startNoTraversal = "(?!(?:^|/)\\.\\.?(?:$|/))", startNoDot = "(?!\\.)", addPatternStart = new Set([ "[", "." ]), justDots = new Set([ "..", "." ]), reSpecials = new Set("().*{}+?[]^$\\!"), regExpEscape = _ => _.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), qmark = "[^/]", star = qmark + "*?", starNoEmpty = qmark + "+?", _AST = class _AST {
constructor(_, ee, ne = {}) {
__privateAdd(this, _fillNegs);
__privateAdd(this, _partsToRegExp);
__publicField(this, "type");
__privateAdd(this, _root, void 0);
__privateAdd(this, _hasMagic, void 0);
__privateAdd(this, _uflag, false);
__privateAdd(this, _parts, []);
__privateAdd(this, _parent, void 0);
__privateAdd(this, _parentIndex, void 0);
__privateAdd(this, _negs, void 0);
__privateAdd(this, _filledNegs, false);
__privateAdd(this, _options, void 0);
__privateAdd(this, _toString, void 0);
__privateAdd(this, _emptyExt, false);
this.type = _;
if (_) __privateSet(this, _hasMagic, true);
__privateSet(this, _parent, ee);
__privateSet(this, _root, __privateGet(this, _parent) ? __privateGet(__privateGet(this, _parent), _root) : this);
__privateSet(this, _options, __privateGet(this, _root) === this ? ne : __privateGet(__privateGet(this, _root), _options));
__privateSet(this, _negs, __privateGet(this, _root) === this ? [] : __privateGet(__privateGet(this, _root), _negs));
if ("!" === _ && !__privateGet(__privateGet(this, _root), _filledNegs)) __privateGet(this, _negs).push(this);
__privateSet(this, _parentIndex, __privateGet(this, _parent) ? __privateGet(__privateGet(this, _parent), _parts).length : 0);
}
get hasMagic() {
if (void 0 !== __privateGet(this, _hasMagic)) return __privateGet(this, _hasMagic);
for (const _ of __privateGet(this, _parts)) if ("string" != typeof _) if (_.type || _.hasMagic) return __privateSet(this, _hasMagic, true);
return __privateGet(this, _hasMagic);
}
toString() {
if (void 0 !== __privateGet(this, _toString)) return __privateGet(this, _toString);
if (!this.type) return __privateSet(this, _toString, __privateGet(this, _parts).map((_ => String(_))).join("")); else return __privateSet(this, _toString, this.type + "(" + __privateGet(this, _parts).map((_ => String(_))).join("|") + ")");
}
push(..._) {
for (const ee of _) if ("" !== ee) {
if ("string" != typeof ee && !(ee instanceof _AST && __privateGet(ee, _parent) === this)) throw new Error("invalid part: " + ee);
__privateGet(this, _parts).push(ee);
}
}
toJSON() {
var _;
const ee = null === this.type ? __privateGet(this, _parts).slice().map((_ => "string" == typeof _ ? _ : _.toJSON())) : [ this.type, ...__privateGet(this, _parts).map((_ => _.toJSON())) ];
if (this.isStart() && !this.type) ee.unshift([]);
if (this.isEnd() && (this === __privateGet(this, _root) || __privateGet(__privateGet(this, _root), _filledNegs) && "!" === (null == (_ = __privateGet(this, _parent)) ? void 0 : _.type))) ee.push({});
return ee;
}
isStart() {
var _;
if (__privateGet(this, _root) === this) return true;
if (!(null == (_ = __privateGet(this, _parent)) ? void 0 : _.isStart())) return false;
if (0 === __privateGet(this, _parentIndex)) return true;
const ee = __privateGet(this, _parent);
for (let _ = 0; _ < __privateGet(this, _parentIndex); _++) {
const ne = __privateGet(ee, _parts)[_];
if (!(ne instanceof _AST && "!" === ne.type)) return false;
}
return true;
}
isEnd() {
var _, ee, ne;
if (__privateGet(this, _root) === this) return true;
if ("!" === (null == (_ = __privateGet(this, _parent)) ? void 0 : _.type)) return true;
if (!(null == (ee = __privateGet(this, _parent)) ? void 0 : ee.isEnd())) return false;
if (!this.type) return null == (ne = __privateGet(this, _parent)) ? void 0 : ne.isEnd();
const ie = __privateGet(this, _parent) ? __privateGet(__privateGet(this, _parent), _parts).length : 0;
return __privateGet(this, _parentIndex) === ie - 1;
}
copyIn(_) {
if ("string" == typeof _) this.push(_); else this.push(_.clone(this));
}
clone(_) {
const ee = new _AST(this.type, _);
for (const _ of __privateGet(this, _parts)) ee.copyIn(_);
return ee;
}
static fromGlob(_, ee = {}) {
var ne;
const ie = new _AST(null, void 0, ee);
__privateMethod(ne = _AST, _parseAST, parseAST_fn).call(ne, _, ie, 0, ee);
return ie;
}
toMMPattern() {
if (this !== __privateGet(this, _root)) return __privateGet(this, _root).toMMPattern();
const _ = this.toString(), [ee, ne, ie, re] = this.toRegExpSource();
if (!(ie || __privateGet(this, _hasMagic) || __privateGet(this, _options).nocase && !__privateGet(this, _options).nocaseMagicOnly && _.toUpperCase() !== _.toLowerCase())) return ne;
const se = (__privateGet(this, _options).nocase ? "i" : "") + (re ? "u" : "");
return Object.assign(new RegExp(`^${ee}$`, se), {
_src: ee,
_glob: _
});
}
toRegExpSource(_) {
var ee;
const ne = null != _ ? _ : !!__privateGet(this, _options).dot;
if (__privateGet(this, _root) === this) __privateMethod(this, _fillNegs, fillNegs_fn).call(this);
if (!this.type) {
const ie = this.isStart() && this.isEnd(), re = __privateGet(this, _parts).map((ee => {
var ne;
const [re, se, oe, le] = "string" == typeof ee ? __privateMethod(ne = _AST, _parseGlob, parseGlob_fn).call(ne, ee, __privateGet(this, _hasMagic), ie) : ee.toRegExpSource(_);
__privateSet(this, _hasMagic, __privateGet(this, _hasMagic) || oe);
__privateSet(this, _uflag, __privateGet(this, _uflag) || le);
return re;
})).join("");
let se = "";
if (this.isStart()) if ("string" == typeof __privateGet(this, _parts)[0]) if (!(1 === __privateGet(this, _parts).length && justDots.has(__privateGet(this, _parts)[0]))) {
const ee = addPatternStart, ie = ne && ee.has(re.charAt(0)) || re.startsWith("\\.") && ee.has(re.charAt(2)) || re.startsWith("\\.\\.") && ee.has(re.charAt(4)), oe = !ne && !_ && ee.has(re.charAt(0));
se = ie ? startNoTraversal : oe ? startNoDot : "";
}
let oe = "";
if (this.isEnd() && __privateGet(__privateGet(this, _root), _filledNegs) && "!" === (null == (ee = __privateGet(this, _parent)) ? void 0 : ee.type)) oe = "(?:$|\\/)";
return [ se + re + oe, unescape2(re), __privateSet(this, _hasMagic, !!__privateGet(this, _hasMagic)), __privateGet(this, _uflag) ];
}
const ie = "*" === this.type || "+" === this.type, re = "!" === this.type ? "(?:(?!(?:" : "(?:";
let se = __privateMethod(this, _partsToRegExp, partsToRegExp_fn).call(this, ne);
if (this.isStart() && this.isEnd() && !se && "!" !== this.type) {
const _ = this.toString();
__privateSet(this, _parts, [ _ ]);
this.type = null;
__privateSet(this, _hasMagic, void 0);
return [ _, unescape2(this.toString()), false, false ];
}
let oe = !ie || _ || ne || !startNoDot ? "" : __privateMethod(this, _partsToRegExp, partsToRegExp_fn).call(this, true);
if (oe === se) oe = "";
if (oe) se = `(?:${se})(?:${oe})*?`;
let le = "";
if ("!" === this.type && __privateGet(this, _emptyExt)) le = (this.isStart() && !ne ? startNoDot : "") + starNoEmpty; else le = re + se + ("!" === this.type ? "))" + (this.isStart() && !ne && !_ ? startNoDot : "") + star + ")" : "@" === this.type ? ")" : "?" === this.type ? ")?" : "+" === this.type && oe ? ")" : "*" === this.type && oe ? ")?" : `)${this.type}`);
return [ le, unescape2(se), __privateSet(this, _hasMagic, !!__privateGet(this, _hasMagic)), __privateGet(this, _uflag) ];
}
};
_root = new WeakMap;
_hasMagic = new WeakMap;
_uflag = new WeakMap;
_parts = new WeakMap;
_parent = new WeakMap;
_parentIndex = new WeakMap;
_negs = new WeakMap;
_filledNegs = new WeakMap;
_options = new WeakMap;
_toString = new WeakMap;
_emptyExt = new WeakMap;
_fillNegs = new WeakSet;
fillNegs_fn = function() {
if (this !== __privateGet(this, _root)) throw new Error("should only call on root");
if (__privateGet(this, _filledNegs)) return this;
this.toString();
__privateSet(this, _filledNegs, true);
let _;
for (;_ = __privateGet(this, _negs).pop(); ) {
if ("!" !== _.type) continue;
let ee = _, ne = __privateGet(ee, _parent);
for (;ne; ) {
for (let ie = __privateGet(ee, _parentIndex) + 1; !ne.type && ie < __privateGet(ne, _parts).length; ie++) for (const ee of __privateGet(_, _parts)) {
if ("string" == typeof ee) throw new Error("string part in extglob AST??");
ee.copyIn(__privateGet(ne, _parts)[ie]);
}
ee = ne;
ne = __privateGet(ee, _parent);
}
}
return this;
};
_parseAST = new WeakSet;
parseAST_fn = function(_, ee, ne, ie) {
var re, se;
let oe = false, le = false, ue = -1, de = false;
if (null === ee.type) {
let se = ne, fe = "";
for (;se < _.length; ) {
const ne = _.charAt(se++);
if (!oe && "\\" !== ne) if (!le) {
if ("[" === ne) {
le = true;
ue = se;
de = false;
fe += ne;
continue;
}
if (ie.noext || !isExtglobType(ne) || "(" !== _.charAt(se)) fe += ne; else {
ee.push(fe);
fe = "";
const oe = new _AST(ne, ee);
se = __privateMethod(re = _AST, _parseAST, parseAST_fn).call(re, _, oe, se, ie);
ee.push(oe);
}
} else {
if (se === ue + 1) {
if ("^" === ne || "!" === ne) de = true;
} else if ("]" === ne && !(se === ue + 2 && de)) le = false;
fe += ne;
} else {
oe = !oe;
fe += ne;
}
}
ee.push(fe);
return se;
}
let fe = ne + 1, he = new _AST(null, ee);
const pe = [];
let ge = "";
for (;fe < _.length; ) {
const ne = _.charAt(fe++);
if (!oe && "\\" !== ne) if (!le) {
if ("[" === ne) {
le = true;
ue = fe;
de = false;
ge += ne;
continue;
}
if (!isExtglobType(ne) || "(" !== _.charAt(fe)) if ("|" !== ne) {
if (")" === ne) {
if ("" === ge && 0 === __privateGet(ee, _parts).length) __privateSet(ee, _emptyExt, true);
he.push(ge);
ge = "";
ee.push(...pe, he);
return fe;
}
ge += ne;
} else {
he.push(ge);
ge = "";
pe.push(he);
he = new _AST(null, ee);
} else {
he.push(ge);
ge = "";
const ee = new _AST(ne, he);
he.push(ee);
fe = __privateMethod(se = _AST, _parseAST, parseAST_fn).call(se, _, ee, fe, ie);
}
} else {
if (fe === ue + 1) {
if ("^" === ne || "!" === ne) de = true;
} else if ("]" === ne && !(fe === ue + 2 && de)) le = false;
ge += ne;
} else {
oe = !oe;
ge += ne;
}
}
ee.type = null;
__privateSet(ee, _hasMagic, void 0);
__privateSet(ee, _parts, [ _.substring(ne - 1) ]);
return fe;
};
_partsToRegExp = new WeakSet;
partsToRegExp_fn = function(_) {
return __privateGet(this, _parts).map((ee => {
if ("string" == typeof ee) throw new Error("string type in extglob ast??");
const [ne, ie, re, se] = ee.toRegExpSource(_);
__privateSet(this, _uflag, __privateGet(this, _uflag) || se);
return ne;
})).filter((_ => !(this.isStart() && this.isEnd() && !_))).join("|");
};
_parseGlob = new WeakSet;
parseGlob_fn = function(_, ee, ne = false) {
let ie = false, re = "", se = false;
for (let oe = 0; oe < _.length; oe++) {
const le = _.charAt(oe);
if (!ie) if ("\\" !== le) {
if ("[" === le) {
const [ne, ie, le, ue] = parseClass(_, oe);
if (le) {
re += ne;
se = se || ie;
oe += le - 1;
ee = ee || ue;
continue;
}
}
if ("*" !== le) if ("?" !== le) re += regExpEscape(le); else {
re += qmark;
ee = true;
} else {
if (ne && "*" === _) re += starNoEmpty; else re += star;
ee = true;
}
} else if (oe === _.length - 1) re += "\\\\"; else ie = true; else {
ie = false;
re += (reSpecials.has(le) ? "\\" : "") + le;
}
}
return [ re, unescape2(_), !!ee, se ];
};
__privateAdd(_AST, _parseAST);
__privateAdd(_AST, _parseGlob);
var AST = _AST, escape = (_, {windowsPathsNoEscape: ee = false} = {}) => ee ? _.replace(/[?*()[\]]/g, "[$&]") : _.replace(/[?*()[\]\\]/g, "\\$&"), minimatch = (_, ee, ne = {}) => {
assertValidPattern(ee);
if (!ne.nocomment && "#" === ee.charAt(0)) return false; else return new Minimatch(ee, ne).match(_);
}, starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/, starDotExtTest = _ => ee => !ee.startsWith(".") && ee.endsWith(_), starDotExtTestDot = _ => ee => ee.endsWith(_), starDotExtTestNocase = _ => {
_ = _.toLowerCase();
return ee => !ee.startsWith(".") && ee.toLowerCase().endsWith(_);
}, starDotExtTestNocaseDot = _ => {
_ = _.toLowerCase();
return ee => ee.toLowerCase().endsWith(_);
}, starDotStarRE = /^\*+\.\*+$/, starDotStarTest = _ => !_.startsWith(".") && _.includes("."), starDotStarTestDot = _ => "." !== _ && ".." !== _ && _.includes("."), dotStarRE = /^\.\*+$/, dotStarTest = _ => "." !== _ && ".." !== _ && _.startsWith("."), starRE = /^\*+$/, starTest = _ => 0 !== _.length && !_.startsWith("."), starTestDot = _ => 0 !== _.length && "." !== _ && ".." !== _, qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/, qmarksTestNocase = ([_, ee = ""]) => {
const ne = qmarksTestNoExt([ _ ]);
if (!ee) return ne;
ee = ee.toLowerCase();
return _ => ne(_) && _.toLowerCase().endsWith(ee);
}, qmarksTestNocaseDot = ([_, ee = ""]) => {
const ne = qmarksTestNoExtDot([ _ ]);
if (!ee) return ne;
ee = ee.toLowerCase();
return _ => ne(_) && _.toLowerCase().endsWith(ee);
}, qmarksTestDot = ([_, ee = ""]) => {
const ne = qmarksTestNoExtDot([ _ ]);
return !ee ? ne : _ => ne(_) && _.endsWith(ee);
}, qmarksTest = ([_, ee = ""]) => {
const ne = qmarksTestNoExt([ _ ]);
return !ee ? ne : _ => ne(_) && _.endsWith(ee);
}, qmarksTestNoExt = ([_]) => {
const ee = _.length;
return _ => _.length === ee && !_.startsWith(".");
}, qmarksTestNoExtDot = ([_]) => {
const ee = _.length;
return _ => _.length === ee && "." !== _ && ".." !== _;
}, defaultPlatform = "object" == typeof process && process ? "object" == typeof process.env && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix", path = {
win32: {
sep: "\\"
},
posix: {
sep: "/"
}
}, sep = "win32" === defaultPlatform ? path.win32.sep : path.posix.sep;
minimatch.sep = sep;
var GLOBSTAR = Symbol("globstar **");
minimatch.GLOBSTAR = GLOBSTAR;
var qmark2 = "[^/]", star2 = qmark2 + "*?", twoStarDot = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?", twoStarNoDot = "(?:(?!(?:\\/|^)\\.).)*?", filter = (_, ee = {}) => ne => minimatch(ne, _, ee);
minimatch.filter = filter;
var ext = (_, ee = {}) => Object.assign({}, _, ee), defaults = _ => {
if (!_ || "object" != typeof _ || !Object.keys(_).length) return minimatch;
const ee = minimatch;
return Object.assign(((ne, ie, re = {}) => ee(ne, ie, ext(_, re))), {
Minimatch: class Minimatch extends ee.Minimatch {
constructor(ee, ne = {}) {
super(ee, ext(_, ne));
}
static defaults(ne) {
return ee.defaults(ext(_, ne)).Minimatch;
}
},
AST: class AST extends ee.AST {
constructor(ee, ne, ie = {}) {
super(ee, ne, ext(_, ie));
}
static fromGlob(ne, ie = {}) {
return ee.AST.fromGlob(ne, ext(_, ie));
}
},
unescape: (ne, ie = {}) => ee.unescape(ne, ext(_, ie)),
escape: (ne, ie = {}) => ee.escape(ne, ext(_, ie)),
filter: (ne, ie = {}) => ee.filter(ne, ext(_, ie)),
defaults: ne => ee.defaults(ext(_, ne)),
makeRe: (ne, ie = {}) => ee.makeRe(ne, ext(_, ie)),
braceExpand: (ne, ie = {}) => ee.braceExpand(ne, ext(_, ie)),
match: (ne, ie, re = {}) => ee.match(ne, ie, ext(_, re)),
sep: ee.sep,
GLOBSTAR
});
};
minimatch.defaults = defaults;
var braceExpand = (_, ee = {}) => {
assertValidPattern(_);
if (ee.nobrace || !/\{(?:(?!\{).)*\}/.test(_)) return [ _ ]; else return (0, import_brace_expansion.default)(_);
};
minimatch.braceExpand = braceExpand;
var makeRe = (_, ee = {}) => new Minimatch(_, ee).makeRe();
minimatch.makeRe = makeRe;
var match = (_, ee, ne = {}) => {
const ie = new Minimatch(ee, ne);
_ = _.filter((_ => ie.match(_)));
if (ie.options.nonull && !_.length) _.push(ee);
return _;
};
minimatch.match = match;
var globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/, regExpEscape2 = _ => _.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), Minimatch = class {
constructor(_, ee = {}) {
__publicField(this, "options");
__publicField(this, "set");
__publicField(this, "pattern");
__publicField(this, "windowsPathsNoEscape");
__publicField(this, "nonegate");
__publicField(this, "negate");
__publicField(this, "comment");
__publicField(this, "empty");
__publicField(this, "preserveMultipleSlashes");
__publicField(this, "partial");
__publicField(this, "globSet");
__publicField(this, "globParts");
__publicField(this, "nocase");
__publicField(this, "isWindows");
__publicField(this, "platform");
__publicField(this, "windowsNoMagicRoot");
__publicField(this, "regexp");
assertValidPattern(_);
ee = ee || {};
this.options = ee;
this.pattern = _;
this.platform = ee.platform || defaultPlatform;
this.isWindows = "win32" === this.platform;
this.windowsPathsNoEscape = !!ee.windowsPathsNoEscape || false === ee.allowWindowsEscape;
if (this.windowsPathsNoEscape) this.pattern = this.pattern.replace(/\\/g, "/");
this.preserveMultipleSlashes = !!ee.preserveMultipleSlashes;
this.regexp = null;
this.negate = false;
this.nonegate = !!ee.nonegate;
this.comment = false;
this.empty = false;
this.partial = !!ee.partial;
this.nocase = !!this.options.nocase;
this.windowsNoMagicRoot = void 0 !== ee.windowsNoMagicRoot ? ee.windowsNoMagicRoot : !!(this.isWindows && this.nocase);
this.globSet = [];
this.globParts = [];
this.set = [];
this.make();
}
hasMagic() {
if (this.options.magicalBraces && this.set.length > 1) return true;
for (const _ of this.set) for (const ee of _) if ("string" != typeof ee) return true;
return false;
}
debug(..._) {}
make() {
const _ = this.pattern, ee = this.options;
if (!ee.nocomment && "#" === _.charAt(0)) {
this.comment = true;
return;
}
if (!_) {
this.empty = true;
return;
}
this.parseNegate();
this.globSet = [ ...new Set(this.braceExpand()) ];
if (ee.debug) this.debug = (..._) => console.error(..._);
this.debug(this.pattern, this.globSet);
const ne = this.globSet.map((_ => this.slashSplit(_)));
this.globParts = this.preprocess(ne);
this.debug(this.pattern, this.globParts);
let ie = this.globParts.map(((_, ee, ne) => {
if (this.isWindows && this.windowsNoMagicRoot) {
const ee = !("" !== _[0] || "" !== _[1] || "?" !== _[2] && globMagic.test(_[2]) || globMagic.test(_[3])), ne = /^[a-z]:/i.test(_[0]);
if (ee) return [ ..._.slice(0, 4), ..._.slice(4).map((_ => this.parse(_))) ]; else if (ne) return [ _[0], ..._.slice(1).map((_ => this.parse(_))) ];
}
return _.map((_ => this.parse(_)));
}));
this.debug(this.pattern, ie);
this.set = ie.filter((_ => -1 === _.indexOf(false)));
if (this.isWindows) for (let _ = 0; _ < this.set.length; _++) {
const ee = this.set[_];
if ("" === ee[0] && "" === ee[1] && "?" === this.globParts[_][2] && "string" == typeof ee[3] && /^[a-z]:$/i.test(ee[3])) ee[2] = "?";
}
this.debug(this.pattern, this.set);
}
preprocess(_) {
if (this.options.noglobstar) for (let ee = 0; ee < _.length; ee++) for (let ne = 0; ne < _[ee].length; ne++) if ("**" === _[ee][ne]) _[ee][ne] = "*";
const {optimizationLevel: ee = 1} = this.options;
if (ee >= 2) {
_ = this.firstPhasePreProcess(_);
_ = this.secondPhasePreProcess(_);
} else if (ee >= 1) _ = this.levelOneOptimize(_); else _ = this.adjascentGlobstarOptimize(_);
return _;
}
adjascentGlobstarOptimize(_) {
return _.map((_ => {
let ee = -1;
for (;-1 !== (ee = _.indexOf("**", ee + 1)); ) {
let ne = ee;
for (;"**" === _[ne + 1]; ) ne++;
if (ne !== ee) _.splice(ee, ne - ee);
}
return _;
}));
}
levelOneOptimize(_) {
return _.map((_ => 0 === (_ = _.reduce(((_, ee) => {
const ne = _[_.length - 1];
if ("**" === ee && "**" === ne) return _;
if (".." === ee) if (ne && ".." !== ne && "." !== ne && "**" !== ne) {
_.pop();
return _;
}
_.push(ee);
return _;
}), [])).length ? [ "" ] : _));
}
levelTwoFileOptimize(_) {
if (!Array.isArray(_)) _ = this.slashSplit(_);
let ee = false;
do {
ee = false;
if (!this.preserveMultipleSlashes) {
for (let ne = 1; ne < _.length - 1; ne++) {
const ie = _[ne];
if (1 !== ne || "" !== ie || "" !== _[0]) if ("." === ie || "" === ie) {
ee = true;
_.splice(ne, 1);
ne--;
}
}
if ("." === _[0] && 2 === _.length && ("." === _[1] || "" === _[1])) {
ee = true;
_.pop();
}
}
let ne = 0;
for (;-1 !== (ne = _.indexOf("..", ne + 1)); ) {
const ie = _[ne - 1];
if (ie && "." !== ie && ".." !== ie && "**" !== ie) {
ee = true;
_.splice(ne - 1, 2);
ne -= 2;
}
}
} while (ee);
return 0 === _.length ? [ "" ] : _;
}
firstPhasePreProcess(_) {
let ee = false;
do {
ee = false;
for (let ne of _) {
let ie = -1;
for (;-1 !== (ie = ne.indexOf("**", ie + 1)); ) {
let re = ie;
for (;"**" === ne[re + 1]; ) re++;
if (re > ie) ne.splice(ie + 1, re - ie);
let se = ne[ie + 1];
const oe = ne[ie + 2], le = ne[ie + 3];
if (".." !== se) continue;
if (!oe || "." === oe || ".." === oe || !le || "." === le || ".." === le) continue;
ee = true;
ne.splice(ie, 1);
const ue = ne.slice(0);
ue[ie] = "**";
_.push(ue);
ie--;
}
if (!this.preserveMultipleSlashes) {
for (let _ = 1; _ < ne.length - 1; _++) {
const ie = ne[_];
if (1 !== _ || "" !== ie || "" !== ne[0]) if ("." === ie || "" === ie) {
ee = true;
ne.splice(_, 1);
_--;
}
}
if ("." === ne[0] && 2 === ne.length && ("." === ne[1] || "" === ne[1])) {
ee = true;
ne.pop();
}
}
let re = 0;
for (;-1 !== (re = ne.indexOf("..", re + 1)); ) {
const _ = ne[re - 1];
if (_ && "." !== _ && ".." !== _ && "**" !== _) {
ee = true;
const _ = 1 === re && "**" === ne[re + 1] ? [ "." ] : [];
ne.splice(re - 1, 2, ..._);
if (0 === ne.length) ne.push("");
re -= 2;
}
}
}
} while (ee);
return _;
}
secondPhasePreProcess(_) {
for (let ee = 0; ee < _.length - 1; ee++) for (let ne = ee + 1; ne < _.length; ne++) {
const ie = this.partsMatch(_[ee], _[ne], !this.preserveMultipleSlashes);
if (ie) {
_[ee] = ie;
_[ne] = [];
}
}
return _.filter((_ => _.length));
}
partsMatch(_, ee, ne = false) {
let ie = 0, re = 0, se = [], oe = "";
for (;ie < _.length && re < ee.length; ) if (_[ie] === ee[re]) {
se.push("b" === oe ? ee[re] : _[ie]);
ie++;
re++;
} else if (ne && "**" === _[ie] && ee[re] === _[ie + 1]) {
se.push(_[ie]);
ie++;
} else if (ne && "**" === ee[re] && _[ie] === ee[re + 1]) {
se.push(ee[re]);
re++;
} else if ("*" === _[ie] && ee[re] && (this.options.dot || !ee[re].startsWith(".")) && "**" !== ee[re]) {
if ("b" === oe) return false;
oe = "a";
se.push(_[ie]);
ie++;
re++;
} else if ("*" === ee[re] && _[ie] && (this.options.dot || !_[ie].startsWith(".")) && "**" !== _[ie]) {
if ("a" === oe) return false;
oe = "b";
se.push(ee[re]);
ie++;
re++;
} else return false;
return _.length === ee.length && se;
}
parseNegate() {
if (this.nonegate) return;
const _ = this.pattern;
let ee = false, ne = 0;
for (let ie = 0; ie < _.length && "!" === _.charAt(ie); ie++) {
ee = !ee;
ne++;
}
if (ne) this.pattern = _.slice(ne);
this.negate = ee;
}
matchOne(_, ee, ne = false) {
const ie = this.options;
if (this.isWindows) {
const ne = "string" == typeof _[0] && /^[a-z]:$/i.test(_[0]), ie = !ne && "" === _[0] && "" === _[1] && "?" === _[2] && /^[a-z]:$/i.test(_[3]), re = "string" == typeof ee[0] && /^[a-z]:$/i.test(ee[0]), se = ie ? 3 : ne ? 0 : void 0, oe = !re && "" === ee[0] && "" === ee[1] && "?" === ee[2] && "string" == typeof ee[3] && /^[a-z]:$/i.test(ee[3]) ? 3 : re ? 0 : void 0;
if ("number" == typeof se && "number" == typeof oe) {
const [ne, ie] = [ _[se], ee[oe] ];
if (ne.toLowerCase() === ie.toLowerCase()) {
ee[oe] = ne;
if (oe > se) ee = ee.slice(oe); else if (se > oe) _ = _.slice(se);
}
}
}
const {optimizationLevel: re = 1} = this.options;
if (re >= 2) _ = this.levelTwoFileOptimize(_);
this.debug("matchOne", this, {
file: _,
pattern: ee
});
this.debug("matchOne", _.length, ee.length);
for (var se = 0, oe = 0, le = _.length, ue = ee.length; se < le && oe < ue; se++,
oe++) {
this.debug("matchOne loop");
var de = ee[oe], fe = _[se];
this.debug(ee, de, fe);
if (false === de) return false;
if (de === GLOBSTAR) {
this.debug("GLOBSTAR", [ ee, de, fe ]);
var he = se, pe = oe + 1;
if (pe === ue) {
this.debug("** at the end");
for (;se < le; se++) if ("." === _[se] || ".." === _[se] || !ie.dot && "." === _[se].charAt(0)) return false;
return true;
}
for (;he < le; ) {
var ge = _[he];
this.debug("\nglobstar while", _, he, ee, pe, ge);
if (this.matchOne(_.slice(he), ee.slice(pe), ne)) {
this.debug("globstar found match!", he, le, ge);
return true;
} else {
if ("." === ge || ".." === ge || !ie.dot && "." === ge.charAt(0)) {
this.debug("dot detected!", _, he, ee, pe);
break;
}
this.debug("globstar swallow a segment, and continue");
he++;
}
}
if (ne) {
this.debug("\n>>> no match, partial?", _, he, ee, pe);
if (he === le) return true;
}
return false;
}
let re;
if ("string" == typeof de) {
re = fe === de;
this.debug("string match", de, fe, re);
} else {
re = de.test(fe);
this.debug("pattern match", de, fe, re);
}
if (!re) return false;
}
if (se === le && oe === ue) return true; else if (se === le) return ne; else if (oe === ue) return se === le - 1 && "" === _[se]; else throw new Error("wtf?");
}
braceExpand() {
return braceExpand(this.pattern, this.options);
}
parse(_) {
assertValidPattern(_);
const ee = this.options;
if ("**" === _) return GLOBSTAR;
if ("" === _) return "";
let ne, ie = null;
if (ne = _.match(starRE)) ie = ee.dot ? starTestDot : starTest; else if (ne = _.match(starDotExtRE)) ie = (ee.nocase ? ee.dot ? starDotExtTestNocaseDot : starDotExtTestNocase : ee.dot ? starDotExtTestDot : starDotExtTest)(ne[1]); else if (ne = _.match(qmarksRE)) ie = (ee.nocase ? ee.dot ? qmarksTestNocaseDot : qmarksTestNocase : ee.dot ? qmarksTestDot : qmarksTest)(ne); else if (ne = _.match(starDotStarRE)) ie = ee.dot ? starDotStarTestDot : starDotStarTest; else if (ne = _.match(dotStarRE)) ie = dotStarTest;
const re = AST.fromGlob(_, this.options).toMMPattern();
return ie ? Object.assign(re, {
test: ie
}) : re;
}
makeRe() {
if (this.regexp || false === this.regexp) return this.regexp;
const _ = this.set;
if (!_.length) {
this.regexp = false;
return this.regexp;
}
const ee = this.options, ne = ee.noglobstar ? star2 : ee.dot ? twoStarDot : twoStarNoDot, ie = new Set(ee.nocase ? [ "i" ] : []);
let re = _.map((_ => {
const ee = _.map((_ => {
if (_ instanceof RegExp) for (const ee of _.flags.split("")) ie.add(ee);
return "string" == typeof _ ? regExpEscape2(_) : _ === GLOBSTAR ? GLOBSTAR : _._src;
}));
ee.forEach(((_, ie) => {
const re = ee[ie + 1], se = ee[ie - 1];
if (_ === GLOBSTAR && se !== GLOBSTAR) if (void 0 === se) if (void 0 !== re && re !== GLOBSTAR) ee[ie + 1] = "(?:\\/|" + ne + "\\/)?" + re; else ee[ie] = ne; else if (void 0 === re) ee[ie - 1] = se + "(?:\\/|" + ne + ")?"; else if (re !== GLOBSTAR) {
ee[ie - 1] = se + "(?:\\/|\\/" + ne + "\\/)" + re;
ee[ie + 1] = GLOBSTAR;
}
}));
return ee.filter((_ => _ !== GLOBSTAR)).join("/");
})).join("|");
const [se, oe] = _.length > 1 ? [ "(?:", ")" ] : [ "", "" ];
re = "^" + se + re + oe + "$";
if (this.negate) re = "^(?!" + re + ").+$";
try {
this.regexp = new RegExp(re, [ ...ie ].join(""));
} catch (_) {
this.regexp = false;
}
return this.regexp;
}
slashSplit(_) {
if (this.preserveMultipleSlashes) return _.split("/"); else if (this.isWindows && /^\/\/[^\/]+/.test(_)) return [ "", ..._.split(/\/+/) ]; else return _.split(/\/+/);
}
match(_, ee = this.partial) {
this.debug("match", _, this.pattern);
if (this.comment) return false;
if (this.empty) return "" === _;
if ("/" === _ && ee) return true;
const ne = this.options;
if (this.isWindows) _ = _.split("\\").join("/");
const ie = this.slashSplit(_);
this.debug(this.pattern, "split", ie);
const re = this.set;
this.debug(this.pattern, "set", re);
let se = ie[ie.length - 1];
if (!se) for (let _ = ie.length - 2; !se && _ >= 0; _--) se = ie[_];
for (let _ = 0; _ < re.length; _++) {
const oe = re[_];
let le = ie;
if (ne.matchBase && 1 === oe.length) le = [ se ];
if (this.matchOne(le, oe, ee)) if (ne.flipNegate) return true; else return !this.negate;
}
if (ne.flipNegate) return false; else return this.negate;
}
static defaults(_) {
return minimatch.defaults(_).Minimatch;
}
};
minimatch.AST = AST;
minimatch.Minimatch = Minimatch;
minimatch.escape = escape;
minimatch.unescape = unescape2;
var webcrypto, import_crypto = require("crypto");
if (globalThis.crypto) webcrypto = globalThis.crypto; else {
const _ = import_crypto.webcrypto;
webcrypto = _;
}
var revMap = {}, numMap = {};
for (let _ = 0; _ < 256; _++) {
revMap[`00${_.toString(16)}`.slice(-2)] = _;
numMap[_] = `00${_.toString(16)}`.slice(-2);
}
function* range(_, ee) {
for (let ne = _; ne <= ee; ne++) yield ne;
}
var table = {}, revTable = {};
[ ...range(192, 447) ].forEach(((_, ee) => {
table[ee] = _;
revTable[_] = ee;
}));
var BINARY_CHUNK_MAX = 31457280;
function hexStringToUint8Array(_) {
const ee = _.length / 2, ne = new Uint8Array(ee);
for (let ie = 0; ie < ee; ie++) ne[ie] = revMap[_[2 * ie] + _[2 * ie + 1]];
return ne;
}
function uint8ArrayToHexString(_) {
return [ ..._ ].map((_ => numMap[_])).join("");
}
var QUANTUM = 32768, writeString = _ => {
const ee = new Uint8Array(4 * _.length), ne = _.length;
let ie = 0, re = 0, se = 0;
for (;se < ne; ) {
re = _.charCodeAt(se++);
if (re < 128) ee[ie++] = re; else if (re < 2048) {
ee[ie++] = 192 | re >>> 6;
ee[ie++] = 128 | 63 & re;
} else if (re < 55296 || re > 57343) {
ee[ie++] = 224 | re >>> 12;
ee[ie++] = 128 | re >>> 6 & 63;
ee[ie++] = 128 | 63 & re;
} else {
re = 65536 + (re - 55296 << 10 | _.charCodeAt(se++) - 56320);
ee[ie++] = 240 | re >>> 18;
ee[ie++] = 128 | re >>> 12 & 63;
ee[ie++] = 128 | re >>> 6 & 63;
ee[ie++] = 128 | 63 & re;
}
}
return ee.slice(0, ie);
}, readString = _ => {
let ee = 0;
const ne = _.length;
let ie = "";
for (;ee < ne; ) {
const re = [], se = Math.min(ee + QUANTUM, ne);
for (;ee < se; ) {
const ne = _[ee++];
if (ne < 128) re.push(ne); else if (192 == (224 & ne)) re.push((31 & ne) << 6 | 63 & _[ee++]); else if (224 == (240 & ne)) re.push((15 & ne) << 12 | (63 & _[ee++]) << 6 | 63 & _[ee++]); else if (240 == (248 & ne)) {
let ie = (7 & ne) << 18 | (63 & _[ee++]) << 12 | (63 & _[ee++]) << 6 | 63 & _[ee++];
if (ie < 65536) re.push(ie); else {
ie -= 65536;
re.push(55296 + (ie >>> 10), 56320 + (1023 & ie));
}
}
}
ie += String.fromCharCode(...re);
}
return ie;
}, encodeChunkSize = 15e7;
function arrayBufferToBase64internalBrowser(_) {
return new Promise(((ee, ne) => {
const ie = new Blob([ _ ], {
type: "application/octet-binary"
}), re = new FileReader;
re.onload = function(ie) {
var re, se;
const oe = (null == (se = null == (re = ie.target) ? void 0 : re.result) ? void 0 : se.toString()) || "";
if (0 != _.byteLength && ("" == oe || "data:" == oe)) return ne(new TypeError("Could not parse the encoded string"));
const le = oe.substring(oe.indexOf(",") + 1);
ee(le);
};
re.readAsDataURL(ie);
}));
}
async function arrayBufferToBase64Single(_) {
const ee = _ instanceof Uint8Array ? _ : new Uint8Array(_);
if (ee.byteLength < QUANTUM) return btoa(String.fromCharCode.apply(null, [ ...ee ])); else return await arrayBufferToBase64internalBrowser(ee);
}
async function arrayBufferToBase64(_) {
const ee = _ instanceof Uint8Array ? _ : new Uint8Array(_);
if (ee.byteLength < QUANTUM) return [ btoa(String.fromCharCode.apply(null, [ ...ee ])) ];
const ne = ee.byteLength, ie = [];
let re = 0;
do {
const _ = re * encodeChunkSize, ne = new DataView(ee.buffer, _, Math.min(encodeChunkSize, ee.byteLength - _));
ie.push(await arrayBufferToBase64internalBrowser(ne));
re++;
} while (re * encodeChunkSize < ne);
return ie;
}
function base64ToArrayBuffer(_) {
if ("string" == typeof _) return base64ToArrayBufferInternalBrowser(_);
const ee = _.map((_ => base64ToArrayBufferInternalBrowser(_))), ne = ee.reduce(((_, ee) => _ + ee.byteLength), 0), ie = new Uint8Array(ne);
let re = 0;
ee.forEach((_ => {
ie.set(new Uint8Array(_), re);
re += _.byteLength;
}));
return ie.buffer;
}
function base64ToArrayBufferInternalBrowser(_) {
try {
const ee = globalThis.atob(_), ne = ee.length, ie = new Uint8Array(ne);
for (let _ = 0; _ < ne; _++) ie[_] = ee.charCodeAt(_);
return ie.buffer;
} catch (_) {
Logger("Base64 Decode error", LOG_LEVEL_VERBOSE);
Logger(_, LOG_LEVEL_VERBOSE);
return new ArrayBuffer(0);
}
}
var regexpBase64 = /^[A-Za-z0-9+/]+=*$/;
function tryConvertBase64ToArrayBuffer(_) {
try {
const ee = _.replace(/\r|\n/g, "");
if (!regexpBase64.test(ee)) return false;
const ne = globalThis.atob(ee);
if (globalThis.btoa(ne) !== ee) return false;
const ie = ne.length, re = new Uint8Array(ie);
for (let _ = 0; _ < ie; _++) re[_] = ne.charCodeAt(_);
return re.buffer;
} catch (_) {
return false;
}
}
function versionNumberString2Number(_) {
return _.split(".").reverse().map(((_, ee) => _ / 1 * 1e3 ** ee)).reduce(((_, ee) => _ + ee), 0);
}
var escapeStringToHTML = _ => {
if (!_) return ""; else return _.replace(/[<>&"'`]/g, (_ => ({
"<": "<",
">": ">",
"&": "&",
'"': """,
"'": "'",
"`": "`"
}[_])));
};
function decodeToArrayBuffer(_) {
if (1 == _.length) return _decodeToArrayBuffer(_[0]);
const ee = _.map((_ => _decodeToArrayBuffer(_))), ne = ee.reduce(((_, ee) => _ + ee.byteLength), 0), ie = new Uint8Array(ne);
let re = 0;
ee.forEach((_ => {
ie.set(new Uint8Array(_), re);
re += _.byteLength;
}));
return ie.buffer;
}
function _decodeToArrayBuffer(_) {
const ee = new Uint8Array(_.length), ne = _.length;
for (let ie = 0; ie < ne; ie++) {
const ne = _.charCodeAt(ie);
if (ne >= 38 && ne <= 126 && 58 != ne) ee[ie] = ne; else ee[ie] = revTable[ne];
}
return ee.buffer;
}
function decodeBinary(_) {
if (0 == _.length) return (new Uint8Array).buffer;
if ("string" == typeof _) {
if ("%" === _[0]) return _decodeToArrayBuffer(_.substring(1));
} else if ("%" === _[0][0]) {
const [ee, ...ne] = _;
return decodeToArrayBuffer([ ee.substring(1), ...ne ]);
}
return base64ToArrayBuffer(_);
}
function isValidFilenameInWidows(_) {
if (/[\u0000-\u001f]|[\\":?<>|*#]/g.test(_)) return false;
if (/(\\|\/)(COM\d|LPT\d|CON|PRN|AUX|NUL|CLOCK$)($|\.)/gi.test(_)) return false; else return true;
}
function isValidFilenameInDarwin(_) {
return !/[\u0000-\u001f]|[:]/g.test(_);
}
function isValidFilenameInLinux(_) {
return !/[\u0000-\u001f]|[:]/g.test(_);
}
function isValidFilenameInAndroid(_) {
return !/[\u0000-\u001f]|[\\":?<>|*#]/g.test(_);
}
function isFilePath(_) {
if (-1 === _.indexOf(":")) return true; else return false;
}
function stripAllPrefixes(_) {
if (isFilePath(_)) return _;
const [, ee] = expandFilePathPrefix(_);
return stripAllPrefixes(ee);
}
function addPrefix(_, ee) {
if (ee && _.startsWith(ee)) return _; else return `${null != ee ? ee : ""}${_}`;
}
function expandFilePathPrefix(_) {
let [ee, ne] = _.split(":", 2);
if (!ne) {
ne = ee;
ee = "";
} else ee += ":";
return [ ee, ne ];
}
function expandDocumentIDPrefix(_) {
let [ee, ne] = _.split(":", 2);
if (!ne) {
ne = ee;
ee = "";
} else ee += ":";
return [ ee, ne ];
}
var hashString = memorizeFuncWithLRUCache((async _ => {
const ee = writeString(_);
let ne = await webcrypto.subtle.digest("SHA-256", ee);
const ie = _.length;
for (let _ = 0; _ < ie; _++) ne = await webcrypto.subtle.digest("SHA-256", ee);
return uint8ArrayToHexString(new Uint8Array(ne));
}));
async function path2id_base(_, ee) {
if (_.startsWith(PREFIX_OBFUSCATED)) return _;
let ne = _;
if (ne.startsWith("_")) ne = "/" + ne;
if (!ee) return ne;
const [ie, re] = expandFilePathPrefix(ne);
if (re.startsWith(PREFIX_OBFUSCATED)) return ne;
const se = await hashString(ee), oe = await hashString(`${se}:${_}`);
return ie + PREFIX_OBFUSCATED + oe;
}
function id2path_base(_, ee) {
if (ee && (null == ee ? void 0 : ee.path)) return id2path_base(ee.path);
if (_.startsWith(PREFIX_OBFUSCATED)) throw new Error("Entry has been obfuscated!");
const [ne, ie] = expandDocumentIDPrefix(_);
if (ie.startsWith(PREFIX_OBFUSCATED)) throw new Error("Entry has been obfuscated!");
if (ie.startsWith("/")) return ie.substring(1); else return ne + ie;
}
function getPath(_) {
return id2path_base(_._id, _);
}
function stripPrefix(_) {
const [ee, ne] = _.split(":", 2);
if (!ne) return ee; else return ne;
}
function shouldBeIgnored(_) {
if (_ == FLAGMD_REDFLAG) return true;
if (_ == FLAGMD_REDFLAG2) return true;
if (_ == FLAGMD_REDFLAG2_HR) return true;
if (_ == FLAGMD_REDFLAG3) return true;
if (_ == FLAGMD_REDFLAG3_HR) return true;
if (_.startsWith(PREFIXMD_LOGFILE)) return true; else return false;
}
function isPlainText(_) {
if (_.endsWith(".md")) return true;
if (_.endsWith(".txt")) return true;
if (_.endsWith(".svg")) return true;
if (_.endsWith(".html")) return true;
if (_.endsWith(".csv")) return true;
if (_.endsWith(".css")) return true;
if (_.endsWith(".js")) return true;
if (_.endsWith(".xml")) return true;
if (_.endsWith(".canvas")) return true; else return false;
}
function shouldSplitAsPlainText(_) {
if (_.endsWith(".md")) return true;
if (_.endsWith(".txt")) return true;
if (_.endsWith(".canvas")) return true; else return false;
}
var matchOpts = {
platform: "linux",
dot: true,
flipNegate: true,
nocase: true
};
function isAccepted(_, ee) {
if (-1 !== _.indexOf("./") || -1 !== _.indexOf("../")) return false;
const ne = ee.map((_ => _.trim())).filter((_ => _.length > 0 && !_.startsWith("#")));
let ie;
for (const ee of ne) {
if (ee.endsWith("/")) if (minimatch(_, `${ee}**`, matchOpts)) return false;
const ne = ee.startsWith("!");
if (minimatch(_, ee, matchOpts) || !ee.endsWith("/") && minimatch(_, ee + "/**", matchOpts)) ie = ne;
}
return ie;
}
async function isAcceptedAll(_, ee, ne) {
const ie = unique(_.substring(0, _.lastIndexOf("/")).split("/").reduce(((_, ee) => [ ..._, _[_.length - 1] + "/" + ee ]), [ "" ]).map((_ => _.substring(1)))).reverse();
for (const re of ie) for (const ie of ee) {
const ee = re + "/" + ie, se = await ne(ee);
if (false === se) continue;
const oe = isAccepted(_.substring(re.length ? re.length + 1 : 0), se);
if (void 0 !== oe) return oe;
}
return true;
}
function makeUniqueString() {
const _ = [ ...Array(30) ].map((() => Math.floor(52 * Math.random()))).map((_ => "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"[_])).join("");
return `${Date.now()}-${_}`;
}
function Semaphore(_, ee) {
let ne = _, ie = 0, re = [];
function execProcess() {
re = re.filter((_ => "DONE" != _.state));
for (const _ of re) if ("NONE" == _.state) {
if (_.quantity + ie > ne) break;
_.state = "RUNNING";
ie += _.quantity;
if (null == _ ? void 0 : _.timer) clearTimeout(_.timer);
_.notify(true);
}
}
function release(_) {
const ne = re.find((ee => ee.key == _));
if (!ne) throw new Error("Missing locked semaphore!");
if ("RUNNING" == ne.state) ie -= ne.quantity;
ne.state = "DONE";
if (ee) ee(re.filter((_ => "DONE" != _.state)));
execProcess();
}
return {
setLimit(_) {
ne = _;
},
_acquire(_, ee, ie) {
const se = makeUniqueString();
if (ne < _) throw Error("Too big quantity");
let notify2 = _ => {};
const oe = new Promise((_ => {
notify2 = ee => {
if (ee) _((() => {
release(se);
})); else _(false);
};
})), le = {
key: se,
notify: notify2,
semaphoreStopper: oe,
quantity: _,
memo: ee,
state: "NONE"
};
if (ie) le.timer = setTimeout((() => {
release(se);
notify2(false);
}), ie);
re.push(le);
execProcess();
return oe;
},
acquire(_ = 1, ee) {
return this._acquire(_, null != ee ? ee : "", 0);
},
tryAcquire(_ = 1, ee, ne) {
return this._acquire(_, null != ne ? ne : "", ee);
},
peekQueues: () => re
};
}
var semiStaticFieldBuffer, KeyBuffs = new Map, decKeyBuffs = new Map, KEY_RECYCLE_COUNT = 100, nonceBuffer = new Uint32Array(1);
async function getKeyForEncrypt(_, ee) {
const ne = `${_}-${ee}`, ie = KeyBuffs.get(ne);
if (ie) {
ie.count--;
if (ie.count > 0) return [ ie.key, ie.salt ];
ie.count--;
}
const re = 15 - _.length, se = ee ? 1e3 * (re > 0 ? re : 0) + 121 - re : 1e5, oe = (new TextEncoder).encode(_), le = await webcrypto.subtle.digest({
name: "SHA-256"
}, oe), ue = await webcrypto.subtle.importKey("raw", le, {
name: "PBKDF2"
}, false, [ "deriveKey" ]), de = webcrypto.getRandomValues(new Uint8Array(16)), fe = await webcrypto.subtle.deriveKey({
name: "PBKDF2",
salt: de,
iterations: se,
hash: "SHA-256"
}, ue, {
name: "AES-GCM",
length: 256
}, false, [ "encrypt" ]);
KeyBuffs.set(ne, {
key: fe,
salt: de,
count: KEY_RECYCLE_COUNT
});
return [ fe, de ];
}
var keyGCCount = 5 * KEY_RECYCLE_COUNT, decKeyIdx = 0, decKeyMin = 0;
async function getKeyForDecryption(_, ee, ne) {
if (--keyGCCount < 0) {
keyGCCount = KEY_RECYCLE_COUNT;
const _ = (decKeyIdx - decKeyMin) / 2;
for (const [ee, ne] of decKeyBuffs) {
if (ne.count < _) decKeyBuffs.delete(ee);
decKeyMin = decKeyIdx;
}
}
decKeyIdx++;
const ie = _ + uint8ArrayToHexString(ee) + ne, re = decKeyBuffs.get(ie);
if (re) {
re.count = decKeyIdx;
return [ re.key, re.salt ];
}
const se = 15 - _.length, oe = ne ? 1e3 * (se > 0 ? se : 0) + 121 - se : 1e5, le = (new TextEncoder).encode(_), ue = await webcrypto.subtle.digest({
name: "SHA-256"
}, le), de = await webcrypto.subtle.importKey("raw", ue, {
name: "PBKDF2"
}, false, [ "deriveKey" ]), fe = await webcrypto.subtle.deriveKey({
name: "PBKDF2",
salt: ee,
iterations: oe,
hash: "SHA-256"
}, de, {
name: "AES-GCM",
length: 256
}, false, [ "decrypt" ]);
decKeyBuffs.set(ie, {
key: fe,
salt: ee,
count: 0
});
return [ fe, ee ];
}
function getSemiStaticField(_) {
if (null != semiStaticFieldBuffer && !_) return semiStaticFieldBuffer; else return semiStaticFieldBuffer = webcrypto.getRandomValues(new Uint8Array(12));
}
function getNonce() {
nonceBuffer[0]++;
if (nonceBuffer[0] > 1e4) getSemiStaticField(true);
return nonceBuffer;
}
async function encrypt(_, ee, ne) {
const [ie, re] = await getKeyForEncrypt(ee, ne), se = getSemiStaticField(), oe = getNonce(), le = new Uint8Array([ ...se, ...new Uint8Array(oe.buffer) ]), ue = writeString(_), de = await webcrypto.subtle.encrypt({
name: "AES-GCM",
iv: le
}, ie, ue), fe = "" + await arrayBufferToBase64Single(new Uint8Array(de));
return `%${uint8ArrayToHexString(le)}${uint8ArrayToHexString(re)}${fe}`;
}
async function getKeyForObfuscatePath(_, ee, ne) {
const ie = 15 - _.length, re = ne ? 1e3 * (ie > 0 ? ie : 0) + 121 - ie : 1e5, se = (new TextEncoder).encode(_), oe = await webcrypto.subtle.digest({
name: "SHA-256"
}, se), le = new Uint8Array(await webcrypto.subtle.digest({
name: "SHA-256"
}, new Uint8Array([ ...ee, ...se ]))), ue = le.slice(0, 16), de = le.slice(16, 32), fe = await webcrypto.subtle.importKey("raw", oe, {
name: "PBKDF2"
}, false, [ "deriveKey" ]);
return [ await webcrypto.subtle.deriveKey({
name: "PBKDF2",
salt: ue,
iterations: re,
hash: "SHA-256"
}, fe, {
name: "AES-GCM",
length: 256
}, false, [ "encrypt" ]), ue, de ];
}
async function obfuscatePath(_, ee, ne) {
const ie = writeString(_), [re, se, oe] = await getKeyForObfuscatePath(ee, ie, ne), le = await webcrypto.subtle.encrypt({
name: "AES-GCM",
iv: oe
}, re, ie), ue = await arrayBufferToBase64Single(new Uint8Array(le));
return `%${uint8ArrayToHexString(oe)}${uint8ArrayToHexString(se)}${ue}`;
}
async function decryptV2(_, ee, ne) {
try {
const ie = _.substring(1, 33), re = _.substring(33, 65), se = _.substring(65), [oe] = await getKeyForDecryption(ee, hexStringToUint8Array(re), ne), le = hexStringToUint8Array(ie), ue = decodeBinary(se), de = await webcrypto.subtle.decrypt({
name: "AES-GCM",
iv: le
}, oe, ue);
return readString(new Uint8Array(de));
} catch (_) {
Logger("Couldn't decode! You should wrong the passphrases (V2)", LOG_LEVEL_VERBOSE);
Logger(_, LOG_LEVEL_VERBOSE);
throw _;
}
}
async function decrypt(_, ee, ne) {
try {
if ("%" == _[0]) return decryptV2(_, ee, ne);
if (!_.startsWith("[") || !_.endsWith("]")) throw new Error("Encrypted data corrupted!");
const ie = _.substring(1, _.length - 1).split(",").map((_ => '"' == _[0] ? _.substring(1, _.length - 1) : _)), [re, se, oe] = ie, [le] = await getKeyForDecryption(ee, hexStringToUint8Array(oe), ne), ue = hexStringToUint8Array(se), de = atob(re), fe = de.length, he = new Uint8Array(fe);
for (let _ = fe; _ >= 0; --_) he[_] = de.charCodeAt(_);
const pe = await webcrypto.subtle.decrypt({
name: "AES-GCM",
iv: ue
}, le, he), ge = readString(new Uint8Array(pe));
return JSON.parse(ge);
} catch (_) {
Logger("Couldn't decode! You should wrong the passphrases", LOG_LEVEL_VERBOSE);
Logger(_, LOG_LEVEL_VERBOSE);
throw _;
}
}
async function tryDecrypt(_, ee, ne) {
if (!ee) return false;
try {
return await decrypt(_, ee, ne);
} catch (_) {
return false;
}
}
async function testCrypt() {
const _ = "✨supercalifragilisticexpialidocious✨⛰️", ee = await encrypt(_, "passwordTest", false);
if (_ != await decrypt(ee, "passwordTest", false)) {
Logger("WARNING! Your device would not support encryption.", LOG_LEVEL_VERBOSE);
return false;
} else {
Logger("CRYPT LOGIC OK", LOG_LEVEL_VERBOSE);
const ee = (new TextEncoder).encode(_), ne = await encryptBinary(ee, "passwordTest", false), ie = await decryptBinary(ne, "passwordTest", false);
if (ee.join("-") !== ie.join("-")) {
Logger("WARNING! Your device would not support encryption (Binary).", LOG_LEVEL_VERBOSE);
return false;
} else Logger("CRYPT LOGIC OK (Binary)", LOG_LEVEL_VERBOSE);
return true;
}
}
async function encryptBinary(_, ee, ne) {
const [ie, re] = await getKeyForEncrypt(ee, ne), se = getSemiStaticField(), oe = getNonce(), le = new Uint8Array([ ...se, ...new Uint8Array(oe.buffer) ]), ue = _, de = new Uint8Array(await webcrypto.subtle.encrypt({
name: "AES-GCM",
iv: le
}, ie, ue)), fe = new Uint8Array(de.byteLength + le.byteLength + re.byteLength);
fe.set(le, 0);
fe.set(re, le.byteLength);
fe.set(de, le.byteLength + re.byteLength);
return fe;
}
async function decryptBinary(_, ee, ne) {
try {
const ie = _.slice(0, 16), re = _.slice(16, 32), se = _.slice(32), [oe] = await getKeyForDecryption(ee, re, ne), le = await webcrypto.subtle.decrypt({
name: "AES-GCM",
iv: ie
}, oe, se);
return new Uint8Array(le);
} catch (_) {
Logger("Couldn't decode! You should wrong the passphrases (V2 Bin)", LOG_LEVEL_VERBOSE);
Logger(_, LOG_LEVEL_VERBOSE);
throw _;
}
}
var queueTails = new Map;
async function performTask(_) {
if (!_.isRunning) try {
_.isRunning = true;
const ee = await _.task();
_.resolver(ee);
} catch (ee) {
_.rejector(ee);
} finally {
const ee = _.next;
_.isFinished = true;
if (ee) fireAndForget((() => performTask(ee))); else queueTails.delete(_.key);
}
}
function _enqueue(_, ee, {swapIfExist: ne, shareResult: ie} = {}) {
const re = promiseWithResolver(), se = {
task: ee,
resolver: re.resolve,
rejector: re.reject,
key: _
}, oe = queueTails.get(_);
if (void 0 === oe) queueTails.set(_, se); else {
const ee = oe;
queueTails.set(_, se);
ee.next = se;
if (ne) ee.rejector(new Error("Cancelled"));
}
if (!oe || oe.isFinished) fireAndForget((() => performTask(se)));
return re.promise;
}
function serialized(_, ee) {
return _enqueue(_, ee);
}
function shareRunningResult(_, ee) {
const ne = queueTails.get(_);
if (!ne) return _enqueue(_, ee);
let ie = ne.resolver, re = ne.rejector;
const se = promiseWithResolver();
ne.resolver = _ => {
null == ie || ie(_);
se.resolve(_);
};
ne.rejector = _ => {
null == re || re(_);
se.reject(_);
};
se.promise.finally((() => {
ie = void 0;
re = void 0;
}));
return se.promise;
}
function skipIfDuplicated(_, ee) {
if (void 0 !== queueTails.get(_)) return Promise.resolve(null); else return _enqueue(_, ee);
}
function isLockAcquired(_) {
return void 0 !== queueTails.get(_);
}
var Notifier = class {
constructor() {
this.p = promiseWithResolver();
this.isUsed = false;
}
notify() {
if (this.isUsed) {
this.isUsed = false;
this.p.promise.finally(noop);
this.p.resolve();
this.p = promiseWithResolver();
}
}
get nextNotify() {
this.isUsed = true;
return this.p.promise;
}
}, processNo = 0, allRunningProcessors = new Set([]), QueueProcessor = class {
constructor(_, ee, ne, ie) {
this._queue = [];
this._enqueueProcessor = (_, ee) => (_.push(ee), _);
this._isSuspended = true;
this._nextProcessNeedsImmediate = false;
this._waitId = "";
this._root = void 0;
this._instance = processNo++;
this._keepResultUntilDownstreamConnected = false;
this._keptResult = [];
this._runOnUpdateBatch = () => {};
this.concurrentLimit = 1;
this.batchSize = 1;
this.yieldThreshold = 1;
this.delay = 0;
this.interval = 0;
this.processingEntities = 0;
this.waitingEntries = 0;
this._notifier = new Notifier;
this._processingBatches = new Set;
this.addProcessingBatch = _ => {
const ee = this._processingBatches.add(_);
this._updateBatchProcessStatus();
return ee;
};
this.deleteProcessingBatch = _ => {
const ee = this._processingBatches.delete(_);
this._updateBatchProcessStatus();
return ee;
};
this._processing = false;
var re, se, oe, le, ue, de, fe;
this._root = this;
this._processor = _;
this.batchSize = null != (re = null == ee ? void 0 : ee.batchSize) ? re : 1;
this.yieldThreshold = null != (oe = null != (se = null == ee ? void 0 : ee.yieldThreshold) ? se : null == ee ? void 0 : ee.batchSize) ? oe : 0;
this.concurrentLimit = null != (le = null == ee ? void 0 : ee.concurrentLimit) ? le : 1;
this.delay = null != (ue = null == ee ? void 0 : ee.delay) ? ue : 0;
this.maintainDelay = null != (de = null == ee ? void 0 : ee.maintainDelay) ? de : false;
this.interval = null != (fe = null == ee ? void 0 : ee.interval) ? fe : 0;
if (null == ee ? void 0 : ee.keepResultUntilDownstreamConnected) this._keepResultUntilDownstreamConnected = ee.keepResultUntilDownstreamConnected;
if (null == ee ? void 0 : ee.remainingReactiveSource) this._remainingReactiveSource = null == ee ? void 0 : ee.remainingReactiveSource;
if (null == ee ? void 0 : ee.totalRemainingReactiveSource) this._totalRemainingReactiveSource = null == ee ? void 0 : ee.totalRemainingReactiveSource;
if (null == ee ? void 0 : ee.processingEntitiesReactiveSource) this._processingEntitiesReactiveSource = null == ee ? void 0 : ee.processingEntitiesReactiveSource;
if (void 0 !== (null == ee ? void 0 : ee.suspended)) this._isSuspended = null == ee ? void 0 : ee.suspended;
if (ie) this.replaceEnqueueProcessor(ie);
if (void 0 !== (null == ee ? void 0 : ee.pipeTo)) this.pipeTo(ee.pipeTo);
if (ne) this.enqueueAll(ne);
allRunningProcessors.add(this);
this._run();
}
get nowProcessing() {
return this.processingEntities;
}
get totalNowProcessing() {
var _;
return this.nowProcessing + ((null == (_ = this._pipeTo) ? void 0 : _.totalNowProcessing) || 0);
}
get remaining() {
return this._queue.length + this.processingEntities + this.waitingEntries;
}
get totalRemaining() {
var _;
return this.remaining + ((null == (_ = this._pipeTo) ? void 0 : _.totalRemaining) || 0);
}
updateStatus(_) {
_();
this._updateReactiveSource();
}
suspend() {
this._isSuspended = true;
this._notifier.notify();
return this;
}
resume() {
this._isSuspended = false;
this._notifier.notify();
this.requestNextFlush();
this._run();
return this;
}
resumePipeLine() {
var _;
null == (_ = this._pipeTo) || _.resumePipeLine();
this.resume();
return this;
}
startPipeline() {
this.root.resumePipeLine();
return this;
}
get root() {
if (void 0 === this._root) return this; else return this._root;
}
replaceEnqueueProcessor(_) {
this._enqueueProcessor = _;
return this;
}
modifyQueue(_) {
this._queue = _(this._queue);
this._notifier.notify();
}
clearQueue() {
this._queue = [];
this._notifier.notify();
}
onUpdateProgress(_) {
this._runOnUpdateBatch = _;
return this;
}
pipeTo(_) {
this._pipeTo = _;
this._pipeTo._root = this.root;
if (this._keptResult.length > 0) {
const _ = [ ...this._keptResult ];
this._keptResult = [];
this._pipeTo.enqueueAll(_);
}
return _;
}
isIdle() {
return this._isIdle() && (!this._pipeTo ? true : this._pipeTo.isIdle());
}
_isIdle() {
return 0 == this.totalRemaining;
}
async _idleDetector() {
if (this._isSuspended) return Promise.resolve();
if (this._isIdle()) return Promise.resolve();
do {
await Promise.race([ delay(3e3), this._notifier.nextNotify ]);
} while (!this._isIdle());
return Promise.resolve();
}
idleDetectors() {
const _ = this._idleDetector();
if (this._pipeTo) return [ _, ...this._pipeTo.idleDetectors() ]; else return [ _ ];
}
get isSuspended() {
var _;
return this._isSuspended || (null == (_ = this._pipeTo) ? void 0 : _.isSuspended) || false;
}
_updateReactiveSource() {
this.root.updateReactiveSource();
}
updateReactiveSource() {
if (this._pipeTo) this._pipeTo.updateReactiveSource();
if (this._remainingReactiveSource) this._remainingReactiveSource.value = this.remaining;
if (this._totalRemainingReactiveSource) this._totalRemainingReactiveSource.value = this.totalRemaining;
if (this._processingEntitiesReactiveSource) this._processingEntitiesReactiveSource.value = this.nowProcessing;
}
_updateBatchProcessStatus() {
this._updateReactiveSource();
this._runOnUpdateBatch();
}
_collectBatch() {
return this._queue.splice(0, this.batchSize);
}
_canCollectBatch() {
return 0 !== this._queue.length;
}
enqueue(_) {
this._queue = this._enqueueProcessor(this._queue, _);
this._updateBatchProcessStatus();
this._notifier.notify();
return this;
}
enqueueAll(_) {
let ee = this._queue;
for (const ne of _) ee = this._enqueueProcessor(ee, ne);
this._queue = ee;
this._updateBatchProcessStatus();
this._notifier.notify();
return this;
}
requestNextFlush() {
if (this._canCollectBatch()) {
this._nextProcessNeedsImmediate = true;
this._notifier.notify();
}
}
flush() {
if (!this._isSuspended) {
this.requestNextFlush();
return this.waitForAllDownstream();
}
}
async waitForAllDownstream(_) {
const ee = [];
if (_) ee.push(delay(_, RESULT_TIMED_OUT));
do {
const _ = this.idleDetectors(), ne = [ ...ee, Promise.all(_) ];
if (await Promise.race(ne) === RESULT_TIMED_OUT) return false;
} while (!this.isIdle());
return true;
}
waitForAllProcessed(_) {
this.root.startPipeline();
return this.root.waitForAllDownstream(_);
}
async waitForAllDoneAndTerminate(_) {
this.root.startPipeline();
const ee = await this.root.waitForAllDownstream(_);
this.terminateAll();
return ee;
}
async _runProcessor(_) {
const ee = await this._processor(_);
if (ee) if (this._pipeTo) this._pipeTo.enqueueAll(ee); else if (this._keepResultUntilDownstreamConnected) this._keptResult.push(...ee);
}
async* pump() {
let _, ee = true;
do {
if (this._canCollectBatch()) {
if (ee) await this.delayUntilRequested(this.delay);
_ = this._collectBatch();
if (0 != _.length) {
yield _;
if (this._canCollectBatch()) ee = false;
}
} else {
ee = true;
await Promise.race([ this._notifier.nextNotify, delay(3e3) ]);
}
} while (this._canCollectBatch() && !this._isSuspended);
}
async delayUntilRequested(_) {
if (this._nextProcessNeedsImmediate) {
this._nextProcessNeedsImmediate = false;
return;
}
const ee = delay(_, RESULT_TIMED_OUT);
let ne;
do {
ne = await Promise.race([ this._notifier.nextNotify, ee ]);
} while (ne !== RESULT_TIMED_OUT && false === this._nextProcessNeedsImmediate && this.yieldThreshold >= this._queue.length);
this._nextProcessNeedsImmediate = false;
}
async _process() {
if (this._processing && this._isSuspended) return;
let _ = 0;
try {
this._processing = true;
do {
const ee = this.pump();
for await (const ne of ee) {
const ee = ne.length;
this.updateStatus((() => {
this.waitingEntries += ee;
}));
for (;this._processingBatches.size >= this.concurrentLimit; ) await this._notifier.nextNotify;
const ie = Date.now() + Math.random(), batchTask = async () => {
this.updateStatus((() => {
this.processingEntities += ee;
this.waitingEntries -= ee;
}));
this.addProcessingBatch(ie);
try {
if (this.interval && _) {
const ee = Date.now() - _;
if (ee < this.interval) {
const _ = this.interval - ee;
await delay(_);
}
}
_ = Date.now();
await this._runProcessor(ne);
} catch (_) {
Logger("Processor error!");
Logger(_, LOG_LEVEL_VERBOSE);
} finally {
this.deleteProcessingBatch(ie);
this.updateStatus((() => {
this.processingEntities -= ee;
}));
this._notifier.notify();
}
};
this._notifier.notify();
fireAndForget((() => batchTask()));
}
await this._notifier.nextNotify;
} while (!this._isSuspended);
} finally {
this._processing = false;
}
}
_run() {
if (!this._isSuspended) if (!this._processing) fireAndForget((() => this._process()));
}
terminateAll() {
this.root.terminate();
}
terminate() {
if (this._pipeTo) {
this._pipeTo.terminate();
this._pipeTo = void 0;
}
this._isSuspended = true;
this._enqueueProcessor = () => [];
this._processor = () => Promise.resolve([]);
this.clearQueue();
this._notifier.notify();
this._notifier.notify();
this._notifier.notify();
this._queue.length = 0;
allRunningProcessors.delete(this);
}
};
function stopAllRunningProcessors() {
const _ = [ ...allRunningProcessors ];
for (const ee of _) ee.terminate();
}
var ch2 = {}, wk = function(_, ee, ne, ie, re) {
var se = new Worker(ch2[ee] || (ch2[ee] = URL.createObjectURL(new Blob([ _ + ';addEventListener("error",function(e){e=e.error;postMessage({$e$:[e.message,e.code,e.stack]})})' ], {
type: "text/javascript"
}))));
se.onmessage = function(_) {
var ee = _.data, ne = ee.$e$;
if (ne) {
var ie = new Error(ne[0]);
ie["code"] = ne[1];
ie.stack = ne[2];
re(ie, null);
} else re(null, ee);
};
se.postMessage(ne, ie);
return se;
}, u8 = Uint8Array, u16 = Uint16Array, i32 = Int32Array, fleb = new u8([ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 0, 0, 0 ]), fdeb = new u8([ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 0, 0 ]), clim = new u8([ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]), freb = function(_, ee) {
for (var ne = new u16(31), ie = 0; ie < 31; ++ie) ne[ie] = ee += 1 << _[ie - 1];
var re = new i32(ne[30]);
for (ie = 1; ie < 30; ++ie) for (var se = ne[ie]; se < ne[ie + 1]; ++se) re[se] = se - ne[ie] << 5 | ie;
return {
b: ne,
r: re
};
}, _a = freb(fleb, 2), fl = _a.b, revfl = _a.r;
fl[28] = 258, revfl[258] = 28;
var x2, _b = freb(fdeb, 0), fd = _b.b, revfd = _b.r, rev = new u16(32768);
for (i2 = 0; i2 < 32768; ++i2) {
x2 = (61680 & (x2 = (52428 & (x2 = (43690 & i2) >> 1 | (21845 & i2) << 1)) >> 2 | (13107 & x2) << 2)) >> 4 | (3855 & x2) << 4;
rev[i2] = ((65280 & x2) >> 8 | (255 & x2) << 8) >> 1;
}
var hMap = function(_, ee, ne) {
for (var ie = _.length, re = 0, se = new u16(ee); re < ie; ++re) if (_[re]) ++se[_[re] - 1];
var oe, le = new u16(ee);
for (re = 1; re < ee; ++re) le[re] = le[re - 1] + se[re - 1] << 1;
if (ne) {
oe = new u16(1 << ee);
var ue = 15 - ee;
for (re = 0; re < ie; ++re) if (_[re]) for (var de = re << 4 | _[re], fe = ee - _[re], he = le[_[re] - 1]++ << fe, pe = he | (1 << fe) - 1; he <= pe; ++he) oe[rev[he] >> ue] = de;
} else {
oe = new u16(ie);
for (re = 0; re < ie; ++re) if (_[re]) oe[re] = rev[le[_[re] - 1]++] >> 15 - _[re];
}
return oe;
}, flt = new u8(288);
for (i2 = 0; i2 < 144; ++i2) flt[i2] = 8;
for (i2 = 144; i2 < 256; ++i2) flt[i2] = 9;
for (i2 = 256; i2 < 280; ++i2) flt[i2] = 7;
for (i2 = 280; i2 < 288; ++i2) flt[i2] = 8;
var fdt = new u8(32);
for (i2 = 0; i2 < 32; ++i2) fdt[i2] = 5;
var flm = hMap(flt, 9, 0), flrm = hMap(flt, 9, 1), fdm = hMap(fdt, 5, 0), fdrm = hMap(fdt, 5, 1), max = function(_) {
for (var ee = _[0], ne = 1; ne < _.length; ++ne) if (_[ne] > ee) ee = _[ne];
return ee;
}, bits = function(_, ee, ne) {
var ie = ee / 8 | 0;
return (_[ie] | _[ie + 1] << 8) >> (7 & ee) & ne;
}, bits16 = function(_, ee) {
var ne = ee / 8 | 0;
return (_[ne] | _[ne + 1] << 8 | _[ne + 2] << 16) >> (7 & ee);
}, shft = function(_) {
return (_ + 7) / 8 | 0;
}, slc = function(_, ee, ne) {
if (null == ee || ee < 0) ee = 0;
if (null == ne || ne > _.length) ne = _.length;
return new u8(_.subarray(ee, ne));
}, ec = [ "unexpected EOF", "invalid block type", "invalid length/literal", "invalid distance", "stream finished", "no stream handler", , "no callback", "invalid UTF-8 data", "extra field too long", "date not in range 1980-2099", "filename too long", "stream finishing", "invalid zip data" ], err = function(_, ee, ne) {
var ie = new Error(ee || ec[_]);
ie.code = _;
if (Error.captureStackTrace) Error.captureStackTrace(ie, err);
if (!ne) throw ie;
return ie;
}, inflt = function(_, ee, ne, ie) {
var re = _.length, se = ie ? ie.length : 0;
if (!re || ee.f && !ee.l) return ne || new u8(0);
var oe = !ne, le = oe || 2 != ee.i, ue = ee.i;
if (oe) ne = new u8(3 * re);
var cbuf = function(_) {
var ee = ne.length;
if (_ > ee) {
var ie = new u8(Math.max(2 * ee, _));
ie.set(ne);
ne = ie;
}
}, de = ee.f || 0, fe = ee.p || 0, he = ee.b || 0, pe = ee.l, ge = ee.d, me = ee.m, ye = ee.n, ve = 8 * re;
do {
if (!pe) {
de = bits(_, fe, 1);
var Se = bits(_, fe + 1, 3);
fe += 3;
if (!Se) {
var Ee = _[(Ie = shft(fe) + 4) - 4] | _[Ie - 3] << 8, Ce = Ie + Ee;
if (Ce > re) {
if (ue) err(0);
break;
}
if (le) cbuf(he + Ee);
ne.set(_.subarray(Ie, Ce), he);
ee.b = he += Ee, ee.p = fe = 8 * Ce, ee.f = de;
continue;
} else if (1 == Se) pe = flrm, ge = fdrm, me = 9, ye = 5; else if (2 == Se) {
var we = bits(_, fe, 31) + 257, Oe = bits(_, fe + 10, 15) + 4, ke = we + bits(_, fe + 5, 31) + 1;
fe += 14;
for (var xe = new u8(ke), Ae = new u8(19), Le = 0; Le < Oe; ++Le) Ae[clim[Le]] = bits(_, fe + 3 * Le, 7);
fe += 3 * Oe;
var Re = max(Ae), Te = (1 << Re) - 1, Pe = hMap(Ae, Re, 1);
for (Le = 0; Le < ke; ) {
var Ie, De = Pe[bits(_, fe, Te)];
fe += 15 & De;
if ((Ie = De >> 4) < 16) xe[Le++] = Ie; else {
var Be = 0, Ne = 0;
if (16 == Ie) Ne = 3 + bits(_, fe, 3), fe += 2, Be = xe[Le - 1]; else if (17 == Ie) Ne = 3 + bits(_, fe, 7),
fe += 3; else if (18 == Ie) Ne = 11 + bits(_, fe, 127), fe += 7;
for (;Ne--; ) xe[Le++] = Be;
}
}
var Me = xe.subarray(0, we), Fe = xe.subarray(we);
me = max(Me);
ye = max(Fe);
pe = hMap(Me, me, 1);
ge = hMap(Fe, ye, 1);
} else err(1);
if (fe > ve) {
if (ue) err(0);
break;
}
}
if (le) cbuf(he + 131072);
for (var je = (1 << me) - 1, $e = (1 << ye) - 1, Ge = fe; ;Ge = fe) {
var Ve = (Be = pe[bits16(_, fe) & je]) >> 4;
if ((fe += 15 & Be) > ve) {
if (ue) err(0);
break;
}
if (!Be) err(2);
if (Ve < 256) ne[he++] = Ve; else if (256 == Ve) {
Ge = fe, pe = null;
break;
} else {
var Ue = Ve - 254;
if (Ve > 264) {
var ze = fleb[Le = Ve - 257];
Ue = bits(_, fe, (1 << ze) - 1) + fl[Le];
fe += ze;
}
var qe = ge[bits16(_, fe) & $e], He = qe >> 4;
if (!qe) err(3);
fe += 15 & qe;
Fe = fd[He];
if (He > 3) {
ze = fdeb[He];
Fe += bits16(_, fe) & (1 << ze) - 1, fe += ze;
}
if (fe > ve) {
if (ue) err(0);
break;
}
if (le) cbuf(he + 131072);
var Ke = he + Ue;
if (he < Fe) {
var We = se - Fe, Xe = Math.min(Fe, Ke);
if (We + he < 0) err(3);
for (;he < Xe; ++he) ne[he] = ie[We + he];
}
for (;he < Ke; ++he) ne[he] = ne[he - Fe];
}
}
ee.l = pe, ee.p = Ge, ee.b = he, ee.f = de;
if (pe) de = 1, ee.m = me, ee.d = ge, ee.n = ye;
} while (!de);
return he != ne.length && oe ? slc(ne, 0, he) : ne.subarray(0, he);
}, wbits = function(_, ee, ne) {
ne <<= 7 & ee;
var ie = ee / 8 | 0;
_[ie] |= ne;
_[ie + 1] |= ne >> 8;
}, wbits16 = function(_, ee, ne) {
ne <<= 7 & ee;
var ie = ee / 8 | 0;
_[ie] |= ne;
_[ie + 1] |= ne >> 8;
_[ie + 2] |= ne >> 16;
}, hTree = function(_, ee) {
for (var ne = [], ie = 0; ie < _.length; ++ie) if (_[ie]) ne.push({
s: ie,
f: _[ie]
});
var re = ne.length, se = ne.slice();
if (!re) return {
t: et,
l: 0
};
if (1 == re) {
var oe = new u8(ne[0].s + 1);
oe[ne[0].s] = 1;
return {
t: oe,
l: 1
};
}
ne.sort((function(_, ee) {
return _.f - ee.f;
}));
ne.push({
s: -1,
f: 25001
});
var le = ne[0], ue = ne[1], de = 0, fe = 1, he = 2;
ne[0] = {
s: -1,
f: le.f + ue.f,
l: le,
r: ue
};
for (;fe != re - 1; ) {
le = ne[ne[de].f < ne[he].f ? de++ : he++];
ue = ne[de != fe && ne[de].f < ne[he].f ? de++ : he++];
ne[fe++] = {
s: -1,
f: le.f + ue.f,
l: le,
r: ue
};
}
var pe = se[0].s;
for (ie = 1; ie < re; ++ie) if (se[ie].s > pe) pe = se[ie].s;
var ge = new u16(pe + 1), me = ln(ne[fe - 1], ge, 0);
if (me > ee) {
ie = 0;
var ye = 0, ve = me - ee, Se = 1 << ve;
se.sort((function(_, ee) {
return ge[ee.s] - ge[_.s] || _.f - ee.f;
}));
for (;ie < re; ++ie) {
var Ee = se[ie].s;
if (ge[Ee] > ee) {
ye += Se - (1 << me - ge[Ee]);
ge[Ee] = ee;
} else break;
}
ye >>= ve;
for (;ye > 0; ) {
var Ce = se[ie].s;
if (ge[Ce] < ee) ye -= 1 << ee - ge[Ce]++ - 1; else ++ie;
}
for (;ie >= 0 && ye; --ie) {
var we = se[ie].s;
if (ge[we] == ee) {
--ge[we];
++ye;
}
}
me = ee;
}
return {
t: new u8(ge),
l: me
};
}, ln = function(_, ee, ne) {
return -1 == _.s ? Math.max(ln(_.l, ee, ne + 1), ln(_.r, ee, ne + 1)) : ee[_.s] = ne;
}, lc = function(_) {
for (var ee = _.length; ee && !_[--ee]; ) ;
for (var ne = new u16(++ee), ie = 0, re = _[0], se = 1, w2 = function(_) {
ne[ie++] = _;
}, oe = 1; oe <= ee; ++oe) if (_[oe] == re && oe != ee) ++se; else {
if (!re && se > 2) {
for (;se > 138; se -= 138) w2(32754);
if (se > 2) {
w2(se > 10 ? se - 11 << 5 | 28690 : se - 3 << 5 | 12305);
se = 0;
}
} else if (se > 3) {
w2(re), --se;
for (;se > 6; se -= 6) w2(8304);
if (se > 2) w2(se - 3 << 5 | 8208), se = 0;
}
for (;se--; ) w2(re);
se = 1;
re = _[oe];
}
return {
c: ne.subarray(0, ie),
n: ee
};
}, clen = function(_, ee) {
for (var ne = 0, ie = 0; ie < ee.length; ++ie) ne += _[ie] * ee[ie];
return ne;
}, wfblk = function(_, ee, ne) {
var ie = ne.length, re = shft(ee + 2);
_[re] = 255 & ie;
_[re + 1] = ie >> 8;
_[re + 2] = 255 ^ _[re];
_[re + 3] = 255 ^ _[re + 1];
for (var se = 0; se < ie; ++se) _[re + se + 4] = ne[se];
return 8 * (re + 4 + ie);
}, wblk = function(_, ee, ne, ie, re, se, oe, le, ue, de, fe) {
wbits(ee, fe++, ne);
++re[256];
for (var he = hTree(re, 15), pe = he.t, ge = he.l, me = hTree(se, 15), ye = me.t, ve = me.l, Se = lc(pe), Ee = Se.c, Ce = Se.n, we = lc(ye), Oe = we.c, ke = we.n, xe = new u16(19), Ae = 0; Ae < Ee.length; ++Ae) ++xe[31 & Ee[Ae]];
for (Ae = 0; Ae < Oe.length; ++Ae) ++xe[31 & Oe[Ae]];
for (var Le = hTree(xe, 7), Re = Le.t, Te = Le.l, Pe = 19; Pe > 4 && !Re[clim[Pe - 1]]; --Pe) ;
var Ie, De, Be, Ne, Me = de + 5 << 3, Fe = clen(re, flt) + clen(se, fdt) + oe, je = clen(re, pe) + clen(se, ye) + oe + 14 + 3 * Pe + clen(xe, Re) + 2 * xe[16] + 3 * xe[17] + 7 * xe[18];
if (ue >= 0 && Me <= Fe && Me <= je) return wfblk(ee, fe, _.subarray(ue, ue + de));
wbits(ee, fe, 1 + (je < Fe)), fe += 2;
if (je < Fe) {
Ie = hMap(pe, ge, 0), De = pe, Be = hMap(ye, ve, 0), Ne = ye;
var $e = hMap(Re, Te, 0);
wbits(ee, fe, Ce - 257);
wbits(ee, fe + 5, ke - 1);
wbits(ee, fe + 10, Pe - 4);
fe += 14;
for (Ae = 0; Ae < Pe; ++Ae) wbits(ee, fe + 3 * Ae, Re[clim[Ae]]);
fe += 3 * Pe;
for (var Ge = [ Ee, Oe ], Ve = 0; Ve < 2; ++Ve) {
var Ue = Ge[Ve];
for (Ae = 0; Ae < Ue.length; ++Ae) {
var ze = 31 & Ue[Ae];
wbits(ee, fe, $e[ze]), fe += Re[ze];
if (ze > 15) wbits(ee, fe, Ue[Ae] >> 5 & 127), fe += Ue[Ae] >> 12;
}
}
} else Ie = flm, De = flt, Be = fdm, Ne = fdt;
for (Ae = 0; Ae < le; ++Ae) {
var qe = ie[Ae];
if (qe > 255) {
wbits16(ee, fe, Ie[257 + (ze = qe >> 18 & 31)]), fe += De[ze + 257];
if (ze > 7) wbits(ee, fe, qe >> 23 & 31), fe += fleb[ze];
var He = 31 & qe;
wbits16(ee, fe, Be[He]), fe += Ne[He];
if (He > 3) wbits16(ee, fe, qe >> 5 & 8191), fe += fdeb[He];
} else wbits16(ee, fe, Ie[qe]), fe += De[qe];
}
wbits16(ee, fe, Ie[256]);
return fe + De[256];
}, deo = new i32([ 65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632 ]), et = new u8(0), dflt = function(_, ee, ne, ie, re, se) {
var oe = se.z || _.length, le = new u8(ie + oe + 5 * (1 + Math.ceil(oe / 7e3)) + re), ue = le.subarray(ie, le.length - re), de = se.l, fe = 7 & (se.r || 0);
if (ee) {
if (fe) ue[0] = se.r >> 3;
for (var he = deo[ee - 1], pe = he >> 13, ge = 8191 & he, me = (1 << ne) - 1, ye = se.p || new u16(32768), ve = se.h || new u16(me + 1), Se = Math.ceil(ne / 3), Ee = 2 * Se, hsh = function(ee) {
return (_[ee] ^ _[ee + 1] << Se ^ _[ee + 2] << Ee) & me;
}, Ce = new i32(25e3), we = new u16(288), Oe = new u16(32), ke = 0, xe = 0, Ae = se.i || 0, Le = 0, Re = se.w || 0, Te = 0; Ae + 2 < oe; ++Ae) {
var Pe = hsh(Ae), Ie = 32767 & Ae, De = ve[Pe];
ye[Ie] = De;
ve[Pe] = Ie;
if (Re <= Ae) {
var Be = oe - Ae;
if ((ke > 7e3 || Le > 24576) && (Be > 423 || !de)) {
fe = wblk(_, ue, 0, Ce, we, Oe, xe, Le, Te, Ae - Te, fe);
Le = ke = xe = 0, Te = Ae;
for (var Ne = 0; Ne < 286; ++Ne) we[Ne] = 0;
for (Ne = 0; Ne < 30; ++Ne) Oe[Ne] = 0;
}
var Me = 2, Fe = 0, je = ge, $e = Ie - De & 32767;
if (Be > 2 && Pe == hsh(Ae - $e)) for (var Ge = Math.min(pe, Be) - 1, Ve = Math.min(32767, Ae), Ue = Math.min(258, Be); $e <= Ve && --je && Ie != De; ) {
if (_[Ae + Me] == _[Ae + Me - $e]) {
for (var ze = 0; ze < Ue && _[Ae + ze] == _[Ae + ze - $e]; ++ze) ;
if (ze > Me) {
Me = ze, Fe = $e;
if (ze > Ge) break;
var qe = Math.min($e, ze - 2), He = 0;
for (Ne = 0; Ne < qe; ++Ne) {
var Ke = Ae - $e + Ne & 32767, We = Ke - ye[Ke] & 32767;
if (We > He) He = We, De = Ke;
}
}
}
$e += (Ie = De) - (De = ye[Ie]) & 32767;
}
if (Fe) {
Ce[Le++] = 268435456 | revfl[Me] << 18 | revfd[Fe];
var Xe = 31 & revfl[Me], Je = 31 & revfd[Fe];
xe += fleb[Xe] + fdeb[Je];
++we[257 + Xe];
++Oe[Je];
Re = Ae + Me;
++ke;
} else {
Ce[Le++] = _[Ae];
++we[_[Ae]];
}
}
}
for (Ae = Math.max(Ae, Re); Ae < oe; ++Ae) {
Ce[Le++] = _[Ae];
++we[_[Ae]];
}
fe = wblk(_, ue, de, Ce, we, Oe, xe, Le, Te, Ae - Te, fe);
if (!de) {
se.r = 7 & fe | ue[fe / 8 | 0] << 3;
fe -= 7;
se.h = ve, se.p = ye, se.i = Ae, se.w = Re;
}
} else {
for (Ae = se.w || 0; Ae < oe + de; Ae += 65535) {
var Qe = Ae + 65535;
if (Qe >= oe) {
ue[fe / 8 | 0] = de;
Qe = oe;
}
fe = wfblk(ue, fe + 1, _.subarray(Ae, Qe));
}
se.i = oe;
}
return slc(le, 0, ie + shft(fe) + re);
}, dopt = function(_, ee, ne, ie, re) {
if (!re) {
re = {
l: 1
};
if (ee.dictionary) {
var se = ee.dictionary.subarray(-32768), oe = new u8(se.length + _.length);
oe.set(se);
oe.set(_, se.length);
_ = oe;
re.w = se.length;
}
}
return dflt(_, null == ee.level ? 6 : ee.level, null == ee.mem ? re.l ? Math.ceil(1.5 * Math.max(8, Math.min(13, Math.log(_.length)))) : 20 : 12 + ee.mem, ne, ie, re);
}, mrg = function(_, ee) {
var ne = {};
for (var ie in _) ne[ie] = _[ie];
for (var ie in ee) ne[ie] = ee[ie];
return ne;
}, wcln = function(_, ee, ne) {
for (var ie = _(), re = _.toString(), se = re.slice(re.indexOf("[") + 1, re.lastIndexOf("]")).replace(/\s+/g, "").split(","), oe = 0; oe < ie.length; ++oe) {
var le = ie[oe], ue = se[oe];
if ("function" == typeof le) {
ee += ";" + ue + "=";
var de = le.toString();
if (le.prototype) if (-1 != de.indexOf("[native code]")) {
var fe = de.indexOf(" ", 8) + 1;
ee += de.slice(fe, de.indexOf("(", fe));
} else {
ee += de;
for (var he in le.prototype) ee += ";" + ue + ".prototype." + he + "=" + le.prototype[he].toString();
} else ee += de;
} else ne[ue] = le;
}
return ee;
}, ch = [], cbfs = function(_) {
var ee = [];
for (var ne in _) if (_[ne].buffer) ee.push((_[ne] = new _[ne].constructor(_[ne])).buffer);
return ee;
}, wrkr = function(_, ee, ne, ie) {
if (!ch[ne]) {
for (var re = "", se = {}, oe = _.length - 1, le = 0; le < oe; ++le) re = wcln(_[le], re, se);
ch[ne] = {
c: wcln(_[oe], re, se),
e: se
};
}
var ue = mrg({}, ch[ne].e);
return wk(ch[ne].c + ";onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage=" + ee.toString() + "}", ne, ue, cbfs(ue), ie);
}, bInflt = function() {
return [ u8, u16, i32, fleb, fdeb, clim, fl, fd, flrm, fdrm, rev, ec, hMap, max, bits, bits16, shft, slc, err, inflt, inflateSync, pbf, gopt ];
}, bDflt = function() {
return [ u8, u16, i32, fleb, fdeb, clim, revfl, revfd, flm, flt, fdm, fdt, rev, deo, et, hMap, wbits, wbits16, hTree, ln, lc, clen, wfblk, wblk, shft, slc, dflt, dopt, deflateSync, pbf ];
}, pbf = function(_) {
return postMessage(_, [ _.buffer ]);
}, gopt = function(_) {
return _ && {
out: _.size && new u8(_.size),
dictionary: _.dictionary
};
}, cbify = function(_, ee, ne, ie, re, se) {
var oe = wrkr(ne, ie, re, (function(_, ee) {
oe.terminate();
se(_, ee);
}));
oe.postMessage([ _, ee ], ee.consume ? [ _.buffer ] : []);
return function() {
oe.terminate();
};
};
function deflate(_, ee, ne) {
if (!ne) ne = ee, ee = {};
if ("function" != typeof ne) err(7);
return cbify(_, ee, [ bDflt ], (function(_) {
return pbf(deflateSync(_.data[0], _.data[1]));
}), 0, ne);
}
function deflateSync(_, ee) {
return dopt(_, ee || {}, 0, 0);
}
function inflate(_, ee, ne) {
if (!ne) ne = ee, ee = {};
if ("function" != typeof ne) err(7);
return cbify(_, ee, [ bInflt ], (function(_) {
return pbf(inflateSync(_.data[0], gopt(_.data[1])));
}), 1, ne);
}
function inflateSync(_, ee) {
return inflt(_, {
i: 2
}, ee && ee.out, ee && ee.dictionary);
}
var td = "undefined" != typeof TextDecoder && new TextDecoder, tds = 0;
try {
td.decode(et, {
stream: true
});
tds = 1;
} catch (_) {}
var isValidRemoteCouchDBURI = _ => {
if (_.startsWith("https://")) return true;
if (_.startsWith("http://")) return true; else return false;
};
function isCloudantURI(_) {
if (-1 !== _.indexOf(".cloudantnosqldb.") || -1 !== _.indexOf(".cloudant.com")) return true; else return false;
}
var checkRemoteVersion = async (_, ee, ne = VER) => {
try {
const ie = await _.get(VERSIONINFO_DOCID);
if ("versioninfo" != ie.type) return false;
const re = ie.version;
if (re < ne) if (await ee(re, ne)) {
await bumpRemoteVersion(_);
return true;
}
if (re == ne) return true; else return false;
} catch (ee) {
if (isErrorOfMissingDoc(ee)) if (await bumpRemoteVersion(_)) return true; else return false;
throw ee;
}
}, bumpRemoteVersion = async (_, ee = VER) => {
const ne = {
_id: VERSIONINFO_DOCID,
version: ee,
type: "versioninfo"
}, ie = await resolveWithIgnoreKnownError(_.get(VERSIONINFO_DOCID), ne);
if ("versioninfo" != ie.type) return false;
ne._rev = ie._rev;
await _.put(ne);
return true;
}, checkSyncInfo = async _ => {
try {
const ee = await _.get(SYNCINFO_ID);
console.log(ee);
return true;
} catch (ee) {
if (isErrorOfMissingDoc(ee)) {
const ee = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", ne = [ ...Array(30) ].map((_ => Math.floor(Math.random() * ee.length))).map((_ => ee[_])).join(""), ie = {
_id: SYNCINFO_ID,
type: "syncinfo",
data: ne
};
if (await _.put(ie)) return true; else return false;
} else {
console.dir(ee);
return false;
}
}
}, MARK_SHIFT = "L", MARK_SHIFT_COMPRESSED = `${MARK_SHIFT}Z`;
function wrapFflateFunc(_) {
return (ee, ne) => new Promise(((ie, re) => {
_(ee, ne, ((_, ee) => {
if (_) re(_); else ie(ee);
}));
}));
}
var wrappedInflate = wrapFflateFunc(inflate), wrappedDeflate = wrapFflateFunc(deflate);
async function _compressText(_) {
const ee = tryConvertBase64ToArrayBuffer(_), ne = new Uint8Array(ee || await new Blob([ _ ], {
type: "application/octet-stream"
}).arrayBuffer());
if (0 == ne.buffer.byteLength) return "";
const ie = await wrappedDeflate(new Uint8Array(ne), {
consume: true,
level: 8
});
return (ee ? "~" : "") + await arrayBufferToBase64Single(ie);
}
async function _decompressText(_, ee = false) {
if (0 == _.length) return "";
const ne = "~" == _[0], ie = _.substring(ne ? 1 : 0);
if (0 == ie.length) return "";
const re = new Uint8Array(base64ToArrayBuffer(ie));
if (0 == re.length) return "";
const se = await wrappedInflate(new Uint8Array(re), {
consume: true
});
if (ne) return await arrayBufferToBase64Single(se);
const oe = new Blob([ se ]);
return await oe.text();
}
async function compressDoc(_) {
if (!("data" in _)) return _;
if ("string" != typeof _.data) return _;
if (_.data.startsWith(MARK_SHIFT_COMPRESSED)) return _;
const ee = _.data, ne = await _compressText(ee), ie = MARK_SHIFT_COMPRESSED + ne;
if (_.data.length > ie.length) _.data = ie;
return _;
}
async function decompressDoc(_) {
if (!("data" in _)) return _;
if ("string" != typeof _.data) return _;
if (_.data.startsWith(MARK_SHIFT_COMPRESSED)) _.data = await _decompressText(_.data.substring(MARK_SHIFT_COMPRESSED.length));
return _;
}
var enableCompression = (_, ee) => {
_.transform({
async incoming(_) {
if (!ee) return _; else return await compressDoc(_);
},
outgoing: async _ => await decompressDoc(_)
});
}, EDEN_ENCRYPTED_KEY = "h:++encrypted";
function shouldEncryptEden(_) {
if ("eden" in _ && !(EDEN_ENCRYPTED_KEY in _.eden)) return true; else return false;
}
function shouldDecryptEden(_) {
if ("eden" in _ && EDEN_ENCRYPTED_KEY in _.eden) return true; else return false;
}
var enableEncryption = (_, ee, ne, ie) => {
const re = new Map;
_.transform({
incoming: async _ => {
const ie = {
..._
};
if (isEncryptedChunkEntry(ie) || isSyncInfoEntry(ie)) try {
ie.data = await encrypt(ie.data, ee, ne);
} catch (_) {
Logger("Encryption failed.", LOG_LEVEL_NOTICE);
Logger(_);
throw _;
}
if (shouldEncryptEden(ie)) ie.eden = {
[EDEN_ENCRYPTED_KEY]: {
data: await encrypt(JSON.stringify(ie.eden), ee, ne),
epoch: 999999
}
};
if (isObfuscatedEntry(ie)) try {
ie.path = await obfuscatePath(getPath(ie), ee, ne);
} catch (_) {
Logger("Encryption failed.", LOG_LEVEL_NOTICE);
Logger(_);
throw _;
}
return ie;
},
outgoing: async _ => {
var se, oe;
const le = {
..._
}, ue = isEncryptedChunkEntry(le) || isSyncInfoEntry(le), de = isObfuscatedEntry(le), fe = shouldDecryptEden(le);
if (ue || de || fe) {
if (ie && re.has(le._id)) return le;
try {
if (ue) le.data = await decrypt(le.data, ee, ne);
if (de) le.path = await decrypt(getPath(le), ee, ne);
if (fe) le.eden = JSON.parse(await decrypt(le.eden[EDEN_ENCRYPTED_KEY].data, ee, ne));
if (ie) re.set(le._id, true);
} catch (_) {
if (ne) try {
if (ue) le.data = await decrypt(le.data, ee, false);
if (de) le.path = await decrypt(getPath(le), ee, false);
if (fe) le.eden = JSON.parse(await decrypt(le.eden[EDEN_ENCRYPTED_KEY].data, ee, false));
if (ie) re.set(le._id, true);
} catch (_) {
if (ie && "SyntaxError" == _.name) return le;
Logger("Decryption failed.", LOG_LEVEL_NOTICE);
Logger(_, LOG_LEVEL_VERBOSE);
Logger(`id:${le._id}-${null == (se = le._rev) ? void 0 : se.substring(0, 10)}`, LOG_LEVEL_VERBOSE);
throw _;
} else {
Logger("Decryption failed.", LOG_LEVEL_NOTICE);
Logger(_, LOG_LEVEL_VERBOSE);
Logger(`id:${le._id}-${null == (oe = le._rev) ? void 0 : oe.substring(0, 10)}`, LOG_LEVEL_VERBOSE);
throw _;
}
}
}
return le;
}
});
};
function isErrorOfMissingDoc(_) {
return 404 == (_ && (null == _ ? void 0 : _.status));
}
async function prepareChunkDesignDoc(_) {
var ee;
const ne = {
_id: "_design/chunks",
_rev: void 0,
ver: 2,
views: {
collectDangling: {
map: (function(_) {
if (_._id.startsWith("h:")) emit([ _._id ], 0); else if ("children" in _) _.children.forEach((_ => emit([ _ ], 1)));
}).toString(),
reduce: "_sum"
}
}
};
let ie = false;
try {
const re = await _.get(ne._id);
if (null != (ee = null == re ? void 0 : re.ver) ? ee : 0 < ne.ver) {
ne._rev = re._rev;
ie = true;
}
} catch (_) {
if (404 == _.status) ie = true; else {
Logger("Failed to make design document for operating chunks");
Logger(_, LOG_LEVEL_VERBOSE);
return false;
}
}
try {
if (ie) await _.put(ne);
} catch (_) {
Logger("Failed to make design document for operating chunks");
Logger(_, LOG_LEVEL_VERBOSE);
return false;
}
return true;
}
async function collectChunksUsage(_) {
if (!await prepareChunkDesignDoc(_)) {
Logger("Could not prepare design document for operating chunks");
return [];
}
return (await _.query("chunks/collectDangling", {
reduce: true,
group: true
})).rows;
}
function collectUnreferencedChunks(_) {
return collectChunks(_, "DANGLING");
}
async function collectChunks(_, ee) {
const ne = await collectChunksUsage(_), ie = ("ALL" == ee ? ne : ne.filter((_ => "DANGLING" == ee ? 0 == _.value : 0 != _.value))).flatMap((_ => _.key));
return (await _.allDocs({
keys: ie
})).rows.filter((_ => !("error" in _))).map((_ => ({
id: _.id,
rev: _.value.rev
})));
}
async function collectUnbalancedChunkIDs(_, ee) {
const ne = await collectChunks(_, "INUSE"), ie = await collectChunks(ee, "INUSE");
return {
onlyOnLocal: ne.filter((_ => !ie.some((ee => ee.id == _.id)))),
onlyOnRemote: ie.filter((_ => !ne.some((ee => ee.id == _.id))))
};
}
async function purgeChunksLocal(_, ee) {
await serialized("purge-local", (async () => {
try {
Logger(`Purging unused ${ee.length} chunks `, LOG_LEVEL_NOTICE, "purge-local-backup");
const ne = arrayToChunkedArray(ee, 100);
let ie = {
ok: 0,
exist: 0,
error: 0
};
for (const ee of ne) {
const ne = (await _.allDocs({
keys: ee.map((_ => _.id)),
include_docs: true
})).rows.filter((_ => "doc" in _)).map((_ => {
const ee = {
..._.doc
};
delete ee._rev;
ee._id = `_local/${ee._id}`;
return ee;
})), re = await _.bulkDocs(ne);
ie = re.map((_ => ({
ok: "ok" in _ ? 1 : 0,
exist: "status" in _ && 409 == _.status ? 1 : 0,
error: "status" in _ && 409 != _.status ? 1 : 0
}))).reduce(((_, ee) => ({
ok: _.ok + ee.ok,
exist: _.exist + ee.exist,
error: _.error + ee.error
})), ie);
Logger(`Local chunk backed up: new:${ie.ok} ,exist:${ie.exist}, error:${ie.error}`, LOG_LEVEL_NOTICE, "purge-local-backup");
const se = re.filter((_ => "error" in _ && 409 != _.status));
for (const _ of se) Logger(`Failed to back up: ${_.id} / ${_.rev}`, LOG_LEVEL_VERBOSE);
}
} catch (_) {
Logger("Could not back up chunks");
Logger(_, LOG_LEVEL_VERBOSE);
}
Logger(`Purging unused ${ee.length} chunks... `, LOG_LEVEL_NOTICE, "purge-local");
const ne = arrayToChunkedArray(ee, 100);
let ie = 0;
for (const re of ne) {
const ne = await _.purgeMulti(re.map((_ => [ _.id, _.rev ])));
ie += Object.values(ne).filter((_ => "ok" in _)).length;
Logger(`Purging: ${ie} / ${ee.length}`, LOG_LEVEL_NOTICE, "purge-local");
}
Logger(`Purging unused chunks done!: ${ie} chunks has been deleted.`, LOG_LEVEL_NOTICE, "purge-local");
}));
}
var _requestToCouchDBFetch = async (_, ee, ne, ie, re, se) => {
const oe = String.fromCharCode.apply(null, [ ...writeString(`${ee}:${ne}`) ]), le = window.btoa(oe), ue = `${_}/${ie}`, de = {
url: ue,
method: se || (re ? "PUT" : "GET"),
headers: new Headers({
authorization: "Basic " + le,
"content-type": "application/json"
}),
contentType: "application/json",
body: JSON.stringify(re)
};
return await fetch(ue, de);
};
async function purgeChunksRemote(_, ee) {
await serialized("purge-remote", (async () => {
const ne = function makeChunkedArrayFromArray(_) {
const ee = [];
for (let ne = 0; ne < _.length; ne += 100) ee.push(_.slice(ne, ne + 100));
return ee;
}(ee);
for (const ee of ne) {
const ne = await _requestToCouchDBFetch(`${_.couchDB_URI}/${_.couchDB_DBNAME}`, _.couchDB_USER, _.couchDB_PASSWORD, "_purge", Object.fromEntries(ee.map((_ => [ _.id, [ _.rev ] ]))), "POST");
Logger(JSON.stringify(await ne.json()), LOG_LEVEL_VERBOSE);
}
}));
}
function sizeToHumanReadable(_) {
if (!_) return "-";
const ee = Math.floor(Math.log(_) / Math.log(1024));
return Number.parseInt((_ / Math.pow(1024, ee)).toFixed(2)) + " " + [ "B", "kB", "MB", "GB", "TB" ][ee];
}
async function purgeUnreferencedChunks(_, ee, ne, ie = false) {
const re = await _.info();
let se = 0;
const getSize = function(_, ee) {
var ne, ie;
return Number.parseInt(null != (ie = null == (ne = null == _ ? void 0 : _.sizes) ? void 0 : ne[ee]) ? ie : 0);
}, oe = ne ? "-remote" : "-local";
Logger(`${ee ? "Counting" : "Cleaning"} ${ne ? "remote" : "local"} database`, LOG_LEVEL_NOTICE);
if (ne) Logger(`Database active-size: ${sizeToHumanReadable(getSize(re, "active"))}, external-size:${sizeToHumanReadable(getSize(re, "external"))}, file-size: ${sizeToHumanReadable(getSize(re, "file"))}`, LOG_LEVEL_NOTICE);
Logger(`Collecting unreferenced chunks on ${re.db_name}`, LOG_LEVEL_NOTICE, "gc-countchunk" + oe);
const le = await collectUnreferencedChunks(_);
se = le.length;
if (0 == le.length) Logger(`No unreferenced chunks! ${re.db_name}`, LOG_LEVEL_NOTICE, "gc-countchunk" + oe); else {
Logger(`Number of unreferenced chunks on ${re.db_name}: ${le.length}`, LOG_LEVEL_NOTICE, "gc-countchunk" + oe);
if (ee) {
Logger(`DryRun of cleaning ${ne ? "remote" : "local"} database up: Done`, LOG_LEVEL_NOTICE);
return se;
}
if (ne) {
Logger("Cleaning unreferenced chunks on remote", LOG_LEVEL_NOTICE, "gc-purge" + oe);
await purgeChunksRemote(ne, le);
} else {
Logger("Cleaning unreferenced chunks on local", LOG_LEVEL_NOTICE, "gc-purge" + oe);
await purgeChunksLocal(_, le);
}
Logger("Cleaning unreferenced chunks done!", LOG_LEVEL_NOTICE, "gc-purge" + oe);
}
if (ie) {
Logger("Compacting database...", LOG_LEVEL_NOTICE, "gc-compact" + oe);
await _.compact();
Logger("Compacting database done", LOG_LEVEL_NOTICE, "gc-compact" + oe);
}
if (ne) {
const ee = await _.info();
Logger(`Processed database active-size: ${sizeToHumanReadable(getSize(ee, "active"))}, external-size:${sizeToHumanReadable(getSize(ee, "external"))}, file-size: ${sizeToHumanReadable(getSize(ee, "file"))}`, LOG_LEVEL_NOTICE);
Logger(`Reduced sizes: active-size: ${sizeToHumanReadable(getSize(re, "active") - getSize(ee, "active"))}, external-size:${sizeToHumanReadable(getSize(re, "external") - getSize(ee, "external"))}, file-size: ${sizeToHumanReadable(getSize(re, "file") - getSize(ee, "file"))}`, LOG_LEVEL_NOTICE);
}
Logger(`Cleaning ${ne ? "remote" : "local"} database up: Done`, LOG_LEVEL_NOTICE);
return se;
}
function transferChunks(_, ee, ne, ie, re) {
let se = 0;
const oe = re.length;
return new QueueProcessor((async _ => {
const ee = _.map((_ => _.id));
return (await ie.allDocs({
keys: ee
})).rows.filter((_ => "error" in _ && "not_found" == _.error)).map((_ => _.key));
}), {
batchSize: 50,
concurrentLimit: 5,
suspended: true,
delay: 100
}, re).pipeTo(new QueueProcessor((async _ => (await ne.allDocs({
keys: _,
include_docs: true
})).rows.filter((_ => !("error" in _))).map((_ => _.doc))), {
batchSize: 25,
concurrentLimit: 1,
suspended: true,
delay: 100
})).pipeTo(new QueueProcessor((async ne => {
try {
await ie.bulkDocs(ne, {
new_edits: false
});
} catch (_) {
Logger(`${ee}: Something went wrong on balancing`, LOG_LEVEL_NOTICE);
Logger(_, LOG_LEVEL_VERBOSE);
} finally {
se += ne.length;
Logger(`${ee}: ${se} / ${oe}`, LOG_LEVEL_NOTICE, "balance-" + _);
}
}), {
batchSize: 100,
delay: 100,
concurrentLimit: 2,
suspended: false
})).startPipeline().waitForAllDoneAndTerminate();
}
async function balanceChunkPurgedDBs(_, ee) {
Logger("Complement missing chunks between databases", LOG_LEVEL_NOTICE);
try {
const {onlyOnLocal: ne, onlyOnRemote: ie} = await collectUnbalancedChunkIDs(_, ee), re = transferChunks("l2r", "local -> remote", _, ee, ne), se = transferChunks("r2l", "remote -> local", ee, _, ie);
await Promise.all([ re, se ]);
Logger("local -> remote: Done", LOG_LEVEL_NOTICE, "balance-l2r");
Logger("remote -> local: Done", LOG_LEVEL_NOTICE, "balance-r2l");
} catch (_) {
Logger("Something went wrong on balancing!", LOG_LEVEL_NOTICE);
Logger(_, LOG_LEVEL_VERBOSE);
}
Logger("Complement completed!", LOG_LEVEL_NOTICE);
}
async function fetchAllUsedChunks(_, ee) {
try {
const ne = await collectChunks(ee, "INUSE");
await transferChunks("r2l", "remote -> local", ee, _, ne);
Logger("remote -> local: Done", LOG_LEVEL_NOTICE, "balance-r2l");
} catch (_) {
Logger("Something went wrong on balancing!", LOG_LEVEL_NOTICE);
Logger(_, LOG_LEVEL_VERBOSE);
}
}
function polyfillPromiseWithResolvers() {
let _, ee;
return {
promise: new Promise(((ne, ie) => {
_ = ne;
ee = ie;
})),
resolve: _,
reject: ee
};
}
var promiseWithResolver = polyfillPromiseWithResolvers;
function resolveWithIgnoreKnownError(_, ee) {
return new Promise(((ne, ie) => {
_.then(ne).catch((_ => isErrorOfMissingDoc(_) ? ne(ee) : ie(_)));
}));
}
var _a2, delay = (_, ee) => new Promise((ne => {
setTimeout((() => {
ne(ee);
}), _);
}));
function getDocData(_) {
return "string" == typeof _ ? _ : _.join("");
}
function getDocDataAsArray(_) {
return "string" == typeof _ ? [ _ ] : _;
}
function isTextBlob(_) {
return "text/plain" === _.type;
}
function createTextBlob(_) {
const ee = Array.isArray(_) ? _ : [ _ ];
return new Blob(ee, {
endings: "transparent",
type: "text/plain"
});
}
function createBinaryBlob(_) {
return new Blob([ _ ], {
endings: "transparent",
type: "application/octet-stream"
});
}
function createBlob(_) {
if (_ instanceof Blob) return _;
if (_ instanceof Uint8Array || _ instanceof ArrayBuffer) return createBinaryBlob(_); else return createTextBlob(_);
}
function isTextDocument(_) {
if ("plain" == _.type) return true;
if ("plain" == _.datatype) return true;
if (isPlainText(_.path)) return true; else return false;
}
function readAsBlob(_) {
if (isTextDocument(_)) return createTextBlob(_.data); else return createBinaryBlob(decodeBinary(_.data));
}
function readContent(_) {
if (isTextDocument(_)) return getDocData(_.data); else return decodeBinary(_.data);
}
var isIndexDBCmpExist = "undefined" != typeof (null == (_a2 = null == window ? void 0 : window.indexedDB) ? void 0 : _a2.cmp);
async function isDocContentSame(_, ee) {
const ne = createBlob(_), ie = createBlob(ee);
if (ne.size != ie.size) return false;
if (isIndexDBCmpExist) return 0 === window.indexedDB.cmp(await ne.arrayBuffer(), await ie.arrayBuffer());
const re = 1e4, se = ne.size;
let oe = 0;
for (;oe < se; ) {
const _ = await ne.slice(oe, oe + re).arrayBuffer(), ee = await ie.slice(oe, oe + re).arrayBuffer();
oe += re;
if (await arrayBufferToBase64Single(_) != await arrayBufferToBase64Single(ee)) return false;
}
return true;
}
function isObfuscatedEntry(_) {
if (_._id.startsWith(PREFIX_OBFUSCATED)) return true; else return false;
}
function isEncryptedChunkEntry(_) {
if (_._id.startsWith(PREFIX_ENCRYPTED_CHUNK)) return true; else return false;
}
function isSyncInfoEntry(_) {
if (_._id == SYNCINFO_ID) return true; else return false;
}
function memorizeFuncWithLRUCache(_) {
const ee = new LRUCache(100, 1e5, true);
return ne => {
if (ee.has(ne)) return ee.get(ne);
const ie = _(ne);
ee.set(ne, ie);
return ie;
};
}
var traps = {};
async function waitForSignal(_, ee) {
return await waitForValue(_, ee) !== RESULT_TIMED_OUT;
}
function waitForValue(_, ee) {
let ne, ie;
const re = ee ? setTimeout((() => {
if (_ in traps) traps[_] = traps[_].filter((_ => _ != ie));
if (ne) ne(RESULT_TIMED_OUT);
ne = void 0;
}), ee) : false;
return new Promise((ee => {
if (!(_ in traps)) traps[_] = [];
ne = ee;
ie = _ => {
if (re) clearTimeout(re);
ee(_);
};
traps[_].push(ie);
}));
}
function sendSignal(_) {
sendValue(_, true);
}
function sendValue(_, ee) {
if (!(_ in traps)) return;
const ne = traps[_];
delete traps[_];
for (const _ of ne) _(ee);
}
function onlyNot(_) {
return function _onlyNot(ee) {
if (ee === _) return false; else return true;
};
}
var globalConcurrencyController = Semaphore(50);
function* arrayToChunkedArray(_, ee) {
const ne = [ ..._ ];
for (;ne.length; ) {
const _ = ne.splice(0, ee);
yield _;
}
}
function unique(_) {
return [ ...new Set(_) ];
}
var noop = () => {};
function fireAndForget(_) {
if ("function" == typeof _) return fireAndForget(_());
_.then(noop).catch(noop);
}
function isObjectDifferent(_, ee, ne = false) {
if (typeof _ != typeof ee) return true;
if ("object" == typeof _) {
if (null === _ || null === ee) return _ !== ee;
const ie = [ ...new Set([ ...Object.keys(_), ...Object.keys(ee) ]) ];
if (ne) return ie.map((ne => void 0 !== (null == _ ? void 0 : _[ne]) && void 0 !== (null == ee ? void 0 : ee[ne]) && isObjectDifferent(null == _ ? void 0 : _[ne], null == ee ? void 0 : ee[ne]))).some((_ => true == _)); else return ie.map((ne => isObjectDifferent(null == _ ? void 0 : _[ne], null == ee ? void 0 : ee[ne]))).some((_ => true == _));
} else return _ !== ee;
}
function determineTypeFromBlob(_) {
return isTextBlob(_) ? "plain" : "newnote";
}
function determineType(_, ee) {
if (ee instanceof Blob) return determineTypeFromBlob(ee);
if (isPlainText(_)) return "plain";
if (ee instanceof Uint8Array) return "newnote";
if (ee instanceof ArrayBuffer) return "newnote"; else return "plain";
}
function isAnyNote(_) {
return "type" in _ && ("newnote" == _.type || "plain" == _.type);
}
function createSavingEntryFromLoadedEntry(_) {
const ee = readAsBlob(_), ne = determineType(_.path, ee);
return {
..._,
data: ee,
datatype: ne,
type: ne,
children: []
};
}
var ExportedSet, ExportedMap, throttle = (_, ee) => {
let ne, ie = 0;
return (...re) => {
if (!ie) {
_(...re);
ie = Date.now();
} else {
clearTimeout(ne);
const se = ee - (Date.now() - ie);
ne = setTimeout((() => {
_(...re);
ie = Date.now();
}), se);
}
};
};
function extractObject(_, ee) {
const ne = {
..._
};
for (const _ in ne) ne[_] = ee[_];
return ne;
}
function setAllItems(_, ee) {
ee.forEach((ee => _.add(ee)));
return _;
}
function concatUInt8Array(_) {
const ee = _.reduce(((_, ee) => _ + ee.length), 0), ne = new Uint8Array(ee);
let ie = 0;
for (const ee of _) {
ne.set(ee, ie);
ie += ee.length;
}
return ne;
}
function replaceAll(_, ee, ne) {
if ("replaceAll" in String.prototype) return _.replaceAll(ee, ne); else return _.split(ee).join(ne);
}
function replaceAllPairs(_, ...ee) {
let ne = `${_}`;
for (const [_, ie] of ee) ne = replaceAll(ne, _, ie);
return ne;
}
function escapeNewLineFromString(_) {
if (_.indexOf("\n") < 0) return _; else return "\\f" + replaceAll(replaceAll(_, "\\", "\\\\"), "\n", "\\n");
}
function unescapeNewLineFromString(_) {
if (!_.startsWith("\\f")) return _; else return replaceAll(replaceAll(_.substring(2), "\\\\", "\\"), "\\n", "\n");
}
function escapeMarkdownValue(_) {
if ("string" == typeof _) return replaceAllPairs(_, [ "|", "\\|" ], [ "`", "\\`" ]); else return _;
}
function mangle(_) {
return "$" + _;
}
function unmangle(_) {
return _.substring(1);
}
function Map$1() {
this._store = {};
}
Map$1.prototype.get = function(_) {
var ee = mangle(_);
return this._store[ee];
};
Map$1.prototype.set = function(_, ee) {
var ne = mangle(_);
this._store[ne] = ee;
return true;
};
Map$1.prototype.has = function(_) {
return mangle(_) in this._store;
};
Map$1.prototype.keys = function() {
return Object.keys(this._store).map((_ => unmangle(_)));
};
Map$1.prototype.delete = function(_) {
var ee = mangle(_), ne = ee in this._store;
delete this._store[ee];
return ne;
};
Map$1.prototype.forEach = function(_) {
for (var ee = Object.keys(this._store), ne = 0, ie = ee.length; ne < ie; ne++) {
var re = ee[ne];
_(this._store[re], re = unmangle(re));
}
};
Object.defineProperty(Map$1.prototype, "size", {
get: function() {
return Object.keys(this._store).length;
}
});
function Set$1(_) {
this._store = new Map$1;
if (_ && Array.isArray(_)) for (var ee = 0, ne = _.length; ee < ne; ee++) this.add(_[ee]);
}
Set$1.prototype.add = function(_) {
return this._store.set(_, true);
};
Set$1.prototype.has = function(_) {
return this._store.has(_);
};
Set$1.prototype.forEach = function(_) {
this._store.forEach((function(ee, ne) {
_(ne);
}));
};
Object.defineProperty(Set$1.prototype, "size", {
get: function() {
return this._store.size;
}
});
function supportsMapAndSet() {
if ("undefined" == typeof Symbol || "undefined" == typeof Map || "undefined" == typeof Set) return false;
var _ = Object.getOwnPropertyDescriptor(Map, Symbol.species);
return _ && "get" in _ && Map[Symbol.species] === Map;
}
if (supportsMapAndSet()) {
ExportedSet = Set;
ExportedMap = Map;
} else {
ExportedSet = Set$1;
ExportedMap = Map$1;
}
var import_immediate = __toESM(require_lib()), PouchError = class extends Error {
constructor(_, ee, ne) {
super();
this.status = _;
this.name = ee;
this.message = ne;
this.error = true;
}
toString() {
return JSON.stringify({
status: this.status,
name: this.name,
message: this.message,
reason: this.reason
});
}
}, UNAUTHORIZED = new PouchError(401, "unauthorized", "Name or password is incorrect."), MISSING_BULK_DOCS = new PouchError(400, "bad_request", "Missing JSON list of 'docs'"), MISSING_DOC = new PouchError(404, "not_found", "missing"), REV_CONFLICT = new PouchError(409, "conflict", "Document update conflict"), INVALID_ID = new PouchError(400, "bad_request", "_id field must contain a string"), MISSING_ID = new PouchError(412, "missing_id", "_id is required for puts"), RESERVED_ID = new PouchError(400, "bad_request", "Only reserved document ids may start with underscore."), NOT_OPEN = new PouchError(412, "precondition_failed", "Database not open"), UNKNOWN_ERROR = new PouchError(500, "unknown_error", "Database encountered an unknown error"), BAD_ARG = new PouchError(500, "badarg", "Some query argument is invalid"), INVALID_REQUEST = new PouchError(400, "invalid_request", "Request was invalid"), QUERY_PARSE_ERROR = new PouchError(400, "query_parse_error", "Some query parameter is invalid"), DOC_VALIDATION = new PouchError(500, "doc_validation", "Bad special document member"), BAD_REQUEST = new PouchError(400, "bad_request", "Something wrong with the request"), NOT_AN_OBJECT = new PouchError(400, "bad_request", "Document must be a JSON object"), DB_MISSING = new PouchError(404, "not_found", "Database not found"), IDB_ERROR = new PouchError(500, "indexed_db_went_bad", "unknown"), WSQ_ERROR = new PouchError(500, "web_sql_went_bad", "unknown"), LDB_ERROR = new PouchError(500, "levelDB_went_went_bad", "unknown"), FORBIDDEN = new PouchError(403, "forbidden", "Forbidden by design doc validate_doc_update function"), INVALID_REV = new PouchError(400, "bad_request", "Invalid rev format"), FILE_EXISTS = new PouchError(412, "file_exists", "The database could not be created, the file already exists."), MISSING_STUB = new PouchError(412, "missing_stub", "A pre-existing attachment stub wasn't found"), INVALID_URL = new PouchError(413, "invalid_url", "Provided URL is invalid");
function createError(_, ee) {
function CustomPouchError(ee) {
for (var ne = Object.getOwnPropertyNames(_), ie = 0, re = ne.length; ie < re; ie++) if ("function" != typeof _[ne[ie]]) this[ne[ie]] = _[ne[ie]];
if (void 0 === this.stack) this.stack = (new Error).stack;
if (void 0 !== ee) this.reason = ee;
}
CustomPouchError.prototype = PouchError.prototype;
return new CustomPouchError(ee);
}
function generateErrorFromResponse(_) {
if ("object" != typeof _) {
var ee = _;
(_ = UNKNOWN_ERROR).data = ee;
}
if ("error" in _ && "conflict" === _.error) {
_.name = "conflict";
_.status = 409;
}
if (!("name" in _)) _.name = _.error || "unknown";
if (!("status" in _)) _.status = 500;
if (!("message" in _)) _.message = _.message || _.reason;
if (!("stack" in _)) _.stack = (new Error).stack;
return _;
}
var getRandomValues, import_events = __toESM(require_events()), rnds8 = new Uint8Array(16);
function rng() {
if (!getRandomValues) if (!(getRandomValues = "undefined" != typeof crypto && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || "undefined" != typeof msCrypto && "function" == typeof msCrypto.getRandomValues && msCrypto.getRandomValues.bind(msCrypto))) throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
return getRandomValues(rnds8);
}
var regex_default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
function validate(_) {
return "string" == typeof _ && regex_default.test(_);
}
var i2, validate_default = validate, byteToHex = [];
for (i2 = 0; i2 < 256; ++i2) byteToHex.push((i2 + 256).toString(16).substr(1));
function stringify(_) {
var ee = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0, ne = (byteToHex[_[ee + 0]] + byteToHex[_[ee + 1]] + byteToHex[_[ee + 2]] + byteToHex[_[ee + 3]] + "-" + byteToHex[_[ee + 4]] + byteToHex[_[ee + 5]] + "-" + byteToHex[_[ee + 6]] + byteToHex[_[ee + 7]] + "-" + byteToHex[_[ee + 8]] + byteToHex[_[ee + 9]] + "-" + byteToHex[_[ee + 10]] + byteToHex[_[ee + 11]] + byteToHex[_[ee + 12]] + byteToHex[_[ee + 13]] + byteToHex[_[ee + 14]] + byteToHex[_[ee + 15]]).toLowerCase();
if (!validate_default(ne)) throw TypeError("Stringified UUID is invalid");
return ne;
}
var stringify_default = stringify;
function v4(_, ee, ne) {
var ie = (_ = _ || {}).random || (_.rng || rng)();
ie[6] = 15 & ie[6] | 64;
ie[8] = 63 & ie[8] | 128;
if (ee) {
ne = ne || 0;
for (var re = 0; re < 16; ++re) ee[ne + re] = ie[re];
return ee;
}
return stringify_default(ie);
}
var v4_default = v4, thisAtob = function(_) {
return atob(_);
}, thisBtoa = function(_) {
return btoa(_);
};
function createBlob2(_, ee) {
_ = _ || [];
ee = ee || {};
try {
return new Blob(_, ee);
} catch (re) {
if ("TypeError" !== re.name) throw re;
for (var ne = new ("undefined" != typeof BlobBuilder ? BlobBuilder : "undefined" != typeof MSBlobBuilder ? MSBlobBuilder : "undefined" != typeof MozBlobBuilder ? MozBlobBuilder : WebKitBlobBuilder), ie = 0; ie < _.length; ie += 1) ne.append(_[ie]);
return ne.getBlob(ee.type);
}
}
function binaryStringToArrayBuffer(_) {
for (var ee = _.length, ne = new ArrayBuffer(ee), ie = new Uint8Array(ne), re = 0; re < ee; re++) ie[re] = _.charCodeAt(re);
return ne;
}
function binStringToBluffer(_, ee) {
return createBlob2([ binaryStringToArrayBuffer(_) ], {
type: ee
});
}
function b64ToBluffer(_, ee) {
return binStringToBluffer(thisAtob(_), ee);
}
function arrayBufferToBinaryString(_) {
for (var ee = "", ne = new Uint8Array(_), ie = ne.byteLength, re = 0; re < ie; re++) ee += String.fromCharCode(ne[re]);
return ee;
}
function readAsBinaryString(_, ee) {
var ne = new FileReader, ie = "function" == typeof ne.readAsBinaryString;
ne.onloadend = function(_) {
var ne = _.target.result || "";
if (ie) return ee(ne);
ee(arrayBufferToBinaryString(ne));
};
if (ie) ne.readAsBinaryString(_); else ne.readAsArrayBuffer(_);
}
function blobToBinaryString(_, ee) {
readAsBinaryString(_, (function(_) {
ee(_);
}));
}
function blobToBase64(_, ee) {
blobToBinaryString(_, (function(_) {
ee(thisBtoa(_));
}));
}
function readAsArrayBuffer(_, ee) {
var ne = new FileReader;
ne.onloadend = function(_) {
var ne = _.target.result || new ArrayBuffer(0);
ee(ne);
};
ne.readAsArrayBuffer(_);
}
var import_spark_md5 = __toESM(require_spark_md5()), setImmediateShim = self.setImmediate || self.setTimeout, MD5_CHUNK_SIZE = 32768;
function rawToBase64(_) {
return thisBtoa(_);
}
function sliceBlob(_, ee, ne) {
if (_.webkitSlice) return _.webkitSlice(ee, ne); else return _.slice(ee, ne);
}
function appendBlob(_, ee, ne, ie, re) {
if (ne > 0 || ie < ee.size) ee = sliceBlob(ee, ne, ie);
readAsArrayBuffer(ee, (function(ee) {
_.append(ee);
re();
}));
}
function appendString(_, ee, ne, ie, re) {
if (ne > 0 || ie < ee.length) ee = ee.substring(ne, ie);
_.appendBinary(ee);
re();
}
function binaryMd5(_, ee) {
var ne = "string" == typeof _, ie = ne ? _.length : _.size, re = Math.min(MD5_CHUNK_SIZE, ie), se = Math.ceil(ie / re), oe = 0, le = ne ? new import_spark_md5.default : new import_spark_md5.default.ArrayBuffer, ue = ne ? appendString : appendBlob;
function next() {
setImmediateShim(loadNextChunk);
}
function done() {
var _ = rawToBase64(le.end(true));
ee(_);
le.destroy();
}
function loadNextChunk() {
var ee = oe * re, ne = ee + re;
if (++oe < se) ue(le, _, ee, ne, next); else ue(le, _, ee, ne, done);
}
loadNextChunk();
}
function stringMd5(_) {
return import_spark_md5.default.hash(_);
}
function isBinaryObject(_) {
return "undefined" != typeof ArrayBuffer && _ instanceof ArrayBuffer || "undefined" != typeof Blob && _ instanceof Blob;
}
function cloneArrayBuffer(_) {
if ("function" == typeof _.slice) return _.slice(0);
var ee = new ArrayBuffer(_.byteLength), ne = new Uint8Array(ee), ie = new Uint8Array(_);
ne.set(ie);
return ee;
}
function cloneBinaryObject(_) {
if (_ instanceof ArrayBuffer) return cloneArrayBuffer(_);
var ee = _.size, ne = _.type;
if ("function" == typeof _.slice) return _.slice(0, ee, ne); else return _.webkitSlice(0, ee, ne);
}
var funcToString = Function.prototype.toString, objectCtorString = funcToString.call(Object);
function isPlainObject(_) {
var ee = Object.getPrototypeOf(_);
if (null === ee) return true;
var ne = ee.constructor;
return "function" == typeof ne && ne instanceof ne && funcToString.call(ne) == objectCtorString;
}
function clone(_) {
var ee, ne, ie;
if (!_ || "object" != typeof _) return _;
if (Array.isArray(_)) {
ee = [];
for (ne = 0, ie = _.length; ne < ie; ne++) ee[ne] = clone(_[ne]);
return ee;
}
if (_ instanceof Date && isFinite(_)) return _.toISOString();
if (isBinaryObject(_)) return cloneBinaryObject(_);
if (!isPlainObject(_)) return _;
ee = {};
for (ne in _) if (Object.prototype.hasOwnProperty.call(_, ne)) {
var re = clone(_[ne]);
if ("undefined" != typeof re) ee[ne] = re;
}
return ee;
}
function once(_) {
var ee = false;
return function(...ne) {
if (ee) throw new Error("once called more than once"); else {
ee = true;
_.apply(this, ne);
}
};
}
function toPromise(_) {
return function(...ee) {
ee = clone(ee);
var ne = this, ie = "function" == typeof ee[ee.length - 1] ? ee.pop() : false, re = new Promise((function(ie, re) {
var se;
try {
var oe = once((function(_, ee) {
if (_) re(_); else ie(ee);
}));
ee.push(oe);
if ((se = _.apply(ne, ee)) && "function" == typeof se.then) ie(se);
} catch (_) {
re(_);
}
}));
if (ie) re.then((function(_) {
ie(null, _);
}), ie);
return re;
};
}
function logApiCall(_, ee, ne) {
if (_.constructor.listeners("debug").length) {
for (var ie = [ "api", _.name, ee ], re = 0; re < ne.length - 1; re++) ie.push(ne[re]);
_.constructor.emit("debug", ie);
var se = ne[ne.length - 1];
ne[ne.length - 1] = function(ne, ie) {
var re = [ "api", _.name, ee ];
re = re.concat(ne ? [ "error", ne ] : [ "success", ie ]);
_.constructor.emit("debug", re);
se(ne, ie);
};
}
}
function adapterFun(_, ee) {
return toPromise((function(...ne) {
if (this._closed) return Promise.reject(new Error("database is closed"));
if (this._destroyed) return Promise.reject(new Error("database is destroyed"));
var ie = this;
logApiCall(ie, _, ne);
if (!this.taskqueue.isReady) return new Promise((function(ee, re) {
ie.taskqueue.addTask((function(se) {
if (se) re(se); else ee(ie[_].apply(ie, ne));
}));
})); else return ee.apply(this, ne);
}));
}
function pick(_, ee) {
for (var ne = {}, ie = 0, re = ee.length; ie < re; ie++) {
var se = ee[ie];
if (se in _) ne[se] = _[se];
}
return ne;
}
var hasLocal, MAX_NUM_CONCURRENT_REQUESTS = 6;
function identityFunction(_) {
return _;
}
function formatResultForOpenRevsGet(_) {
return [ {
ok: _
} ];
}
function bulkGet(_, ee, ne) {
var ie = ee.docs, re = new ExportedMap;
ie.forEach((function(_) {
if (re.has(_.id)) re.get(_.id).push(_); else re.set(_.id, [ _ ]);
}));
var se = re.size, oe = 0, le = new Array(se), ue = [];
re.forEach((function(_, ee) {
ue.push(ee);
}));
var de = 0;
(function nextBatch() {
if (!(de >= ue.length)) {
var ie = Math.min(de + MAX_NUM_CONCURRENT_REQUESTS, ue.length), fe = ue.slice(de, ie);
(function processBatch(ie, ue) {
ie.forEach((function(ie, de) {
var fe = ue + de, he = re.get(ie), pe = pick(he[0], [ "atts_since", "attachments" ]);
pe.open_revs = he.map((function(_) {
return _.rev;
}));
pe.open_revs = pe.open_revs.filter(identityFunction);
var ge = identityFunction;
if (0 === pe.open_revs.length) {
delete pe.open_revs;
ge = formatResultForOpenRevsGet;
}
[ "revs", "attachments", "binary", "ajax", "latest" ].forEach((function(_) {
if (_ in ee) pe[_] = ee[_];
}));
_.get(ie, pe, (function(_, ee) {
var re;
if (_) re = [ {
error: _
} ]; else re = ge(ee);
(function gotResult(_, ee, ie) {
le[_] = {
id: ee,
docs: ie
};
(function checkDone() {
if (++oe === se) (function collapseResultsAndFinish() {
var _ = [];
le.forEach((function(ee) {
ee.docs.forEach((function(ne) {
_.push({
id: ee.id,
docs: [ ne ]
});
}));
}));
ne(null, {
results: _
});
})();
})();
})(fe, ie, re);
nextBatch();
}));
}));
})(fe, de);
de += fe.length;
}
})();
}
try {
localStorage.setItem("_pouch_check_localstorage", 1);
hasLocal = !!localStorage.getItem("_pouch_check_localstorage");
} catch (_) {
hasLocal = false;
}
function hasLocalStorage() {
return hasLocal;
}
var assign$1, Changes = class extends import_events.default {
constructor() {
super();
this._listeners = {};
if (hasLocalStorage()) addEventListener("storage", (_ => {
this.emit(_.key);
}));
}
addListener(_, ee, ne, ie) {
if (!this._listeners[ee]) {
var re = false, se = this;
this._listeners[ee] = eventFunction;
this.on(_, eventFunction);
}
function eventFunction() {
if (se._listeners[ee]) if (!re) {
re = true;
var _ = pick(ie, [ "style", "include_docs", "attachments", "conflicts", "filter", "doc_ids", "view", "since", "query_params", "binary", "return_docs" ]);
ne.changes(_).on("change", (function(_) {
if (_.seq > ie.since && !ie.cancelled) {
ie.since = _.seq;
ie.onChange(_);
}
})).on("complete", (function() {
if ("waiting" === re) (0, import_immediate.default)(eventFunction);
re = false;
})).on("error", (function onError() {
re = false;
}));
} else re = "waiting";
}
}
removeListener(_, ee) {
if (ee in this._listeners) {
super.removeListener(_, this._listeners[ee]);
delete this._listeners[ee];
}
}
notifyLocalWindows(_) {
if (hasLocalStorage()) localStorage[_] = "a" === localStorage[_] ? "b" : "a";
}
notify(_) {
this.emit(_);
this.notifyLocalWindows(_);
}
};
function guardedConsole(_) {
if ("undefined" != typeof console && "function" == typeof console[_]) {
var ee = Array.prototype.slice.call(arguments, 1);
console[_].apply(console, ee);
}
}
function randomNumber(_, ee) {
var ne = 6e5;
_ = parseInt(_, 10) || 0;
if ((ee = parseInt(ee, 10)) != ee || ee <= _) ee = (_ || 1) << 1; else ee += 1;
if (ee > ne) {
_ = 3e5;
ee = ne;
}
return ~~((ee - _) * Math.random() + _);
}
function defaultBackOff(_) {
var ee = 0;
if (!_) ee = 2e3;
return randomNumber(_, ee);
}
function explainError(_, ee) {
guardedConsole("info", "The above " + _ + " is totally normal. " + ee);
}
if ("function" == typeof Object.assign) assign$1 = Object.assign; else assign$1 = function(_) {
for (var ee = Object(_), ne = 1; ne < arguments.length; ne++) {
var ie = arguments[ne];
if (null != ie) for (var re in ie) if (Object.prototype.hasOwnProperty.call(ie, re)) ee[re] = ie[re];
}
return ee;
};
var assign$2 = assign$1;
function tryFilter(_, ee, ne) {
try {
return !_(ee, ne);
} catch (_) {
var ie = "Filter function threw: " + _.toString();
return createError(BAD_REQUEST, ie);
}
}
function filterChange(_) {
var ee = {}, ne = _.filter && "function" == typeof _.filter;
ee.query = _.query_params;
return function filter3(ie) {
if (!ie.doc) ie.doc = {};
var re = ne && tryFilter(_.filter, ie.doc, ee);
if ("object" == typeof re) return re;
if (re) return false;
if (!_.include_docs) delete ie.doc; else if (!_.attachments) for (var se in ie.doc._attachments) if (Object.prototype.hasOwnProperty.call(ie.doc._attachments, se)) ie.doc._attachments[se].stub = true;
return true;
};
}
function flatten(_) {
for (var ee = [], ne = 0, ie = _.length; ne < ie; ne++) ee = ee.concat(_[ne]);
return ee;
}
function f() {}
var res, hasName = f.name;
if (hasName) res = function(_) {
return _.name;
}; else res = function(_) {
var ee = _.toString().match(/^\s*function\s*(?:(\S+)\s*)?\(/);
if (ee && ee[1]) return ee[1]; else return "";
};
function invalidIdError(_) {
var ee;
if (!_) ee = createError(MISSING_ID); else if ("string" != typeof _) ee = createError(INVALID_ID); else if (/^_/.test(_) && !/^_(design|local)/.test(_)) ee = createError(RESERVED_ID);
if (ee) throw ee;
}
function isRemote(_) {
if ("boolean" == typeof _._remote) return _._remote;
if ("function" == typeof _.type) {
guardedConsole("warn", "db.type() is deprecated and will be removed in a future version of PouchDB");
return "http" === _.type();
}
return false;
}
function listenerCount(_, ee) {
return "listenerCount" in _ ? _.listenerCount(ee) : import_events.default.listenerCount(_, ee);
}
function parseDesignDocFunctionName(_) {
if (!_) return null;
var ee = _.split("/");
if (2 === ee.length) return ee;
if (1 === ee.length) return [ _, _ ]; else return null;
}
function normalizeDesignDocFunctionName(_) {
var ee = parseDesignDocFunctionName(_);
return ee ? ee.join("/") : null;
}
var keys = [ "source", "protocol", "authority", "userInfo", "user", "password", "host", "port", "relative", "path", "directory", "file", "query", "anchor" ], qName = "queryKey", qParser = /(?:^|&)([^&=]*)=?([^&]*)/g, parser = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
function parseUri(_) {
for (var ee = parser.exec(_), ne = {}, ie = 14; ie--; ) {
var re = keys[ie], se = ee[ie] || "", oe = -1 !== [ "user", "password" ].indexOf(re);
ne[re] = oe ? decodeURIComponent(se) : se;
}
ne[qName] = {};
ne[keys[12]].replace(qParser, (function(_, ee, ie) {
if (ee) ne[qName][ee] = ie;
}));
return ne;
}
function scopeEval(_, ee) {
var ne = [], ie = [];
for (var re in ee) if (Object.prototype.hasOwnProperty.call(ee, re)) {
ne.push(re);
ie.push(ee[re]);
}
ne.push(_);
return Function.apply(null, ne).apply(null, ie);
}
function upsert(_, ee, ne) {
return _.get(ee).catch((function(_) {
if (404 !== _.status) throw _;
return {};
})).then((function(ie) {
var re = ie._rev, se = ne(ie);
if (!se) return {
updated: false,
rev: re
};
se._id = ee;
se._rev = re;
return tryAndPut(_, se, ne);
}));
}
function tryAndPut(_, ee, ne) {
return _.put(ee).then((function(_) {
return {
updated: true,
rev: _.rev
};
}), (function(ie) {
if (409 !== ie.status) throw ie;
return upsert(_, ee._id, ne);
}));
}
function rev2(_, ee) {
if (!ee) return v4_default().replace(/-/g, "").toLowerCase();
var ne = assign$2({}, _);
delete ne._rev_tree;
return stringMd5(JSON.stringify(ne));
}
var uuid = v4_default;
function winningRev(_) {
for (var ee, ne, ie, re, se = _.rev_tree.slice(); re = se.pop(); ) {
var oe = re.ids, le = oe[2], ue = re.pos;
if (!le.length) {
var de = !!oe[1].deleted, fe = oe[0];
if (!ee || (ie !== de ? ie : ne !== ue ? ne < ue : ee < fe)) {
ee = fe;
ne = ue;
ie = de;
}
} else for (var he = 0, pe = le.length; he < pe; he++) se.push({
pos: ue + 1,
ids: le[he]
});
}
return ne + "-" + ee;
}
function traverseRevTree(_, ee) {
for (var ne, ie = _.slice(); ne = ie.pop(); ) for (var re = ne.pos, se = ne.ids, oe = se[2], le = ee(0 === oe.length, re, se[0], ne.ctx, se[1]), ue = 0, de = oe.length; ue < de; ue++) ie.push({
pos: re + 1,
ids: oe[ue],
ctx: le
});
}
function sortByPos(_, ee) {
return _.pos - ee.pos;
}
function collectLeaves(_) {
var ee = [];
traverseRevTree(_, (function(_, ne, ie, re, se) {
if (_) ee.push({
rev: ne + "-" + ie,
pos: ne,
opts: se
});
}));
ee.sort(sortByPos).reverse();
for (var ne = 0, ie = ee.length; ne < ie; ne++) delete ee[ne].pos;
return ee;
}
function collectConflicts(_) {
for (var ee = winningRev(_), ne = collectLeaves(_.rev_tree), ie = [], re = 0, se = ne.length; re < se; re++) {
var oe = ne[re];
if (oe.rev !== ee && !oe.opts.deleted) ie.push(oe.rev);
}
return ie;
}
function compactTree(_) {
var ee = [];
traverseRevTree(_.rev_tree, (function(_, ne, ie, re, se) {
if ("available" === se.status && !_) {
ee.push(ne + "-" + ie);
se.status = "missing";
}
}));
return ee;
}
function findPathToLeaf(_, ee) {
let ne = [];
const ie = _.slice();
let re;
for (;re = ie.pop(); ) {
const {pos: _, ids: se} = re, oe = `${_}-${se[0]}`, le = se[2];
ne.push(oe);
if (oe === ee) {
if (0 !== le.length) throw new Error("The requested revision is not a leaf");
return ne.reverse();
}
if (0 === le.length || le.length > 1) ne = [];
for (let ee = 0, ne = le.length; ee < ne; ee++) ie.push({
pos: _ + 1,
ids: le[ee]
});
}
if (0 === ne.length) throw new Error("The requested revision does not exist");
return ne.reverse();
}
function rootToLeaf(_) {
for (var ee, ne = [], ie = _.slice(); ee = ie.pop(); ) {
var re = ee.pos, se = ee.ids, oe = se[0], le = se[1], ue = se[2], de = 0 === ue.length, fe = ee.history ? ee.history.slice() : [];
fe.push({
id: oe,
opts: le
});
if (de) ne.push({
pos: re + 1 - fe.length,
ids: fe
});
for (var he = 0, pe = ue.length; he < pe; he++) ie.push({
pos: re + 1,
ids: ue[he],
history: fe
});
}
return ne.reverse();
}
function sortByPos$1(_, ee) {
return _.pos - ee.pos;
}
function binarySearch(_, ee, ne) {
for (var ie, re = 0, se = _.length; re < se; ) if (ne(_[ie = re + se >>> 1], ee) < 0) re = ie + 1; else se = ie;
return re;
}
function insertSorted(_, ee, ne) {
var ie = binarySearch(_, ee, ne);
_.splice(ie, 0, ee);
}
function pathToTree(_, ee) {
for (var ne, ie, re = ee, se = _.length; re < se; re++) {
var oe = _[re], le = [ oe.id, oe.opts, [] ];
if (ie) {
ie[2].push(le);
ie = le;
} else ne = ie = le;
}
return ne;
}
function compareTree(_, ee) {
return _[0] < ee[0] ? -1 : 1;
}
function mergeTree(_, ee) {
for (var ne = [ {
tree1: _,
tree2: ee
} ], ie = false; ne.length > 0; ) {
var re = ne.pop(), se = re.tree1, oe = re.tree2;
if (se[1].status || oe[1].status) se[1].status = "available" === se[1].status || "available" === oe[1].status ? "available" : "missing";
for (var le = 0; le < oe[2].length; le++) if (se[2][0]) {
for (var ue = false, de = 0; de < se[2].length; de++) if (se[2][de][0] === oe[2][le][0]) {
ne.push({
tree1: se[2][de],
tree2: oe[2][le]
});
ue = true;
}
if (!ue) {
ie = "new_branch";
insertSorted(se[2], oe[2][le], compareTree);
}
} else {
ie = "new_leaf";
se[2][0] = oe[2][le];
}
}
return {
conflicts: ie,
tree: _
};
}
function doMerge(_, ee, ne) {
var ie, re = [], se = false, oe = false;
if (!_.length) return {
tree: [ ee ],
conflicts: "new_leaf"
};
for (var le = 0, ue = _.length; le < ue; le++) {
var de = _[le];
if (de.pos === ee.pos && de.ids[0] === ee.ids[0]) {
ie = mergeTree(de.ids, ee.ids);
re.push({
pos: de.pos,
ids: ie.tree
});
se = se || ie.conflicts;
oe = true;
} else if (true !== ne) {
var fe = de.pos < ee.pos ? de : ee, he = de.pos < ee.pos ? ee : de, pe = he.pos - fe.pos, ge = [], me = [];
me.push({
ids: fe.ids,
diff: pe,
parent: null,
parentIdx: null
});
for (;me.length > 0; ) {
var ye = me.pop();
if (0 !== ye.diff) for (var ve = ye.ids[2], Se = 0, Ee = ve.length; Se < Ee; Se++) me.push({
ids: ve[Se],
diff: ye.diff - 1,
parent: ye.ids,
parentIdx: Se
}); else if (ye.ids[0] === he.ids[0]) ge.push(ye);
}
var Ce = ge[0];
if (!Ce) re.push(de); else {
ie = mergeTree(Ce.ids, he.ids);
Ce.parent[2][Ce.parentIdx] = ie.tree;
re.push({
pos: fe.pos,
ids: fe.ids
});
se = se || ie.conflicts;
oe = true;
}
} else re.push(de);
}
if (!oe) re.push(ee);
re.sort(sortByPos$1);
return {
tree: re,
conflicts: se || "internal_node"
};
}
function stem(_, ee) {
for (var ne, ie, re = rootToLeaf(_), se = 0, oe = re.length; se < oe; se++) {
var le, ue = re[se], de = ue.ids;
if (de.length > ee) {
if (!ne) ne = {};
var fe = de.length - ee;
le = {
pos: ue.pos + fe,
ids: pathToTree(de, fe)
};
for (var he = 0; he < fe; he++) {
var pe = ue.pos + he + "-" + de[he].id;
ne[pe] = true;
}
} else le = {
pos: ue.pos,
ids: pathToTree(de, 0)
};
if (ie) ie = doMerge(ie, le, true).tree; else ie = [ le ];
}
if (ne) traverseRevTree(ie, (function(_, ee, ie) {
delete ne[ee + "-" + ie];
}));
return {
tree: ie,
revs: ne ? Object.keys(ne) : []
};
}
function merge(_, ee, ne) {
var ie = doMerge(_, ee), re = stem(ie.tree, ne);
return {
tree: re.tree,
stemmedRevs: re.revs,
conflicts: ie.conflicts
};
}
function removeLeafFromRevTree(_, ee) {
return _.flatMap((_ => (_ = removeLeafFromPath(_, ee)) ? [ _ ] : []));
}
function removeLeafFromPath(_, ee) {
const ne = clone(_), ie = [ ne ];
let re;
for (;re = ie.pop(); ) {
const {pos: _, ids: [se, , oe], parent: le} = re;
if (0 === oe.length && `${_}-${se}` === ee) {
if (!le) return null;
le.ids[2] = le.ids[2].filter((function(_) {
return _[0] !== se;
}));
return ne;
}
for (let ee = 0, ne = oe.length; ee < ne; ee++) ie.push({
pos: _ + 1,
ids: oe[ee],
parent: re
});
}
return ne;
}
function revExists(_, ee) {
for (var ne, ie = _.slice(), re = ee.split("-"), se = parseInt(re[0], 10), oe = re[1]; ne = ie.pop(); ) {
if (ne.pos === se && ne.ids[0] === oe) return true;
for (var le = ne.ids[2], ue = 0, de = le.length; ue < de; ue++) ie.push({
pos: ne.pos + 1,
ids: le[ue]
});
}
return false;
}
function getTrees(_) {
return _.ids;
}
function isDeleted(_, ee) {
if (!ee) ee = winningRev(_);
for (var ne, ie = ee.substring(ee.indexOf("-") + 1), re = _.rev_tree.map(getTrees); ne = re.pop(); ) {
if (ne[0] === ie) return !!ne[1].deleted;
re = re.concat(ne[2]);
}
}
function isLocalId(_) {
return /^_local/.test(_);
}
function latest(_, ee) {
for (var ne, ie = ee.rev_tree.slice(); ne = ie.pop(); ) {
var re = ne.pos, se = ne.ids, oe = se[0], le = se[1], ue = se[2], de = 0 === ue.length, fe = ne.history ? ne.history.slice() : [];
fe.push({
id: oe,
pos: re,
opts: le
});
if (de) for (var he = 0, pe = fe.length; he < pe; he++) {
var ge = fe[he];
if (ge.pos + "-" + ge.id === _) return re + "-" + oe;
}
for (var me = 0, ye = ue.length; me < ye; me++) ie.push({
pos: re + 1,
ids: ue[me],
history: fe
});
}
throw new Error("Unable to resolve latest revision for id " + ee.id + ", rev " + _);
}
var import_events2 = __toESM(require_events()), a = "undefined" != typeof AbortController ? AbortController : function() {
return {
abort: function() {}
};
}, f2 = fetch, h = Headers;
function pad(_, ee, ne) {
for (var ie = "", re = ne - _.length; ie.length < re; ) ie += ee;
return ie;
}
function padLeft(_, ee, ne) {
return pad(_, ee, ne) + _;
}
var MIN_MAGNITUDE = -324, MAGNITUDE_DIGITS = 3, SEP = "";
function collate(_, ee) {
if (_ === ee) return 0;
_ = normalizeKey(_);
ee = normalizeKey(ee);
var ne = collationIndex(_), ie = collationIndex(ee);
if (ne - ie != 0) return ne - ie;
switch (typeof _) {
case "number":
return _ - ee;
case "boolean":
return _ < ee ? -1 : 1;
case "string":
return stringCollate(_, ee);
}
return Array.isArray(_) ? arrayCollate(_, ee) : objectCollate(_, ee);
}
function normalizeKey(_) {
switch (typeof _) {
case "undefined":
return null;
case "number":
if (_ === 1 / 0 || _ === -1 / 0 || isNaN(_)) return null; else return _;
case "object":
var ee = _;
if (Array.isArray(_)) {
var ne = _.length;
_ = new Array(ne);
for (var ie = 0; ie < ne; ie++) _[ie] = normalizeKey(ee[ie]);
} else if (_ instanceof Date) return _.toJSON(); else if (null !== _) {
_ = {};
for (var re in ee) if (Object.prototype.hasOwnProperty.call(ee, re)) {
var se = ee[re];
if ("undefined" != typeof se) _[re] = normalizeKey(se);
}
}
}
return _;
}
function indexify(_) {
if (null !== _) switch (typeof _) {
case "boolean":
return _ ? 1 : 0;
case "number":
return numToIndexableString(_);
case "string":
return _.replace(/\u0002/g, "").replace(/\u0001/g, "").replace(/\u0000/g, "");
case "object":
var ee = Array.isArray(_), ne = ee ? _ : Object.keys(_), ie = -1, re = ne.length, se = "";
if (ee) for (;++ie < re; ) se += toIndexableString(ne[ie]); else for (;++ie < re; ) {
var oe = ne[ie];
se += toIndexableString(oe) + toIndexableString(_[oe]);
}
return se;
}
return "";
}
function toIndexableString(_) {
return collationIndex(_ = normalizeKey(_)) + SEP + indexify(_) + "\0";
}
function parseNumber(_, ee) {
var ne, ie = ee;
if ("1" === _[ee]) {
ne = 0;
ee++;
} else {
var re = "0" === _[ee];
ee++;
var se = "", oe = _.substring(ee, ee + MAGNITUDE_DIGITS), le = parseInt(oe, 10) + MIN_MAGNITUDE;
if (re) le = -le;
ee += MAGNITUDE_DIGITS;
for (;;) {
var ue = _[ee];
if ("\0" === ue) break; else se += ue;
ee++;
}
if (1 === (se = se.split(".")).length) ne = parseInt(se, 10); else ne = parseFloat(se[0] + "." + se[1]);
if (re) ne -= 10;
if (0 !== le) ne = parseFloat(ne + "e" + le);
}
return {
num: ne,
length: ee - ie
};
}
function pop(_, ee) {
var ne = _.pop();
if (ee.length) {
var ie = ee[ee.length - 1];
if (ne === ie.element) {
ee.pop();
ie = ee[ee.length - 1];
}
var re = ie.element, se = ie.index;
if (Array.isArray(re)) re.push(ne); else if (se === _.length - 2) re[_.pop()] = ne; else _.push(ne);
}
}
function parseIndexableString(_) {
for (var ee = [], ne = [], ie = 0; ;) {
var re = _[ie++];
if ("\0" === re) if (1 === ee.length) return ee.pop(); else {
pop(ee, ne);
continue;
}
switch (re) {
case "1":
ee.push(null);
break;
case "2":
ee.push("1" === _[ie]);
ie++;
break;
case "3":
var se = parseNumber(_, ie);
ee.push(se.num);
ie += se.length;
break;
case "4":
for (var oe = ""; ;) {
var le = _[ie];
if ("\0" === le) break;
oe += le;
ie++;
}
oe = oe.replace(/\u0001\u0001/g, "\0").replace(/\u0001\u0002/g, "").replace(/\u0002\u0002/g, "");
ee.push(oe);
break;
case "5":
var ue = {
element: [],
index: ee.length
};
ee.push(ue.element);
ne.push(ue);
break;
case "6":
var de = {
element: {},
index: ee.length
};
ee.push(de.element);
ne.push(de);
break;
default:
throw new Error("bad collationIndex or unexpectedly reached end of input: " + re);
}
}
}
function arrayCollate(_, ee) {
for (var ne = Math.min(_.length, ee.length), ie = 0; ie < ne; ie++) {
var re = collate(_[ie], ee[ie]);
if (0 !== re) return re;
}
return _.length === ee.length ? 0 : _.length > ee.length ? 1 : -1;
}
function stringCollate(_, ee) {
return _ === ee ? 0 : _ > ee ? 1 : -1;
}
function objectCollate(_, ee) {
for (var ne = Object.keys(_), ie = Object.keys(ee), re = Math.min(ne.length, ie.length), se = 0; se < re; se++) {
var oe = collate(ne[se], ie[se]);
if (0 !== oe) return oe;
if (0 !== (oe = collate(_[ne[se]], ee[ie[se]]))) return oe;
}
return ne.length === ie.length ? 0 : ne.length > ie.length ? 1 : -1;
}
function collationIndex(_) {
var ee = [ "boolean", "number", "string", "object" ].indexOf(typeof _);
if (~ee) {
if (null === _) return 1;
if (Array.isArray(_)) return 5; else return ee < 3 ? ee + 2 : ee + 3;
}
if (Array.isArray(_)) return 5;
}
function numToIndexableString(_) {
if (0 === _) return "1";
var ee = _.toExponential().split(/e\+?/), ne = parseInt(ee[1], 10), ie = _ < 0, re = ie ? "0" : "2", se = padLeft(((ie ? -ne : ne) - MIN_MAGNITUDE).toString(), "0", MAGNITUDE_DIGITS);
re += SEP + se;
var oe = Math.abs(parseFloat(ee[0]));
if (ie) oe = 10 - oe;
var le = oe.toFixed(20);
le = le.replace(/\.?0+$/, "");
return re += SEP + le;
}
function getFieldFromDoc(_, ee) {
for (var ne = _, ie = 0, re = ee.length; ie < re && (ne = ne[ee[ie]]); ie++) ;
return ne;
}
function setFieldInDoc(_, ee, ne) {
for (var ie = 0, re = ee.length; ie < re - 1; ie++) {
var se = ee[ie];
_ = _[se] = _[se] || {};
}
_[ee[re - 1]] = ne;
}
function compare(_, ee) {
return _ < ee ? -1 : _ > ee ? 1 : 0;
}
function parseField(_) {
for (var ee = [], ne = "", ie = 0, re = _.length; ie < re; ie++) {
var se = _[ie];
if (ie > 0 && "\\" === _[ie - 1] && ("$" === se || "." === se)) ne = ne.substring(0, ne.length - 1) + se; else if ("." === se) {
ee.push(ne);
ne = "";
} else ne += se;
}
ee.push(ne);
return ee;
}
var combinationFields = [ "$or", "$nor", "$not" ];
function isCombinationalField(_) {
return combinationFields.indexOf(_) > -1;
}
function getKey(_) {
return Object.keys(_)[0];
}
function getValue(_) {
return _[getKey(_)];
}
function mergeAndedSelectors(_) {
var ee = {}, ne = {
$or: true,
$nor: true
};
_.forEach((function(_) {
Object.keys(_).forEach((function(ie) {
var re = _[ie];
if ("object" != typeof re) re = {
$eq: re
};
if (isCombinationalField(ie)) if (re instanceof Array) {
if (ne[ie]) {
ne[ie] = false;
ee[ie] = re;
return;
}
var se = [];
ee[ie].forEach((function(_) {
Object.keys(re).forEach((function(ee) {
var ne = re[ee], ie = Math.max(Object.keys(_).length, Object.keys(ne).length), oe = mergeAndedSelectors([ _, ne ]);
if (!(Object.keys(oe).length <= ie)) se.push(oe);
}));
}));
ee[ie] = se;
} else ee[ie] = mergeAndedSelectors([ re ]); else {
var oe = ee[ie] = ee[ie] || {};
Object.keys(re).forEach((function(_) {
var ee = re[_];
if ("$gt" === _ || "$gte" === _) return mergeGtGte(_, ee, oe); else if ("$lt" === _ || "$lte" === _) return mergeLtLte(_, ee, oe); else if ("$ne" === _) return mergeNe(ee, oe); else if ("$eq" === _) return mergeEq(ee, oe); else if ("$regex" === _) return mergeRegex(ee, oe);
oe[_] = ee;
}));
}
}));
}));
return ee;
}
function mergeGtGte(_, ee, ne) {
if ("undefined" == typeof ne.$eq) if ("undefined" != typeof ne.$gte) {
if ("$gte" === _) {
if (ee > ne.$gte) ne.$gte = ee;
} else if (ee >= ne.$gte) {
delete ne.$gte;
ne.$gt = ee;
}
} else if ("undefined" != typeof ne.$gt) {
if ("$gte" === _) {
if (ee > ne.$gt) {
delete ne.$gt;
ne.$gte = ee;
}
} else if (ee > ne.$gt) ne.$gt = ee;
} else ne[_] = ee;
}
function mergeLtLte(_, ee, ne) {
if ("undefined" == typeof ne.$eq) if ("undefined" != typeof ne.$lte) {
if ("$lte" === _) {
if (ee < ne.$lte) ne.$lte = ee;
} else if (ee <= ne.$lte) {
delete ne.$lte;
ne.$lt = ee;
}
} else if ("undefined" != typeof ne.$lt) {
if ("$lte" === _) {
if (ee < ne.$lt) {
delete ne.$lt;
ne.$lte = ee;
}
} else if (ee < ne.$lt) ne.$lt = ee;
} else ne[_] = ee;
}
function mergeNe(_, ee) {
if ("$ne" in ee) ee.$ne.push(_); else ee.$ne = [ _ ];
}
function mergeEq(_, ee) {
delete ee.$gt;
delete ee.$gte;
delete ee.$lt;
delete ee.$lte;
delete ee.$ne;
ee.$eq = _;
}
function mergeRegex(_, ee) {
if ("$regex" in ee) ee.$regex.push(_); else ee.$regex = [ _ ];
}
function mergeAndedSelectorsNested(_) {
for (var ee in _) {
if (Array.isArray(_)) for (var ne in _) if (_[ne]["$and"]) _[ne] = mergeAndedSelectors(_[ne]["$and"]);
var ie = _[ee];
if ("object" == typeof ie) mergeAndedSelectorsNested(ie);
}
return _;
}
function isAndInSelector(_, ee) {
for (var ne in _) {
if ("$and" === ne) ee = true;
var ie = _[ne];
if ("object" == typeof ie) ee = isAndInSelector(ie, ee);
}
return ee;
}
function massageSelector(_) {
var ee = clone(_);
if (isAndInSelector(ee, false)) if ("$and" in (ee = mergeAndedSelectorsNested(ee))) ee = mergeAndedSelectors(ee["$and"]);
[ "$or", "$nor" ].forEach((function(_) {
if (_ in ee) ee[_].forEach((function(_) {
for (var ee = Object.keys(_), ne = 0; ne < ee.length; ne++) {
var ie = ee[ne], re = _[ie];
if ("object" != typeof re || null === re) _[ie] = {
$eq: re
};
}
}));
}));
if ("$not" in ee) ee["$not"] = mergeAndedSelectors([ ee["$not"] ]);
for (var ne = Object.keys(ee), ie = 0; ie < ne.length; ie++) {
var re = ne[ie], se = ee[re];
if ("object" != typeof se || null === se) se = {
$eq: se
};
ee[re] = se;
}
normalizeArrayOperators(ee);
return ee;
}
function normalizeArrayOperators(_) {
Object.keys(_).forEach((function(ee) {
var ne = _[ee];
if (Array.isArray(ne)) ne.forEach((function(_) {
if (_ && "object" == typeof _) normalizeArrayOperators(_);
})); else if ("$ne" === ee) _.$ne = [ ne ]; else if ("$regex" === ee) _.$regex = [ ne ]; else if (ne && "object" == typeof ne) normalizeArrayOperators(ne);
}));
}
function createFieldSorter(_) {
function getFieldValuesAsArray(ee) {
return _.map((function(_) {
var ne = parseField(getKey(_));
return getFieldFromDoc(ee, ne);
}));
}
return function(_, ee) {
var ne = collate(getFieldValuesAsArray(_.doc), getFieldValuesAsArray(ee.doc));
if (0 !== ne) return ne; else return compare(_.doc._id, ee.doc._id);
};
}
function filterInMemoryFields(_, ee, ne) {
_ = _.filter((function(_) {
return rowFilter(_.doc, ee.selector, ne);
}));
if (ee.sort) {
var ie = createFieldSorter(ee.sort);
_ = _.sort(ie);
if ("string" != typeof ee.sort[0] && "desc" === getValue(ee.sort[0])) _ = _.reverse();
}
if ("limit" in ee || "skip" in ee) {
var re = ee.skip || 0, se = ("limit" in ee ? ee.limit : _.length) + re;
_ = _.slice(re, se);
}
return _;
}
function rowFilter(_, ee, ne) {
return ne.every((function(ne) {
var ie = ee[ne], re = parseField(ne), se = getFieldFromDoc(_, re);
if (isCombinationalField(ne)) return matchCominationalSelector(ne, ie, _); else return matchSelector(ie, _, re, se);
}));
}
function matchSelector(_, ee, ne, ie) {
if (!_) return true;
if ("object" == typeof _) return Object.keys(_).every((function(re) {
var se = _[re];
if (0 === re.indexOf("$")) return match2(re, ee, se, ne, ie); else {
var oe = parseField(re);
if (void 0 === ie && "object" != typeof se && oe.length > 0) return false;
var le = getFieldFromDoc(ie, oe);
if ("object" == typeof se) return matchSelector(se, ee, ne, le); else return match2("$eq", ee, se, oe, le);
}
})); else return _ === ie;
}
function matchCominationalSelector(_, ee, ne) {
if ("$or" === _) return ee.some((function(_) {
return rowFilter(ne, _, Object.keys(_));
}));
if ("$not" === _) return !rowFilter(ne, ee, Object.keys(ee)); else return !ee.find((function(_) {
return rowFilter(ne, _, Object.keys(_));
}));
}
function match2(_, ee, ne, ie, re) {
if (!matchers[_]) throw new Error('unknown operator "' + _ + '" - should be one of $eq, $lte, $lt, $gt, $gte, $exists, $ne, $in, $nin, $size, $mod, $regex, $elemMatch, $type, $allMatch or $all');
return matchers[_](ee, ne, ie, re);
}
function fieldExists(_) {
return "undefined" != typeof _ && null !== _;
}
function fieldIsNotUndefined(_) {
return "undefined" != typeof _;
}
function modField(_, ee) {
if ("number" != typeof _ || parseInt(_, 10) !== _) return false; else return _ % ee[0] === ee[1];
}
function arrayContainsValue(_, ee) {
return ee.some((function(ee) {
if (_ instanceof Array) return _.some((function(_) {
return 0 === collate(ee, _);
})); else return 0 === collate(ee, _);
}));
}
function arrayContainsAllValues(_, ee) {
return ee.every((function(ee) {
return _.some((function(_) {
return 0 === collate(ee, _);
}));
}));
}
function arraySize(_, ee) {
return _.length === ee;
}
function regexMatch(_, ee) {
return new RegExp(ee).test(_);
}
function typeMatch(_, ee) {
switch (ee) {
case "null":
return null === _;
case "boolean":
return "boolean" == typeof _;
case "number":
return "number" == typeof _;
case "string":
return "string" == typeof _;
case "array":
return _ instanceof Array;
case "object":
return "[object Object]" === {}.toString.call(_);
}
}
var matchers = {
$elemMatch: function(_, ee, ne, ie) {
if (!Array.isArray(ie)) return false;
if (0 === ie.length) return false;
if ("object" == typeof ie[0] && null !== ie[0]) return ie.some((function(_) {
return rowFilter(_, ee, Object.keys(ee));
})); else return ie.some((function(ie) {
return matchSelector(ee, _, ne, ie);
}));
},
$allMatch: function(_, ee, ne, ie) {
if (!Array.isArray(ie)) return false;
if (0 === ie.length) return false;
if ("object" == typeof ie[0] && null !== ie[0]) return ie.every((function(_) {
return rowFilter(_, ee, Object.keys(ee));
})); else return ie.every((function(ie) {
return matchSelector(ee, _, ne, ie);
}));
},
$eq: function(_, ee, ne, ie) {
return fieldIsNotUndefined(ie) && 0 === collate(ie, ee);
},
$gte: function(_, ee, ne, ie) {
return fieldIsNotUndefined(ie) && collate(ie, ee) >= 0;
},
$gt: function(_, ee, ne, ie) {
return fieldIsNotUndefined(ie) && collate(ie, ee) > 0;
},
$lte: function(_, ee, ne, ie) {
return fieldIsNotUndefined(ie) && collate(ie, ee) <= 0;
},
$lt: function(_, ee, ne, ie) {
return fieldIsNotUndefined(ie) && collate(ie, ee) < 0;
},
$exists: function(_, ee, ne, ie) {
if (ee) return fieldIsNotUndefined(ie); else return !fieldIsNotUndefined(ie);
},
$mod: function(_, ee, ne, ie) {
return fieldExists(ie) && modField(ie, ee);
},
$ne: function(_, ee, ne, ie) {
return ee.every((function(_) {
return 0 !== collate(ie, _);
}));
},
$in: function(_, ee, ne, ie) {
return fieldExists(ie) && arrayContainsValue(ie, ee);
},
$nin: function(_, ee, ne, ie) {
return fieldExists(ie) && !arrayContainsValue(ie, ee);
},
$size: function(_, ee, ne, ie) {
return fieldExists(ie) && Array.isArray(ie) && arraySize(ie, ee);
},
$all: function(_, ee, ne, ie) {
return Array.isArray(ie) && arrayContainsAllValues(ie, ee);
},
$regex: function(_, ee, ne, ie) {
return fieldExists(ie) && "string" == typeof ie && ee.every((function(_) {
return regexMatch(ie, _);
}));
},
$type: function(_, ee, ne, ie) {
return typeMatch(ie, ee);
}
};
function matchesSelector(_, ee) {
if ("object" != typeof ee) throw new Error("Selector error: expected a JSON object");
var ne = filterInMemoryFields([ {
doc: _
} ], {
selector: ee = massageSelector(ee)
}, Object.keys(ee));
return ne && 1 === ne.length;
}
function evalFilter(_) {
return scopeEval('"use strict";\nreturn ' + _ + ";", {});
}
function evalView(_) {
return scopeEval([ "return function(doc) {", ' "use strict";', " var emitted = false;", " var emit = function (a, b) {", " emitted = true;", " };", " var view = " + _ + ";", " view(doc);", " if (emitted) {", " return true;", " }", "};" ].join("\n"), {});
}
function validate2(_, ee) {
if (_.selector) if (_.filter && "_selector" !== _.filter) {
var ne = "string" == typeof _.filter ? _.filter : "function";
return ee(new Error('selector invalid for filter "' + ne + '"'));
}
ee();
}
function normalize(_) {
if (_.view && !_.filter) _.filter = "_view";
if (_.selector && !_.filter) _.filter = "_selector";
if (_.filter && "string" == typeof _.filter) if ("_view" === _.filter) _.view = normalizeDesignDocFunctionName(_.view); else _.filter = normalizeDesignDocFunctionName(_.filter);
}
function shouldFilter(_, ee) {
return ee.filter && "string" == typeof ee.filter && !ee.doc_ids && !isRemote(_.db);
}
function filter2(_, ee) {
var ne = ee.complete;
if ("_view" === ee.filter) {
if (!ee.view || "string" != typeof ee.view) {
var ie = createError(BAD_REQUEST, "`view` filter parameter not found or invalid.");
return ne(ie);
}
var re = parseDesignDocFunctionName(ee.view);
_.db.get("_design/" + re[0], (function(ie, se) {
if (_.isCancelled) return ne(null, {
status: "cancelled"
});
if (ie) return ne(generateErrorFromResponse(ie));
var oe = se && se.views && se.views[re[1]] && se.views[re[1]].map;
if (!oe) return ne(createError(MISSING_DOC, se.views ? "missing json key: " + re[1] : "missing json key: views"));
ee.filter = evalView(oe);
_.doChanges(ee);
}));
} else if (ee.selector) {
ee.filter = function(_) {
return matchesSelector(_, ee.selector);
};
_.doChanges(ee);
} else {
var se = parseDesignDocFunctionName(ee.filter);
_.db.get("_design/" + se[0], (function(ie, re) {
if (_.isCancelled) return ne(null, {
status: "cancelled"
});
if (ie) return ne(generateErrorFromResponse(ie));
var oe = re && re.filters && re.filters[se[1]];
if (!oe) return ne(createError(MISSING_DOC, re && re.filters ? "missing json key: " + se[1] : "missing json key: filters"));
ee.filter = evalFilter(oe);
_.doChanges(ee);
}));
}
}
function applyChangesFilterPlugin(_) {
_._changesFilterPlugin = {
validate: validate2,
normalize,
shouldFilter,
filter: filter2
};
}
var index_browser_es_default = applyChangesFilterPlugin;
function tryCatchInChangeListener(_, ee, ne, ie) {
try {
_.emit("change", ee, ne, ie);
} catch (_) {
guardedConsole("error", 'Error in .on("change", function):', _);
}
}
function processChange(_, ee, ne) {
var ie = [ {
rev: _._rev
} ];
if ("all_docs" === ne.style) ie = collectLeaves(ee.rev_tree).map((function(_) {
return {
rev: _.rev
};
}));
var re = {
id: ee.id,
changes: ie,
doc: _
};
if (isDeleted(ee, _._rev)) re.deleted = true;
if (ne.conflicts) {
re.doc._conflicts = collectConflicts(ee);
if (!re.doc._conflicts.length) delete re.doc._conflicts;
}
return re;
}
var Changes2 = class extends import_events2.default {
constructor(_, ee, ne) {
super();
this.db = _;
var ie = (ee = ee ? clone(ee) : {}).complete = once(((ee, ne) => {
if (ee) {
if (listenerCount(this, "error") > 0) this.emit("error", ee);
} else this.emit("complete", ne);
this.removeAllListeners();
_.removeListener("destroyed", onDestroy2);
}));
if (ne) {
this.on("complete", (function(_) {
ne(null, _);
}));
this.on("error", ne);
}
const onDestroy2 = () => {
this.cancel();
};
_.once("destroyed", onDestroy2);
ee.onChange = (_, ee, ne) => {
if (!this.isCancelled) tryCatchInChangeListener(this, _, ee, ne);
};
var re = new Promise((function(_, ne) {
ee.complete = function(ee, ie) {
if (ee) ne(ee); else _(ie);
};
}));
this.once("cancel", (function() {
_.removeListener("destroyed", onDestroy2);
ee.complete(null, {
status: "cancelled"
});
}));
this.then = re.then.bind(re);
this["catch"] = re["catch"].bind(re);
this.then((function(_) {
ie(null, _);
}), ie);
if (!_.taskqueue.isReady) _.taskqueue.addTask((_ => {
if (_) ee.complete(_); else if (this.isCancelled) this.emit("cancel"); else this.validateChanges(ee);
})); else this.validateChanges(ee);
}
cancel() {
this.isCancelled = true;
if (this.db.taskqueue.isReady) this.emit("cancel");
}
validateChanges(_) {
var ee = _.complete;
if (PouchDB._changesFilterPlugin) PouchDB._changesFilterPlugin.validate(_, (ne => {
if (ne) return ee(ne);
this.doChanges(_);
})); else this.doChanges(_);
}
doChanges(_) {
var ee = _.complete;
if ("live" in (_ = clone(_)) && !("continuous" in _)) _.continuous = _.live;
_.processChange = processChange;
if ("latest" === _.since) _.since = "now";
if (!_.since) _.since = 0;
if ("now" !== _.since) {
if (PouchDB._changesFilterPlugin) {
PouchDB._changesFilterPlugin.normalize(_);
if (PouchDB._changesFilterPlugin.shouldFilter(this, _)) return PouchDB._changesFilterPlugin.filter(this, _);
} else [ "doc_ids", "filter", "selector", "view" ].forEach((function(ee) {
if (ee in _) guardedConsole("warn", 'The "' + ee + '" option was passed in to changes/replicate, but pouchdb-changes-filter plugin is not installed, so it was ignored. Please install the plugin to enable filtering.');
}));
if (!("descending" in _)) _.descending = false;
_.limit = 0 === _.limit ? 1 : _.limit;
_.complete = ee;
var ne = this.db._changes(_);
if (ne && "function" == typeof ne.cancel) {
const _ = this.cancel;
this.cancel = (...ee) => {
ne.cancel();
_.apply(this, ee);
};
}
} else this.db.info().then((ne => {
if (!this.isCancelled) {
_.since = ne.update_seq;
this.doChanges(_);
} else ee(null, {
status: "cancelled"
});
}), ee);
}
};
function compare2(_, ee) {
return _ < ee ? -1 : _ > ee ? 1 : 0;
}
function yankError(_, ee) {
return function(ne, ie) {
if (ne || ie[0] && ie[0].error) {
(ne = ne || ie[0]).docId = ee;
_(ne);
} else _(null, ie.length ? ie[0] : ie);
};
}
function cleanDocs(_) {
for (var ee = 0; ee < _.length; ee++) {
var ne = _[ee];
if (ne._deleted) delete ne._attachments; else if (ne._attachments) for (var ie = Object.keys(ne._attachments), re = 0; re < ie.length; re++) {
var se = ie[re];
ne._attachments[se] = pick(ne._attachments[se], [ "data", "digest", "content_type", "length", "revpos", "stub" ]);
}
}
}
function compareByIdThenRev(_, ee) {
var ne = compare2(_._id, ee._id);
if (0 !== ne) return ne; else return compare2(_._revisions ? _._revisions.start : 0, ee._revisions ? ee._revisions.start : 0);
}
function computeHeight(_) {
var ee = {}, ne = [];
traverseRevTree(_, (function(_, ie, re, se) {
var oe = ie + "-" + re;
if (_) ee[oe] = 0;
if (void 0 !== se) ne.push({
from: se,
to: oe
});
return oe;
}));
ne.reverse();
ne.forEach((function(_) {
if (void 0 === ee[_.from]) ee[_.from] = 1 + ee[_.to]; else ee[_.from] = Math.min(ee[_.from], 1 + ee[_.to]);
}));
return ee;
}
function allDocsKeysParse(_) {
var ee = "limit" in _ ? _.keys.slice(_.skip, _.limit + _.skip) : _.skip > 0 ? _.keys.slice(_.skip) : _.keys;
_.keys = ee;
_.skip = 0;
delete _.limit;
if (_.descending) {
ee.reverse();
_.descending = false;
}
}
function doNextCompaction(_) {
var ee = _._compactionQueue[0], ne = ee.opts, ie = ee.callback;
_.get("_local/compaction").catch((function() {
return false;
})).then((function(ee) {
if (ee && ee.last_seq) ne.last_seq = ee.last_seq;
_._compact(ne, (function(ee, ne) {
if (ee) ie(ee); else ie(null, ne);
(0, import_immediate.default)((function() {
_._compactionQueue.shift();
if (_._compactionQueue.length) doNextCompaction(_);
}));
}));
}));
}
function appendPurgeSeq(_, ee, ne) {
return _.get("_local/purges").then((function(_) {
const ie = _.purgeSeq + 1;
_.purges.push({
docId: ee,
rev: ne,
purgeSeq: ie
});
if (_.purges.length > self.purged_infos_limit) _.purges.splice(0, _.purges.length - self.purged_infos_limit);
_.purgeSeq = ie;
return _;
})).catch((function(_) {
if (404 !== _.status) throw _;
return {
_id: "_local/purges",
purges: [ {
docId: ee,
rev: ne,
purgeSeq: 0
} ],
purgeSeq: 0
};
})).then((function(ee) {
return _.put(ee);
}));
}
function attachmentNameError(_) {
if ("_" === _.charAt(0)) return _ + " is not a valid attachment name, attachment names cannot start with '_'"; else return false;
}
var AbstractPouchDB = class extends import_events2.default {
_setup() {
this.post = adapterFun("post", (function(_, ee, ne) {
if ("function" == typeof ee) {
ne = ee;
ee = {};
}
if ("object" != typeof _ || Array.isArray(_)) return ne(createError(NOT_AN_OBJECT));
this.bulkDocs({
docs: [ _ ]
}, ee, yankError(ne, _._id));
})).bind(this);
this.put = adapterFun("put", (function(_, ee, ne) {
if ("function" == typeof ee) {
ne = ee;
ee = {};
}
if ("object" != typeof _ || Array.isArray(_)) return ne(createError(NOT_AN_OBJECT));
invalidIdError(_._id);
if (isLocalId(_._id) && "function" == typeof this._putLocal) if (_._deleted) return this._removeLocal(_, ne); else return this._putLocal(_, ne);
const putDoc = ne => {
if ("function" == typeof this._put && false !== ee.new_edits) this._put(_, ee, ne); else this.bulkDocs({
docs: [ _ ]
}, ee, yankError(ne, _._id));
};
if (ee.force && _._rev) {
(function transformForceOptionToNewEditsOption() {
var ne = _._rev.split("-"), ie = ne[1], re = parseInt(ne[0], 10) + 1, se = rev2();
_._revisions = {
start: re,
ids: [ se, ie ]
};
_._rev = re + "-" + se;
ee.new_edits = false;
})();
putDoc((function(ee) {
var ie = ee ? null : {
ok: true,
id: _._id,
rev: _._rev
};
ne(ee, ie);
}));
} else putDoc(ne);
})).bind(this);
this.putAttachment = adapterFun("putAttachment", (function(_, ee, ne, ie, re) {
var se = this;
if ("function" == typeof re) {
re = ie;
ie = ne;
ne = null;
}
if ("undefined" == typeof re) {
re = ie;
ie = ne;
ne = null;
}
if (!re) guardedConsole("warn", "Attachment", ee, "on document", _, "is missing content_type");
function createAttachment(_) {
var ne = "_rev" in _ ? parseInt(_._rev, 10) : 0;
_._attachments = _._attachments || {};
_._attachments[ee] = {
content_type: re,
data: ie,
revpos: ++ne
};
return se.put(_);
}
return se.get(_).then((function(_) {
if (_._rev !== ne) throw createError(REV_CONFLICT);
return createAttachment(_);
}), (function(ee) {
if (ee.reason === MISSING_DOC.message) return createAttachment({
_id: _
}); else throw ee;
}));
})).bind(this);
this.removeAttachment = adapterFun("removeAttachment", (function(_, ee, ne, ie) {
this.get(_, ((_, re) => {
if (!_) if (re._rev === ne) {
if (!re._attachments) return ie();
delete re._attachments[ee];
if (0 === Object.keys(re._attachments).length) delete re._attachments;
this.put(re, ie);
} else ie(createError(REV_CONFLICT)); else ie(_);
}));
})).bind(this);
this.remove = adapterFun("remove", (function(_, ee, ne, ie) {
var re;
if ("string" == typeof ee) {
re = {
_id: _,
_rev: ee
};
if ("function" == typeof ne) {
ie = ne;
ne = {};
}
} else {
re = _;
if ("function" == typeof ee) {
ie = ee;
ne = {};
} else {
ie = ne;
ne = ee;
}
}
(ne = ne || {}).was_delete = true;
var se = {
_id: re._id,
_rev: re._rev || ne.rev,
_deleted: true
};
if (isLocalId(se._id) && "function" == typeof this._removeLocal) return this._removeLocal(re, ie);
this.bulkDocs({
docs: [ se ]
}, ne, yankError(ie, se._id));
})).bind(this);
this.revsDiff = adapterFun("revsDiff", (function(_, ee, ne) {
if ("function" == typeof ee) {
ne = ee;
ee = {};
}
var ie = Object.keys(_);
if (!ie.length) return ne(null, {});
var re = 0, se = new ExportedMap;
function addToMissing(_, ee) {
if (!se.has(_)) se.set(_, {
missing: []
});
se.get(_).missing.push(ee);
}
ie.map((function(ee) {
this._getRevisionTree(ee, (function(oe, le) {
if (oe && 404 === oe.status && "missing" === oe.message) se.set(ee, {
missing: _[ee]
}); else if (oe) return ne(oe); else (function processDoc(ee, ne) {
var ie = _[ee].slice(0);
traverseRevTree(ne, (function(_, ne, re, se, oe) {
var le = ne + "-" + re, ue = ie.indexOf(le);
if (-1 !== ue) {
ie.splice(ue, 1);
if ("available" !== oe.status) addToMissing(ee, le);
}
}));
ie.forEach((function(_) {
addToMissing(ee, _);
}));
})(ee, le);
if (++re === ie.length) {
var ue = {};
se.forEach((function(_, ee) {
ue[ee] = _;
}));
return ne(null, ue);
}
}));
}), this);
})).bind(this);
this.bulkGet = adapterFun("bulkGet", (function(_, ee) {
bulkGet(this, _, ee);
})).bind(this);
this.compactDocument = adapterFun("compactDocument", (function(_, ee, ne) {
this._getRevisionTree(_, ((ie, re) => {
if (ie) return ne(ie);
var se = computeHeight(re), oe = [], le = [];
Object.keys(se).forEach((function(_) {
if (se[_] > ee) oe.push(_);
}));
traverseRevTree(re, (function(_, ee, ne, ie, re) {
var se = ee + "-" + ne;
if ("available" === re.status && -1 !== oe.indexOf(se)) le.push(se);
}));
this._doCompaction(_, le, ne);
}));
})).bind(this);
this.compact = adapterFun("compact", (function(_, ee) {
if ("function" == typeof _) {
ee = _;
_ = {};
}
_ = _ || {};
this._compactionQueue = this._compactionQueue || [];
this._compactionQueue.push({
opts: _,
callback: ee
});
if (1 === this._compactionQueue.length) doNextCompaction(this);
})).bind(this);
this.get = adapterFun("get", (function(_, ee, ne) {
if ("function" == typeof ee) {
ne = ee;
ee = {};
}
if ("string" != typeof _) return ne(createError(INVALID_ID));
if (isLocalId(_) && "function" == typeof this._getLocal) return this._getLocal(_, ne);
var ie = [];
const finishOpenRevs = () => {
var re = [], se = ie.length;
if (!se) return ne(null, re);
ie.forEach((ie => {
this.get(_, {
rev: ie,
revs: ee.revs,
latest: ee.latest,
attachments: ee.attachments,
binary: ee.binary
}, (function(_, ee) {
if (!_) {
for (var oe, le = 0, ue = re.length; le < ue; le++) if (re[le].ok && re[le].ok._rev === ee._rev) {
oe = true;
break;
}
if (!oe) re.push({
ok: ee
});
} else re.push({
missing: ie
});
if (! --se) ne(null, re);
}));
}));
};
if (!ee.open_revs) return this._get(_, ee, ((ie, re) => {
if (ie) {
ie.docId = _;
return ne(ie);
}
var se = re.doc, oe = re.metadata, le = re.ctx;
if (ee.conflicts) {
var ue = collectConflicts(oe);
if (ue.length) se._conflicts = ue;
}
if (isDeleted(oe, se._rev)) se._deleted = true;
if (ee.revs || ee.revs_info) {
for (var de = se._rev.split("-"), fe = parseInt(de[0], 10), he = de[1], pe = rootToLeaf(oe.rev_tree), ge = null, me = 0; me < pe.length; me++) {
var ye = pe[me], ve = ye.ids.map((function(_) {
return _.id;
})).indexOf(he);
if (ve === fe - 1 || !ge && -1 !== ve) ge = ye;
}
if (!ge) {
(ie = new Error("invalid rev tree")).docId = _;
return ne(ie);
}
var Se = ge.ids.map((function(_) {
return _.id;
})).indexOf(se._rev.split("-")[1]) + 1, Ee = ge.ids.length - Se;
ge.ids.splice(Se, Ee);
ge.ids.reverse();
if (ee.revs) se._revisions = {
start: ge.pos + ge.ids.length - 1,
ids: ge.ids.map((function(_) {
return _.id;
}))
};
if (ee.revs_info) {
var Ce = ge.pos + ge.ids.length;
se._revs_info = ge.ids.map((function(_) {
return {
rev: --Ce + "-" + _.id,
status: _.opts.status
};
}));
}
}
if (ee.attachments && se._attachments) {
var we = se._attachments, Oe = Object.keys(we).length;
if (0 === Oe) return ne(null, se);
Object.keys(we).forEach((_ => {
this._getAttachment(se._id, _, we[_], {
rev: se._rev,
binary: ee.binary,
ctx: le
}, (function(ee, ie) {
var re = se._attachments[_];
re.data = ie;
delete re.stub;
delete re.length;
if (! --Oe) ne(null, se);
}));
}));
} else {
if (se._attachments) for (var ke in se._attachments) if (Object.prototype.hasOwnProperty.call(se._attachments, ke)) se._attachments[ke].stub = true;
ne(null, se);
}
})); else if ("all" === ee.open_revs) this._getRevisionTree(_, (function(_, ee) {
if (_) return ne(_);
ie = collectLeaves(ee).map((function(_) {
return _.rev;
}));
finishOpenRevs();
})); else if (Array.isArray(ee.open_revs)) {
ie = ee.open_revs;
for (var re = 0; re < ie.length; re++) {
var se = ie[re];
if (!("string" == typeof se && /^\d+-/.test(se))) return ne(createError(INVALID_REV));
}
finishOpenRevs();
} else return ne(createError(UNKNOWN_ERROR, "function_clause"));
})).bind(this);
this.getAttachment = adapterFun("getAttachment", (function(_, ee, ne, ie) {
if (ne instanceof Function) {
ie = ne;
ne = {};
}
this._get(_, ne, ((re, se) => {
if (re) return ie(re);
if (se.doc._attachments && se.doc._attachments[ee]) {
ne.ctx = se.ctx;
ne.binary = true;
this._getAttachment(_, ee, se.doc._attachments[ee], ne, ie);
} else return ie(createError(MISSING_DOC));
}));
})).bind(this);
this.allDocs = adapterFun("allDocs", (function(_, ee) {
if ("function" == typeof _) {
ee = _;
_ = {};
}
_.skip = "undefined" != typeof _.skip ? _.skip : 0;
if (_.start_key) _.startkey = _.start_key;
if (_.end_key) _.endkey = _.end_key;
if ("keys" in _) {
if (!Array.isArray(_.keys)) return ee(new TypeError("options.keys must be an array"));
var ne = [ "startkey", "endkey", "key" ].filter((function(ee) {
return ee in _;
}))[0];
if (ne) {
ee(createError(QUERY_PARSE_ERROR, "Query parameter `" + ne + "` is not compatible with multi-get"));
return;
}
if (!isRemote(this)) {
allDocsKeysParse(_);
if (0 === _.keys.length) return this._allDocs({
limit: 0
}, ee);
}
}
return this._allDocs(_, ee);
})).bind(this);
this.close = adapterFun("close", (function(_) {
this._closed = true;
this.emit("closed");
return this._close(_);
})).bind(this);
this.info = adapterFun("info", (function(_) {
this._info(((ee, ne) => {
if (ee) return _(ee);
ne.db_name = ne.db_name || this.name;
ne.auto_compaction = !!(this.auto_compaction && !isRemote(this));
ne.adapter = this.adapter;
_(null, ne);
}));
})).bind(this);
this.id = adapterFun("id", (function(_) {
return this._id(_);
})).bind(this);
this.bulkDocs = adapterFun("bulkDocs", (function(_, ee, ne) {
if ("function" == typeof ee) {
ne = ee;
ee = {};
}
ee = ee || {};
if (Array.isArray(_)) _ = {
docs: _
};
if (!_ || !_.docs || !Array.isArray(_.docs)) return ne(createError(MISSING_BULK_DOCS));
for (var ie = 0; ie < _.docs.length; ++ie) if ("object" != typeof _.docs[ie] || Array.isArray(_.docs[ie])) return ne(createError(NOT_AN_OBJECT));
var re;
_.docs.forEach((function(_) {
if (_._attachments) Object.keys(_._attachments).forEach((function(ee) {
re = re || attachmentNameError(ee);
if (!_._attachments[ee].content_type) guardedConsole("warn", "Attachment", ee, "on document", _._id, "is missing content_type");
}));
}));
if (re) return ne(createError(BAD_REQUEST, re));
if (!("new_edits" in ee)) if ("new_edits" in _) ee.new_edits = _.new_edits; else ee.new_edits = true;
var se = this;
if (!ee.new_edits && !isRemote(se)) _.docs.sort(compareByIdThenRev);
cleanDocs(_.docs);
var oe = _.docs.map((function(_) {
return _._id;
}));
this._bulkDocs(_, ee, (function(_, ie) {
if (_) return ne(_);
if (!ee.new_edits) ie = ie.filter((function(_) {
return _.error;
}));
if (!isRemote(se)) for (var re = 0, le = ie.length; re < le; re++) ie[re].id = ie[re].id || oe[re];
ne(null, ie);
}));
})).bind(this);
this.registerDependentDatabase = adapterFun("registerDependentDatabase", (function(_, ee) {
var ne = clone(this.__opts);
if (this.__opts.view_adapter) ne.adapter = this.__opts.view_adapter;
var ie = new this.constructor(_, ne);
upsert(this, "_local/_pouch_dependentDbs", (function diffFun(ee) {
ee.dependentDbs = ee.dependentDbs || {};
if (ee.dependentDbs[_]) return false;
ee.dependentDbs[_] = true;
return ee;
})).then((function() {
ee(null, {
db: ie
});
})).catch(ee);
})).bind(this);
this.destroy = adapterFun("destroy", (function(_, ee) {
if ("function" == typeof _) {
ee = _;
_ = {};
}
var ne = "use_prefix" in this ? this.use_prefix : true;
const destroyDb = () => {
this._destroy(_, ((_, ne) => {
if (_) return ee(_);
this._destroyed = true;
this.emit("destroyed");
ee(null, ne || {
ok: true
});
}));
};
if (isRemote(this)) return destroyDb();
this.get("_local/_pouch_dependentDbs", ((_, ie) => {
if (_) if (404 !== _.status) return ee(_); else return destroyDb();
var re = ie.dependentDbs, se = this.constructor, oe = Object.keys(re).map((_ => {
var ee = ne ? _.replace(new RegExp("^" + se.prefix), "") : _;
return new se(ee, this.__opts).destroy();
}));
Promise.all(oe).then(destroyDb, ee);
}));
})).bind(this);
}
_compact(_, ee) {
var ne, ie = {
return_docs: false,
last_seq: _.last_seq || 0
}, re = [], se = 0;
const onChange = _ => {
this.activeTasks.update(ne, {
completed_items: ++se
});
re.push(this.compactDocument(_.id, 0));
}, onError = _ => {
this.activeTasks.remove(ne, _);
ee(_);
}, onComplete = _ => {
var ie = _.last_seq;
Promise.all(re).then((() => upsert(this, "_local/compaction", (_ => {
if (!_.last_seq || _.last_seq < ie) {
_.last_seq = ie;
return _;
}
return false;
})))).then((() => {
this.activeTasks.remove(ne);
ee(null, {
ok: true
});
})).catch(onError);
};
this.info().then((_ => {
ne = this.activeTasks.add({
name: "database_compaction",
total_items: _.update_seq - ie.last_seq
});
this.changes(ie).on("change", onChange).on("complete", onComplete).on("error", onError);
}));
}
changes(_, ee) {
if ("function" == typeof _) {
ee = _;
_ = {};
}
(_ = _ || {}).return_docs = "return_docs" in _ ? _.return_docs : !_.live;
return new Changes2(this, _, ee);
}
type() {
return "function" == typeof this._type ? this._type() : this.adapter;
}
};
AbstractPouchDB.prototype.purge = adapterFun("_purge", (function(_, ee, ne) {
if ("undefined" == typeof this._purge) return ne(createError(UNKNOWN_ERROR, "Purge is not implemented in the " + this.adapter + " adapter."));
var ie = this;
ie._getRevisionTree(_, ((re, se) => {
if (re) return ne(re);
if (!se) return ne(createError(MISSING_DOC));
let oe;
try {
oe = findPathToLeaf(se, ee);
} catch (_) {
return ne(_.message || _);
}
ie._purge(_, oe, ((re, se) => {
if (re) return ne(re); else appendPurgeSeq(ie, _, ee).then((function() {
return ne(null, se);
}));
}));
}));
}));
var TaskQueue = class {
constructor() {
this.isReady = false;
this.failed = false;
this.queue = [];
}
execute() {
var _;
if (this.failed) for (;_ = this.queue.shift(); ) _(this.failed); else for (;_ = this.queue.shift(); ) _();
}
fail(_) {
this.failed = _;
this.execute();
}
ready(_) {
this.isReady = true;
this.db = _;
this.execute();
}
addTask(_) {
this.queue.push(_);
if (this.failed) this.execute();
}
};
function parseAdapter(_, ee) {
var ne = _.match(/([a-z-]*):\/\/(.*)/);
if (ne) return {
name: /https?/.test(ne[1]) ? ne[1] + "://" + ne[2] : ne[2],
adapter: ne[1]
};
var ie = PouchDB.adapters, re = PouchDB.preferredAdapters, se = PouchDB.prefix, oe = ee.adapter;
if (!oe) for (var le = 0; le < re.length && "idb" === (oe = re[le]) && "websql" in ie && hasLocalStorage() && localStorage["_pouch__websqldb_" + se + _]; ++le) guardedConsole("log", 'PouchDB is downgrading "' + _ + '" to WebSQL to avoid data loss, because it was already opened with WebSQL.');
var ue = ie[oe];
return {
name: (ue && "use_prefix" in ue ? ue.use_prefix : true) ? se + _ : _,
adapter: oe
};
}
function inherits(_, ee) {
_.prototype = Object.create(ee.prototype, {
constructor: {
value: _
}
});
}
function createClass(_, ee) {
let klass = function(..._) {
if (!(this instanceof klass)) return new klass(..._);
ee.apply(this, _);
};
inherits(klass, _);
return klass;
}
function prepareForDestruction(_) {
function onDestroyed(ee) {
_.removeListener("closed", onClosed);
if (!ee) _.constructor.emit("destroyed", _.name);
}
function onClosed() {
_.removeListener("destroyed", onDestroyed);
_.constructor.emit("unref", _);
}
_.once("destroyed", onDestroyed);
_.once("closed", onClosed);
_.constructor.emit("ref", _);
}
var PouchInternal = class extends AbstractPouchDB {
constructor(_, ee) {
super();
this._setup(_, ee);
}
_setup(_, ee) {
super._setup();
ee = ee || {};
if (_ && "object" == typeof _) {
_ = (ee = _).name;
delete ee.name;
}
if (void 0 === ee.deterministic_revs) ee.deterministic_revs = true;
this.__opts = ee = clone(ee);
this.auto_compaction = ee.auto_compaction;
this.purged_infos_limit = ee.purged_infos_limit || 1e3;
this.prefix = PouchDB.prefix;
if ("string" != typeof _) throw new Error("Missing/invalid DB name");
var ne = parseAdapter((ee.prefix || "") + _, ee);
ee.name = ne.name;
ee.adapter = ee.adapter || ne.adapter;
this.name = _;
this._adapter = ee.adapter;
PouchDB.emit("debug", [ "adapter", "Picked adapter: ", ee.adapter ]);
if (!PouchDB.adapters[ee.adapter] || !PouchDB.adapters[ee.adapter].valid()) throw new Error("Invalid Adapter: " + ee.adapter);
if (ee.view_adapter) if (!PouchDB.adapters[ee.view_adapter] || !PouchDB.adapters[ee.view_adapter].valid()) throw new Error("Invalid View Adapter: " + ee.view_adapter);
this.taskqueue = new TaskQueue;
this.adapter = ee.adapter;
PouchDB.adapters[ee.adapter].call(this, ee, (_ => {
if (_) return this.taskqueue.fail(_);
prepareForDestruction(this);
this.emit("created", this);
PouchDB.emit("created", this.name);
this.taskqueue.ready(this);
}));
}
}, PouchDB = createClass(PouchInternal, (function(_, ee) {
PouchInternal.prototype._setup.call(this, _, ee);
})), ActiveTasks = class {
constructor() {
this.tasks = {};
}
list() {
return Object.values(this.tasks);
}
add(_) {
const ee = v4_default();
this.tasks[ee] = {
id: ee,
name: _.name,
total_items: _.total_items,
created_at: (new Date).toJSON()
};
return ee;
}
get(_) {
return this.tasks[_];
}
remove(_, ee) {
delete this.tasks[_];
return this.tasks;
}
update(_, ee) {
const ne = this.tasks[_];
if ("undefined" != typeof ne) {
const ie = {
id: ne.id,
name: ne.name,
created_at: ne.created_at,
total_items: ee.total_items || ne.total_items,
completed_items: ee.completed_items || ne.completed_items,
updated_at: (new Date).toJSON()
};
this.tasks[_] = ie;
}
return this.tasks;
}
};
PouchDB.adapters = {};
PouchDB.preferredAdapters = [];
PouchDB.prefix = "_pouch_";
var eventEmitter = new import_events2.default;
function setUpEventEmitter(_) {
Object.keys(import_events2.default.prototype).forEach((function(ee) {
if ("function" == typeof import_events2.default.prototype[ee]) _[ee] = eventEmitter[ee].bind(eventEmitter);
}));
var ee = _._destructionListeners = new ExportedMap;
_.on("ref", (function onConstructorRef(_) {
if (!ee.has(_.name)) ee.set(_.name, []);
ee.get(_.name).push(_);
}));
_.on("unref", (function onConstructorUnref(_) {
if (ee.has(_.name)) {
var ne = ee.get(_.name), ie = ne.indexOf(_);
if (!(ie < 0)) {
ne.splice(ie, 1);
if (ne.length > 1) ee.set(_.name, ne); else ee.delete(_.name);
}
}
}));
_.on("destroyed", (function onConstructorDestroyed(_) {
if (ee.has(_)) {
var ne = ee.get(_);
ee.delete(_);
ne.forEach((function(_) {
_.emit("destroyed", true);
}));
}
}));
}
setUpEventEmitter(PouchDB);
PouchDB.adapter = function(_, ee, ne) {
if (ee.valid()) {
PouchDB.adapters[_] = ee;
if (ne) PouchDB.preferredAdapters.push(_);
}
};
PouchDB.plugin = function(_) {
if ("function" == typeof _) _(PouchDB); else if ("object" != typeof _ || 0 === Object.keys(_).length) throw new Error('Invalid plugin: got "' + _ + '", expected an object or a function'); else Object.keys(_).forEach((function(ee) {
PouchDB.prototype[ee] = _[ee];
}));
if (this.__defaults) PouchDB.__defaults = assign$2({}, this.__defaults);
return PouchDB;
};
PouchDB.defaults = function(_) {
let ee = createClass(PouchDB, (function(_, ne) {
ne = ne || {};
if (_ && "object" == typeof _) {
_ = (ne = _).name;
delete ne.name;
}
ne = assign$2({}, ee.__defaults, ne);
PouchDB.call(this, _, ne);
}));
ee.preferredAdapters = PouchDB.preferredAdapters.slice();
Object.keys(PouchDB).forEach((function(_) {
if (!(_ in ee)) ee[_] = PouchDB[_];
}));
ee.__defaults = assign$2({}, this.__defaults, _);
return ee;
};
PouchDB.fetch = function(_, ee) {
return f2(_, ee);
};
PouchDB.prototype.activeTasks = PouchDB.activeTasks = new ActiveTasks;
var version = "8.0.1";
PouchDB.plugin(index_browser_es_default);
PouchDB.version = version;
var index_es_default = PouchDB;
function toObject(_) {
return _.reduce((function(_, ee) {
_[ee] = true;
return _;
}), {});
}
var reservedWords = toObject([ "_id", "_rev", "_access", "_attachments", "_deleted", "_revisions", "_revs_info", "_conflicts", "_deleted_conflicts", "_local_seq", "_rev_tree", "_replication_id", "_replication_state", "_replication_state_time", "_replication_state_reason", "_replication_stats", "_removed" ]), dataWords = toObject([ "_access", "_attachments", "_replication_id", "_replication_state", "_replication_state_time", "_replication_state_reason", "_replication_stats" ]);
function parseRevisionInfo(_) {
if (!/^\d+-/.test(_)) return createError(INVALID_REV);
var ee = _.indexOf("-"), ne = _.substring(0, ee), ie = _.substring(ee + 1);
return {
prefix: parseInt(ne, 10),
id: ie
};
}
function makeRevTreeFromRevisions(_, ee) {
for (var ne = _.start - _.ids.length + 1, ie = _.ids, re = [ ie[0], ee, [] ], se = 1, oe = ie.length; se < oe; se++) re = [ ie[se], {
status: "missing"
}, [ re ] ];
return [ {
pos: ne,
ids: re
} ];
}
function parseDoc(_, ee, ne) {
if (!ne) ne = {
deterministic_revs: true
};
var ie, re, se, oe = {
status: "available"
};
if (_._deleted) oe.deleted = true;
if (ee) {
if (!_._id) _._id = uuid();
re = rev2(_, ne.deterministic_revs);
if (_._rev) {
if ((se = parseRevisionInfo(_._rev)).error) return se;
_._rev_tree = [ {
pos: se.prefix,
ids: [ se.id, {
status: "missing"
}, [ [ re, oe, [] ] ] ]
} ];
ie = se.prefix + 1;
} else {
_._rev_tree = [ {
pos: 1,
ids: [ re, oe, [] ]
} ];
ie = 1;
}
} else {
if (_._revisions) {
_._rev_tree = makeRevTreeFromRevisions(_._revisions, oe);
ie = _._revisions.start;
re = _._revisions.ids[0];
}
if (!_._rev_tree) {
if ((se = parseRevisionInfo(_._rev)).error) return se;
ie = se.prefix;
re = se.id;
_._rev_tree = [ {
pos: ie,
ids: [ re, oe, [] ]
} ];
}
}
invalidIdError(_._id);
_._rev = ie + "-" + re;
var le = {
metadata: {},
data: {}
};
for (var ue in _) if (Object.prototype.hasOwnProperty.call(_, ue)) {
var de = "_" === ue[0];
if (de && !reservedWords[ue]) {
var fe = createError(DOC_VALIDATION, ue);
fe.message = DOC_VALIDATION.message + ": " + ue;
throw fe;
} else if (de && !dataWords[ue]) le.metadata[ue.slice(1)] = _[ue]; else le.data[ue] = _[ue];
}
return le;
}
function parseBase64(_) {
try {
return thisAtob(_);
} catch (_) {
return {
error: createError(BAD_ARG, "Attachment is not a valid base64 string")
};
}
}
function preprocessString(_, ee, ne) {
var ie = parseBase64(_.data);
if (ie.error) return ne(ie.error);
_.length = ie.length;
if ("blob" === ee) _.data = binStringToBluffer(ie, _.content_type); else if ("base64" === ee) _.data = thisBtoa(ie); else _.data = ie;
binaryMd5(ie, (function(ee) {
_.digest = "md5-" + ee;
ne();
}));
}
function preprocessBlob(_, ee, ne) {
binaryMd5(_.data, (function(ie) {
_.digest = "md5-" + ie;
_.length = _.data.size || _.data.length || 0;
if ("binary" === ee) blobToBinaryString(_.data, (function(ee) {
_.data = ee;
ne();
})); else if ("base64" === ee) blobToBase64(_.data, (function(ee) {
_.data = ee;
ne();
})); else ne();
}));
}
function preprocessAttachment(_, ee, ne) {
if (_.stub) return ne();
if ("string" == typeof _.data) preprocessString(_, ee, ne); else preprocessBlob(_, ee, ne);
}
function preprocessAttachments(_, ee, ne) {
if (!_.length) return ne();
var ie, re = 0;
_.forEach((function(_) {
var ne = _.data && _.data._attachments ? Object.keys(_.data._attachments) : [], re = 0;
if (!ne.length) return done();
function processedAttachment(_) {
ie = _;
if (++re === ne.length) done();
}
for (var se in _.data._attachments) if (Object.prototype.hasOwnProperty.call(_.data._attachments, se)) preprocessAttachment(_.data._attachments[se], ee, processedAttachment);
}));
function done() {
re++;
if (_.length === re) if (ie) ne(ie); else ne();
}
}
function updateDoc(_, ee, ne, ie, re, se, oe, le) {
if (revExists(ee.rev_tree, ne.metadata.rev) && !le) {
ie[re] = ne;
return se();
}
var ue = ee.winningRev || winningRev(ee), de = "deleted" in ee ? ee.deleted : isDeleted(ee, ue), fe = "deleted" in ne.metadata ? ne.metadata.deleted : isDeleted(ne.metadata), he = /^1-/.test(ne.metadata.rev);
if (de && !fe && le && he) {
var pe = ne.data;
pe._rev = ue;
pe._id = ne.metadata.id;
ne = parseDoc(pe, le);
}
var ge = merge(ee.rev_tree, ne.metadata.rev_tree[0], _);
if (le && (de && fe && "new_leaf" !== ge.conflicts || !de && "new_leaf" !== ge.conflicts || de && !fe && "new_branch" === ge.conflicts)) {
var me = createError(REV_CONFLICT);
ie[re] = me;
return se();
}
var ye = ne.metadata.rev;
ne.metadata.rev_tree = ge.tree;
ne.stemmedRevs = ge.stemmedRevs || [];
if (ee.rev_map) ne.metadata.rev_map = ee.rev_map;
var ve, Se = winningRev(ne.metadata), Ee = isDeleted(ne.metadata, Se), Ce = de === Ee ? 0 : de < Ee ? -1 : 1;
if (ye === Se) ve = Ee; else ve = isDeleted(ne.metadata, ye);
oe(ne, Se, Ee, ve, true, Ce, re, se);
}
function rootIsMissing(_) {
return "missing" === _.metadata.rev_tree[0].ids[1].status;
}
function processDocs(_, ee, ne, ie, re, se, oe, le, ue) {
_ = _ || 1e3;
var de = le.new_edits, fe = new ExportedMap, he = 0, pe = ee.length;
function checkAllDocsDone() {
if (++he === pe && ue) ue();
}
ee.forEach((function(_, ee) {
if (!_._id || !isLocalId(_._id)) {
var ie = _.metadata.id;
if (fe.has(ie)) {
pe--;
fe.get(ie).push([ _, ee ]);
} else fe.set(ie, [ [ _, ee ] ]);
} else {
var oe = _._deleted ? "_removeLocal" : "_putLocal";
ne[oe](_, {
ctx: re
}, (function(_, ne) {
se[ee] = _ || ne;
checkAllDocsDone();
}));
}
}));
fe.forEach((function(ee, ne) {
var re = 0;
function docWritten() {
if (++re < ee.length) nextDoc(); else checkAllDocsDone();
}
function nextDoc() {
var ue = ee[re], fe = ue[0], he = ue[1];
if (ie.has(ne)) updateDoc(_, ie.get(ne), fe, se, he, docWritten, oe, de); else {
var pe = merge([], fe.metadata.rev_tree[0], _);
fe.metadata.rev_tree = pe.tree;
fe.stemmedRevs = pe.stemmedRevs || [];
(function insertDoc(_, ee, ne) {
var ie = winningRev(_.metadata), re = isDeleted(_.metadata, ie);
if ("was_delete" in le && re) {
se[ee] = createError(MISSING_DOC, "deleted");
return ne();
}
if (de && rootIsMissing(_)) {
var ue = createError(REV_CONFLICT);
se[ee] = ue;
return ne();
}
oe(_, ie, re, re, false, re ? 0 : 1, ee, ne);
})(fe, he, docWritten);
}
}
nextDoc();
}));
}
var import_vuvuzela = __toESM(require_vuvuzela());
function safeJsonParse(_) {
try {
return JSON.parse(_);
} catch (ee) {
return import_vuvuzela.default.parse(_);
}
}
function safeJsonStringify(_) {
try {
return JSON.stringify(_);
} catch (ee) {
return import_vuvuzela.default.stringify(_);
}
}
var ADAPTER_VERSION = 5, DOC_STORE = "document-store", BY_SEQ_STORE = "by-sequence", ATTACH_STORE = "attach-store", ATTACH_AND_SEQ_STORE = "attach-seq-store", META_STORE = "meta-store", LOCAL_STORE = "local-store", DETECT_BLOB_SUPPORT_STORE = "detect-blob-support";
function idbError(_) {
return function(ee) {
var ne = "unknown_error";
if (ee.target && ee.target.error) ne = ee.target.error.name || ee.target.error.message;
_(createError(IDB_ERROR, ne, ee.type));
};
}
function encodeMetadata(_, ee, ne) {
return {
data: safeJsonStringify(_),
winningRev: ee,
deletedOrLocal: ne ? "1" : "0",
seq: _.seq,
id: _.id
};
}
function decodeMetadata(_) {
if (!_) return null;
var ee = safeJsonParse(_.data);
ee.winningRev = _.winningRev;
ee.deleted = "1" === _.deletedOrLocal;
ee.seq = _.seq;
return ee;
}
function decodeDoc(_) {
if (!_) return _;
var ee = _._doc_id_rev.lastIndexOf(":");
_._id = _._doc_id_rev.substring(0, ee - 1);
_._rev = _._doc_id_rev.substring(ee + 1);
delete _._doc_id_rev;
return _;
}
function readBlobData(_, ee, ne, ie) {
if (ne) if (!_) ie(createBlob2([ "" ], {
type: ee
})); else if ("string" != typeof _) ie(_); else ie(b64ToBluffer(_, ee)); else if (!_) ie(""); else if ("string" != typeof _) readAsBinaryString(_, (function(_) {
ie(thisBtoa(_));
})); else ie(_);
}
function fetchAttachmentsIfNecessary(_, ee, ne, ie) {
var re = Object.keys(_._attachments || {});
if (!re.length) return ie && ie();
var se = 0;
function checkDone() {
if (++se === re.length && ie) ie();
}
re.forEach((function(ie) {
if (ee.attachments && ee.include_docs) (function fetchAttachment(_, ee) {
var ie = _._attachments[ee], re = ie.digest;
ne.objectStore(ATTACH_STORE).get(re).onsuccess = function(_) {
ie.body = _.target.result.body;
checkDone();
};
})(_, ie); else {
_._attachments[ie].stub = true;
checkDone();
}
}));
}
function postProcessAttachments(_, ee) {
return Promise.all(_.map((function(_) {
if (_.doc && _.doc._attachments) {
var ne = Object.keys(_.doc._attachments);
return Promise.all(ne.map((function(ne) {
var ie = _.doc._attachments[ne];
if ("body" in ie) {
var re = ie.body, se = ie.content_type;
return new Promise((function(oe) {
readBlobData(re, se, ee, (function(ee) {
_.doc._attachments[ne] = assign$2(pick(ie, [ "digest", "content_type" ]), {
data: ee
});
oe();
}));
}));
}
})));
}
})));
}
function compactRevs(_, ee, ne) {
var ie = [], re = ne.objectStore(BY_SEQ_STORE), se = ne.objectStore(ATTACH_STORE), oe = ne.objectStore(ATTACH_AND_SEQ_STORE), le = _.length;
function checkDone() {
if (! --le) (function deleteOrphanedAttachments() {
if (ie.length) ie.forEach((function(_) {
oe.index("digestSeq").count(IDBKeyRange.bound(_ + "::", _ + "::", false, false)).onsuccess = function(ee) {
if (!ee.target.result) se.delete(_);
};
}));
})();
}
_.forEach((function(_) {
var ne = re.index("_doc_id_rev"), se = ee + "::" + _;
ne.getKey(se).onsuccess = function(_) {
var ee = _.target.result;
if ("number" != typeof ee) return checkDone();
re.delete(ee);
oe.index("seq").openCursor(IDBKeyRange.only(ee)).onsuccess = function(_) {
var ee = _.target.result;
if (ee) {
var ne = ee.value.digestSeq.split("::")[0];
ie.push(ne);
oe.delete(ee.primaryKey);
ee.continue();
} else checkDone();
};
};
}));
}
function openTransactionSafely(_, ee, ne) {
try {
return {
txn: _.transaction(ee, ne)
};
} catch (_) {
return {
error: _
};
}
}
var changesHandler$1 = new Changes;
function idbBulkDocs(_, ee, ne, ie, re, se) {
for (var oe, le, ue, de, fe, he, pe, ge, me = ee.docs, ye = 0, ve = me.length; ye < ve; ye++) {
var Se = me[ye];
if (!Se._id || !isLocalId(Se._id)) if ((Se = me[ye] = parseDoc(Se, ne.new_edits, _)).error && !pe) pe = Se;
}
if (pe) return se(pe);
var Ee = false, Ce = 0, we = new Array(me.length), Oe = new ExportedMap, ke = false, xe = ie._meta.blobSupport ? "blob" : "base64";
preprocessAttachments(me, xe, (function(ee) {
if (ee) return se(ee);
(function startTransaction() {
var ee = openTransactionSafely(re, [ DOC_STORE, BY_SEQ_STORE, ATTACH_STORE, LOCAL_STORE, ATTACH_AND_SEQ_STORE, META_STORE ], "readwrite");
if (ee.error) return se(ee.error);
(oe = ee.txn).onabort = idbError(se);
oe.ontimeout = idbError(se);
oe.oncomplete = complete;
le = oe.objectStore(DOC_STORE);
ue = oe.objectStore(BY_SEQ_STORE);
de = oe.objectStore(ATTACH_STORE);
fe = oe.objectStore(ATTACH_AND_SEQ_STORE);
(he = oe.objectStore(META_STORE)).get(META_STORE).onsuccess = function(_) {
ge = _.target.result;
updateDocCountIfReady();
};
(function verifyAttachments(_) {
var ee = [];
me.forEach((function(_) {
if (_.data && _.data._attachments) Object.keys(_.data._attachments).forEach((function(ne) {
var ie = _.data._attachments[ne];
if (ie.stub) ee.push(ie.digest);
}));
}));
if (!ee.length) return _();
var ne, ie = 0;
ee.forEach((function(re) {
(function verifyAttachment(_, ee) {
de.get(_).onsuccess = function(ne) {
if (!ne.target.result) {
var ie = createError(MISSING_STUB, "unknown stub attachment with digest " + _);
ie.status = 412;
ee(ie);
} else ee();
};
})(re, (function(re) {
if (re && !ne) ne = re;
(function checkDone() {
if (++ie === ee.length) _(ne);
})();
}));
}));
})((function(ee) {
if (ee) {
ke = true;
return se(ee);
}
(function fetchExistingDocs() {
if (me.length) for (var ee = 0, re = 0, se = me.length; re < se; re++) {
var ue = me[re];
if (!ue._id || !isLocalId(ue._id)) le.get(ue.metadata.id).onsuccess = readMetadata; else checkDone();
}
function checkDone() {
if (++ee === me.length) (function idbProcessDocs() {
processDocs(_.revs_limit, me, ie, Oe, oe, we, writeDoc, ne, onAllDocsProcessed);
})();
}
function readMetadata(_) {
var ee = decodeMetadata(_.target.result);
if (ee) Oe.set(ee.id, ee);
checkDone();
}
})();
}));
})();
}));
function onAllDocsProcessed() {
Ee = true;
updateDocCountIfReady();
}
function updateDocCountIfReady() {
if (ge && Ee) {
ge.docCount += Ce;
he.put(ge);
}
}
function complete() {
if (!ke) {
changesHandler$1.notify(ie._meta.name);
se(null, we);
}
}
function writeDoc(_, ee, ne, ie, re, se, oe, le) {
_.metadata.winningRev = ee;
_.metadata.deleted = ne;
var ue = _.data;
ue._id = _.metadata.id;
ue._rev = _.metadata.rev;
if (ie) ue._deleted = true;
if (ue._attachments && Object.keys(ue._attachments).length) return function writeAttachments(_, ee, ne, ie, re, se) {
var oe = _.data, le = 0, ue = Object.keys(oe._attachments);
function collectResults() {
if (le === ue.length) finishDoc(_, ee, ne, ie, re, se);
}
function attachmentSaved() {
le++;
collectResults();
}
ue.forEach((function(ne) {
var ie = _.data._attachments[ne];
if (!ie.stub) {
var re = ie.data;
delete ie.data;
ie.revpos = parseInt(ee, 10);
(function saveAttachment(_, ee, ne) {
de.count(_).onsuccess = function(ie) {
if (ie.target.result) return ne();
var re = {
digest: _,
body: ee
};
de.put(re).onsuccess = ne;
};
})(ie.digest, re, attachmentSaved);
} else {
le++;
collectResults();
}
}));
}(_, ee, ne, re, oe, le);
Ce += se;
updateDocCountIfReady();
finishDoc(_, ee, ne, re, oe, le);
}
function finishDoc(_, ee, ne, re, se, de) {
var he = _.data, pe = _.metadata;
he._doc_id_rev = pe.id + "::" + pe.rev;
delete he._id;
delete he._rev;
function afterPutDoc(se) {
var ue = _.stemmedRevs || [];
if (re && ie.auto_compaction) ue = ue.concat(compactTree(_.metadata));
if (ue && ue.length) compactRevs(ue, _.metadata.id, oe);
pe.seq = se.target.result;
var de = encodeMetadata(pe, ee, ne);
le.put(de).onsuccess = afterPutMetadata;
}
function afterPutMetadata() {
we[se] = {
ok: true,
id: pe.id,
rev: pe.rev
};
Oe.set(_.metadata.id, _.metadata);
(function insertAttachmentMappings(_, ee, ne) {
var ie = 0, re = Object.keys(_.data._attachments || {});
if (!re.length) return ne();
function checkDone() {
if (++ie === re.length) ne();
}
function add(ne) {
var ie = _.data._attachments[ne].digest, re = fe.put({
seq: ee,
digestSeq: ie + "::" + ee
});
re.onsuccess = checkDone;
re.onerror = function(_) {
_.preventDefault();
_.stopPropagation();
checkDone();
};
}
for (var se = 0; se < re.length; se++) add(re[se]);
})(_, pe.seq, de);
}
var ge = ue.put(he);
ge.onsuccess = afterPutDoc;
ge.onerror = function afterPutDocError(_) {
_.preventDefault();
_.stopPropagation();
ue.index("_doc_id_rev").getKey(he._doc_id_rev).onsuccess = function(_) {
ue.put(he, _.target.result).onsuccess = afterPutDoc;
};
};
}
}
function runBatchedCursor(_, ee, ne, ie, re) {
if (-1 === ie) ie = 1e3;
var se, oe, le;
function onGetAll(_) {
oe = _.target.result;
if (se) re(se, oe, le);
}
function onGetAllKeys(_) {
se = _.target.result;
if (oe) re(se, oe, le);
}
function onCursor(_) {
var ee = _.target.result;
if (!ee) return re();
re([ ee.key ], [ ee.value ], ee);
}
if ("function" == typeof _.getAll && "function" == typeof _.getAllKeys && ie > 1 && !ne) {
le = {
continue: function continuePseudoCursor() {
if (!se.length) return re();
var ne, le = se[se.length - 1];
if (ee && ee.upper) try {
ne = IDBKeyRange.bound(le, ee.upper, true, ee.upperOpen);
} catch (_) {
if ("DataError" === _.name && 0 === _.code) return re();
} else ne = IDBKeyRange.lowerBound(le, true);
ee = ne;
se = null;
oe = null;
_.getAll(ee, ie).onsuccess = onGetAll;
_.getAllKeys(ee, ie).onsuccess = onGetAllKeys;
}
};
_.getAll(ee, ie).onsuccess = onGetAll;
_.getAllKeys(ee, ie).onsuccess = onGetAllKeys;
} else if (ne) _.openCursor(ee, "prev").onsuccess = onCursor; else _.openCursor(ee).onsuccess = onCursor;
}
function getAll(_, ee, ne) {
if ("function" != typeof _.getAll) {
var ie = [];
_.openCursor(ee).onsuccess = function onCursor(_) {
var ee = _.target.result;
if (ee) {
ie.push(ee.value);
ee.continue();
} else ne({
target: {
result: ie
}
});
};
} else _.getAll(ee).onsuccess = ne;
}
function allDocsKeys(_, ee, ne) {
var ie = new Array(_.length), re = 0;
_.forEach((function(se, oe) {
ee.get(se).onsuccess = function(ee) {
if (ee.target.result) ie[oe] = ee.target.result; else ie[oe] = {
key: se,
error: "not_found"
};
if (++re === _.length) ne(_, ie, {});
};
}));
}
function createKeyRange(_, ee, ne, ie, re) {
try {
if (_ && ee) if (re) return IDBKeyRange.bound(ee, _, !ne, false); else return IDBKeyRange.bound(_, ee, false, !ne); else if (_) if (re) return IDBKeyRange.upperBound(_); else return IDBKeyRange.lowerBound(_); else if (ee) if (re) return IDBKeyRange.lowerBound(ee, !ne); else return IDBKeyRange.upperBound(ee, !ne); else if (ie) return IDBKeyRange.only(ie);
} catch (_) {
return {
error: _
};
}
return null;
}
function idbAllDocs(_, ee, ne) {
var ie, re, se = "startkey" in _ ? _.startkey : false, oe = "endkey" in _ ? _.endkey : false, le = "key" in _ ? _.key : false, ue = "keys" in _ ? _.keys : false, de = _.skip || 0, fe = "number" == typeof _.limit ? _.limit : -1, he = false !== _.inclusive_end;
if (!ue) if ((re = (ie = createKeyRange(se, oe, he, le, _.descending)) && ie.error) && !("DataError" === re.name && 0 === re.code)) return ne(createError(IDB_ERROR, re.name, re.message));
var pe = [ DOC_STORE, BY_SEQ_STORE, META_STORE ];
if (_.attachments) pe.push(ATTACH_STORE);
var ge = openTransactionSafely(ee, pe, "readonly");
if (ge.error) return ne(ge.error);
var me = ge.txn;
me.oncomplete = function onTxnComplete() {
if (_.attachments) postProcessAttachments(Oe, _.binary).then(onResultsReady); else onResultsReady();
};
me.onabort = idbError(ne);
var ye, ve, Se = me.objectStore(DOC_STORE), Ee = me.objectStore(BY_SEQ_STORE), Ce = me.objectStore(META_STORE), we = Ee.index("_doc_id_rev"), Oe = [];
Ce.get(META_STORE).onsuccess = function(_) {
ye = _.target.result.docCount;
};
if (_.update_seq) (function getMaxUpdateSeq(_, ee) {
_.openCursor(null, "prev").onsuccess = function onCursor(_) {
var ne = _.target.result, ie = void 0;
if (ne && ne.key) ie = ne.key;
return ee({
target: {
result: [ ie ]
}
});
};
})(Ee, (function(_) {
if (_.target.result && _.target.result.length > 0) ve = _.target.result[0];
}));
function allDocsInner(ee, ne) {
var ie = {
id: ne.id,
key: ne.id,
value: {
rev: ee
}
};
if (ne.deleted) {
if (ue) {
Oe.push(ie);
ie.value.deleted = true;
ie.doc = null;
}
} else if (de-- <= 0) {
Oe.push(ie);
if (_.include_docs) (function fetchDocAsynchronously(ee, ne, ie) {
var re = ee.id + "::" + ie;
we.get(re).onsuccess = function onGetDoc(ie) {
ne.doc = decodeDoc(ie.target.result) || {};
if (_.conflicts) {
var re = collectConflicts(ee);
if (re.length) ne.doc._conflicts = re;
}
fetchAttachmentsIfNecessary(ne.doc, _, me);
};
})(ne, ie, ee);
}
}
function processBatch(_) {
for (var ee = 0, ne = _.length; ee < ne && Oe.length !== fe; ee++) {
var ie = _[ee];
if (!ie.error || !ue) {
var re = decodeMetadata(ie);
allDocsInner(re.winningRev, re);
} else Oe.push(ie);
}
}
function onBatch(_, ee, ne) {
if (ne) {
processBatch(ee);
if (Oe.length < fe) ne.continue();
}
}
function onResultsReady() {
var ee = {
total_rows: ye,
offset: _.skip,
rows: Oe
};
if (_.update_seq && void 0 !== ve) ee.update_seq = ve;
ne(null, ee);
}
if (!re && 0 !== fe) {
if (ue) return allDocsKeys(_.keys, Se, onBatch);
if (-1 === fe) return getAll(Se, ie, (function onGetAll(ee) {
var ne = ee.target.result;
if (_.descending) ne = ne.reverse();
processBatch(ne);
}));
runBatchedCursor(Se, ie, _.descending, fe + de, onBatch);
}
}
function checkBlobSupport(_) {
return new Promise((function(ee) {
var ne = createBlob2([ "" ]), ie = _.objectStore(DETECT_BLOB_SUPPORT_STORE).put(ne, "key");
ie.onsuccess = function() {
var _ = navigator.userAgent.match(/Chrome\/(\d+)/), ne = navigator.userAgent.match(/Edge\//);
ee(ne || !_ || parseInt(_[1], 10) >= 43);
};
ie.onerror = _.onabort = function(_) {
_.preventDefault();
_.stopPropagation();
ee(false);
};
})).catch((function() {
return false;
}));
}
function countDocs(_, ee) {
_.objectStore(DOC_STORE).index("deletedOrLocal").count(IDBKeyRange.only("0")).onsuccess = function(_) {
ee(_.target.result);
};
}
var running = false, queue = [];
function tryCode(_, ee, ne, ie) {
try {
_(ee, ne);
} catch (_) {
ie.emit("error", _);
}
}
function applyNext() {
if (!running && queue.length) {
running = true;
queue.shift()();
}
}
function enqueueTask(_, ee, ne) {
queue.push((function runAction() {
_((function runCallback(_, ie) {
tryCode(ee, _, ie, ne);
running = false;
(0, import_immediate.default)((function runNext() {
applyNext(ne);
}));
}));
}));
applyNext();
}
function changes(_, ee, ne, ie) {
if ((_ = clone(_)).continuous) {
var re = ne + ":" + uuid();
changesHandler$1.addListener(ne, re, ee, _);
changesHandler$1.notify(ne);
return {
cancel: function() {
changesHandler$1.removeListener(ne, re);
}
};
}
var se = _.doc_ids && new ExportedSet(_.doc_ids);
_.since = _.since || 0;
var oe = _.since, le = "limit" in _ ? _.limit : -1;
if (0 === le) le = 1;
var ue, de, fe, he, pe = [], ge = 0, me = filterChange(_), ye = new ExportedMap;
function onGetMetadata(_, ee, ne, ie) {
if (ne.seq !== ee) return ie();
if (ne.winningRev === _._rev) return ie(ne, _);
var re = _._id + "::" + ne.winningRev;
he.get(re).onsuccess = function(_) {
ie(ne, decodeDoc(_.target.result));
};
}
function finish() {
_.complete(null, {
results: pe,
last_seq: oe
});
}
var ve = [ DOC_STORE, BY_SEQ_STORE ];
if (_.attachments) ve.push(ATTACH_STORE);
var Se = openTransactionSafely(ie, ve, "readonly");
if (Se.error) return _.complete(Se.error);
(ue = Se.txn).onabort = idbError(_.complete);
ue.oncomplete = function onTxnComplete() {
if (!_.continuous && _.attachments) postProcessAttachments(pe).then(finish); else finish();
};
de = ue.objectStore(BY_SEQ_STORE);
fe = ue.objectStore(DOC_STORE);
he = de.index("_doc_id_rev");
runBatchedCursor(de, _.since && !_.descending ? IDBKeyRange.lowerBound(_.since, true) : null, _.descending, le, (function onBatch(ee, ne, ie) {
if (ie && ee.length) {
var re = new Array(ee.length), de = new Array(ee.length), he = 0;
ne.forEach((function(ne, oe) {
(function fetchWinningDocAndMetadata(_, ee, ne) {
if (se && !se.has(_._id)) return ne();
var ie = ye.get(_._id);
if (ie) return onGetMetadata(_, ee, ie, ne);
fe.get(_._id).onsuccess = function(re) {
ie = decodeMetadata(re.target.result);
ye.set(_._id, ie);
onGetMetadata(_, ee, ie, ne);
};
})(decodeDoc(ne), ee[oe], (function(ne, se) {
de[oe] = ne;
re[oe] = se;
if (++he === ee.length) (function onBatchDone() {
for (var ee = [], ne = 0, se = re.length; ne < se && ge !== le; ne++) {
var oe = re[ne];
if (oe) {
var ue = de[ne];
ee.push(processMetadataAndWinningDoc(ue, oe));
}
}
Promise.all(ee).then((function(ee) {
for (var ne = 0, ie = ee.length; ne < ie; ne++) if (ee[ne]) _.onChange(ee[ne]);
})).catch(_.complete);
if (ge !== le) ie.continue();
})();
}));
}));
}
function processMetadataAndWinningDoc(ee, ne) {
var ie = _.processChange(ne, ee, _);
oe = ie.seq = ee.seq;
var re = me(ie);
if ("object" == typeof re) return Promise.reject(re);
if (!re) return Promise.resolve();
ge++;
if (_.return_docs) pe.push(ie);
if (_.attachments && _.include_docs) return new Promise((function(ee) {
fetchAttachmentsIfNecessary(ne, _, ue, (function() {
postProcessAttachments([ ie ], _.binary).then((function() {
ee(ie);
}));
}));
})); else return Promise.resolve(ie);
}
}));
}
var blobSupportPromise, cachedDBs = new ExportedMap, openReqList = new ExportedMap;
function IdbPouch(_, ee) {
var ne = this;
enqueueTask((function(ee) {
init(ne, _, ee);
}), ee, ne.constructor);
}
function init(_, ee, ne) {
var ie = ee.name, re = null, se = null;
_._meta = null;
function enrichCallbackError(_) {
return function(ee, ne) {
if (ee && ee instanceof Error && !ee.reason) if (se) ee.reason = se;
_(ee, ne);
};
}
function addDeletedOrLocalIndex(_, ee) {
var ne = _.objectStore(DOC_STORE);
ne.createIndex("deletedOrLocal", "deletedOrLocal", {
unique: false
});
ne.openCursor().onsuccess = function(_) {
var ie = _.target.result;
if (ie) {
var re = ie.value, se = isDeleted(re);
re.deletedOrLocal = se ? "1" : "0";
ne.put(re);
ie.continue();
} else ee();
};
}
function migrateLocalStore(_, ee) {
var ne = _.objectStore(LOCAL_STORE), ie = _.objectStore(DOC_STORE), re = _.objectStore(BY_SEQ_STORE);
ie.openCursor().onsuccess = function(_) {
var se = _.target.result;
if (se) {
var oe = se.value, le = oe.id, ue = isLocalId(le), de = winningRev(oe);
if (ue) {
var fe = le + "::" + de, he = le + "::", pe = le + "::~", ge = re.index("_doc_id_rev"), me = IDBKeyRange.bound(he, pe, false, false), ye = ge.openCursor(me);
ye.onsuccess = function(_) {
if (!(ye = _.target.result)) {
ie.delete(se.primaryKey);
se.continue();
} else {
var ee = ye.value;
if (ee._doc_id_rev === fe) ne.put(ee);
re.delete(ye.primaryKey);
ye.continue();
}
};
} else se.continue();
} else if (ee) ee();
};
}
function migrateAttsAndSeqs(_, ee) {
var ne = _.objectStore(BY_SEQ_STORE), ie = _.objectStore(ATTACH_STORE), re = _.objectStore(ATTACH_AND_SEQ_STORE);
ie.count().onsuccess = function(_) {
if (!_.target.result) return ee();
ne.openCursor().onsuccess = function(_) {
var ne = _.target.result;
if (!ne) return ee();
for (var ie = ne.value, se = ne.primaryKey, oe = Object.keys(ie._attachments || {}), le = {}, ue = 0; ue < oe.length; ue++) le[ie._attachments[oe[ue]].digest] = true;
var de = Object.keys(le);
for (ue = 0; ue < de.length; ue++) {
var fe = de[ue];
re.put({
seq: se,
digestSeq: fe + "::" + se
});
}
ne.continue();
};
};
}
function migrateMetadata(_) {
var ee = _.objectStore(BY_SEQ_STORE), ne = _.objectStore(DOC_STORE);
ne.openCursor().onsuccess = function(_) {
var ie = _.target.result;
if (ie) {
var re = function decodeMetadataCompat(_) {
if (!_.data) {
_.deleted = "1" === _.deletedOrLocal;
return _;
}
return decodeMetadata(_);
}(ie.value);
re.winningRev = re.winningRev || winningRev(re);
if (re.seq) return onGetMetadataSeq();
(function fetchMetadataSeq() {
var _ = re.id + "::", ne = re.id + "::", ie = ee.index("_doc_id_rev").openCursor(IDBKeyRange.bound(_, ne)), se = 0;
ie.onsuccess = function(_) {
var ee = _.target.result;
if (!ee) {
re.seq = se;
return onGetMetadataSeq();
}
var ne = ee.primaryKey;
if (ne > se) se = ne;
ee.continue();
};
})();
}
function onGetMetadataSeq() {
var _ = encodeMetadata(re, re.winningRev, re.deleted);
ne.put(_).onsuccess = function() {
ie.continue();
};
}
};
}
_._remote = false;
_.type = function() {
return "idb";
};
_._id = toPromise((function(ee) {
ee(null, _._meta.instanceId);
}));
_._bulkDocs = function idb_bulkDocs(ne, ie, se) {
idbBulkDocs(ee, ne, ie, _, re, enrichCallbackError(se));
};
_._get = function idb_get(_, ee, ne) {
var ie, se, oe, le = ee.ctx;
if (!le) {
var ue = openTransactionSafely(re, [ DOC_STORE, BY_SEQ_STORE, ATTACH_STORE ], "readonly");
if (ue.error) return ne(ue.error);
le = ue.txn;
}
function finish() {
ne(oe, {
doc: ie,
metadata: se,
ctx: le
});
}
le.objectStore(DOC_STORE).get(_).onsuccess = function(_) {
if (!(se = decodeMetadata(_.target.result))) {
oe = createError(MISSING_DOC, "missing");
return finish();
}
var ne;
if (!ee.rev) {
ne = se.winningRev;
if (isDeleted(se)) {
oe = createError(MISSING_DOC, "deleted");
return finish();
}
} else ne = ee.latest ? latest(ee.rev, se) : ee.rev;
var re = le.objectStore(BY_SEQ_STORE), ue = se.id + "::" + ne;
re.index("_doc_id_rev").get(ue).onsuccess = function(_) {
if (ie = _.target.result) ie = decodeDoc(ie);
if (!ie) {
oe = createError(MISSING_DOC, "missing");
return finish();
}
finish();
};
};
};
_._getAttachment = function(_, ee, ne, ie, se) {
var oe;
if (ie.ctx) oe = ie.ctx; else {
var le = openTransactionSafely(re, [ DOC_STORE, BY_SEQ_STORE, ATTACH_STORE ], "readonly");
if (le.error) return se(le.error);
oe = le.txn;
}
var ue = ne.digest, de = ne.content_type;
oe.objectStore(ATTACH_STORE).get(ue).onsuccess = function(_) {
readBlobData(_.target.result.body, de, ie.binary, (function(_) {
se(null, _);
}));
};
};
_._info = function idb_info(ee) {
var ne, ie, se = openTransactionSafely(re, [ META_STORE, BY_SEQ_STORE ], "readonly");
if (se.error) return ee(se.error);
var oe = se.txn;
oe.objectStore(META_STORE).get(META_STORE).onsuccess = function(_) {
ie = _.target.result.docCount;
};
oe.objectStore(BY_SEQ_STORE).openCursor(null, "prev").onsuccess = function(_) {
var ee = _.target.result;
ne = ee ? ee.key : 0;
};
oe.oncomplete = function() {
ee(null, {
doc_count: ie,
update_seq: ne,
idb_attachment_format: _._meta.blobSupport ? "binary" : "base64"
});
};
};
_._allDocs = function idb_allDocs(_, ee) {
idbAllDocs(_, re, enrichCallbackError(ee));
};
_._changes = function idbChanges2(ee) {
return changes(ee, _, ie, re);
};
_._close = function(_) {
re.close();
cachedDBs.delete(ie);
_();
};
_._getRevisionTree = function(_, ee) {
var ne = openTransactionSafely(re, [ DOC_STORE ], "readonly");
if (ne.error) return ee(ne.error);
ne.txn.objectStore(DOC_STORE).get(_).onsuccess = function(_) {
var ne = decodeMetadata(_.target.result);
if (!ne) ee(createError(MISSING_DOC)); else ee(null, ne.rev_tree);
};
};
_._doCompaction = function(_, ee, ne) {
var ie = openTransactionSafely(re, [ DOC_STORE, BY_SEQ_STORE, ATTACH_STORE, ATTACH_AND_SEQ_STORE ], "readwrite");
if (ie.error) return ne(ie.error);
var se = ie.txn;
se.objectStore(DOC_STORE).get(_).onsuccess = function(ne) {
var ie = decodeMetadata(ne.target.result);
traverseRevTree(ie.rev_tree, (function(_, ne, ie, re, se) {
var oe = ne + "-" + ie;
if (-1 !== ee.indexOf(oe)) se.status = "missing";
}));
compactRevs(ee, _, se);
var re = ie.winningRev, oe = ie.deleted;
se.objectStore(DOC_STORE).put(encodeMetadata(ie, re, oe));
};
se.onabort = idbError(ne);
se.oncomplete = function() {
ne();
};
};
_._getLocal = function(_, ee) {
var ne = openTransactionSafely(re, [ LOCAL_STORE ], "readonly");
if (ne.error) return ee(ne.error);
var ie = ne.txn.objectStore(LOCAL_STORE).get(_);
ie.onerror = idbError(ee);
ie.onsuccess = function(_) {
var ne = _.target.result;
if (!ne) ee(createError(MISSING_DOC)); else {
delete ne["_doc_id_rev"];
ee(null, ne);
}
};
};
_._putLocal = function(_, ee, ne) {
if ("function" == typeof ee) {
ne = ee;
ee = {};
}
delete _._revisions;
var ie = _._rev, se = _._id;
if (!ie) _._rev = "0-1"; else _._rev = "0-" + (parseInt(ie.split("-")[1], 10) + 1);
var oe, le = ee.ctx;
if (!le) {
var ue = openTransactionSafely(re, [ LOCAL_STORE ], "readwrite");
if (ue.error) return ne(ue.error);
(le = ue.txn).onerror = idbError(ne);
le.oncomplete = function() {
if (oe) ne(null, oe);
};
}
var de, fe = le.objectStore(LOCAL_STORE);
if (ie) (de = fe.get(se)).onsuccess = function(re) {
var se = re.target.result;
if (!se || se._rev !== ie) ne(createError(REV_CONFLICT)); else fe.put(_).onsuccess = function() {
oe = {
ok: true,
id: _._id,
rev: _._rev
};
if (ee.ctx) ne(null, oe);
};
}; else {
(de = fe.add(_)).onerror = function(_) {
ne(createError(REV_CONFLICT));
_.preventDefault();
_.stopPropagation();
};
de.onsuccess = function() {
oe = {
ok: true,
id: _._id,
rev: _._rev
};
if (ee.ctx) ne(null, oe);
};
}
};
_._removeLocal = function(_, ee, ne) {
if ("function" == typeof ee) {
ne = ee;
ee = {};
}
var ie, se = ee.ctx;
if (!se) {
var oe = openTransactionSafely(re, [ LOCAL_STORE ], "readwrite");
if (oe.error) return ne(oe.error);
(se = oe.txn).oncomplete = function() {
if (ie) ne(null, ie);
};
}
var le = _._id, ue = se.objectStore(LOCAL_STORE), de = ue.get(le);
de.onerror = idbError(ne);
de.onsuccess = function(re) {
var se = re.target.result;
if (!se || se._rev !== _._rev) ne(createError(MISSING_DOC)); else {
ue.delete(le);
ie = {
ok: true,
id: le,
rev: "0-0"
};
if (ee.ctx) ne(null, ie);
}
};
};
_._destroy = function(_, ee) {
changesHandler$1.removeAllListeners(ie);
var ne = openReqList.get(ie);
if (ne && ne.result) {
ne.result.close();
cachedDBs.delete(ie);
}
var re = indexedDB.deleteDatabase(ie);
re.onsuccess = function() {
openReqList.delete(ie);
if (hasLocalStorage() && ie in localStorage) delete localStorage[ie];
ee(null, {
ok: true
});
};
re.onerror = idbError(ee);
};
var oe = cachedDBs.get(ie);
if (oe) {
re = oe.idb;
_._meta = oe.global;
return (0, import_immediate.default)((function() {
ne(null, _);
}));
}
var le = indexedDB.open(ie, ADAPTER_VERSION);
openReqList.set(ie, le);
le.onupgradeneeded = function(_) {
var ee = _.target.result;
if (_.oldVersion < 1) return function createSchema(_) {
var ee = _.createObjectStore(DOC_STORE, {
keyPath: "id"
});
_.createObjectStore(BY_SEQ_STORE, {
autoIncrement: true
}).createIndex("_doc_id_rev", "_doc_id_rev", {
unique: true
});
_.createObjectStore(ATTACH_STORE, {
keyPath: "digest"
});
_.createObjectStore(META_STORE, {
keyPath: "id",
autoIncrement: false
});
_.createObjectStore(DETECT_BLOB_SUPPORT_STORE);
ee.createIndex("deletedOrLocal", "deletedOrLocal", {
unique: false
});
_.createObjectStore(LOCAL_STORE, {
keyPath: "_id"
});
var ne = _.createObjectStore(ATTACH_AND_SEQ_STORE, {
autoIncrement: true
});
ne.createIndex("seq", "seq");
ne.createIndex("digestSeq", "digestSeq", {
unique: true
});
}(ee);
var ne = _.currentTarget.transaction;
if (_.oldVersion < 3) (function createLocalStoreSchema(_) {
_.createObjectStore(LOCAL_STORE, {
keyPath: "_id"
}).createIndex("_doc_id_rev", "_doc_id_rev", {
unique: true
});
})(ee);
if (_.oldVersion < 4) (function addAttachAndSeqStore(_) {
var ee = _.createObjectStore(ATTACH_AND_SEQ_STORE, {
autoIncrement: true
});
ee.createIndex("seq", "seq");
ee.createIndex("digestSeq", "digestSeq", {
unique: true
});
})(ee);
var ie = [ addDeletedOrLocalIndex, migrateLocalStore, migrateAttsAndSeqs, migrateMetadata ], re = _.oldVersion;
(function next() {
var _ = ie[re - 1];
re++;
if (_) _(ne, next);
})();
};
le.onsuccess = function(ee) {
(re = ee.target.result).onversionchange = function() {
re.close();
cachedDBs.delete(ie);
};
re.onabort = function(_) {
guardedConsole("error", "Database has a global failure", _.target.error);
se = _.target.error;
re.close();
cachedDBs.delete(ie);
};
var oe, le, ue, de, fe = re.transaction([ META_STORE, DETECT_BLOB_SUPPORT_STORE, DOC_STORE ], "readwrite"), he = false;
function completeSetup() {
if ("undefined" != typeof ue && he) {
_._meta = {
name: ie,
instanceId: de,
blobSupport: ue
};
cachedDBs.set(ie, {
idb: re,
global: _._meta
});
ne(null, _);
}
}
function storeMetaDocIfReady() {
if ("undefined" != typeof le && "undefined" != typeof oe) {
var _ = ie + "_id";
if (_ in oe) de = oe[_]; else oe[_] = de = uuid();
oe.docCount = le;
fe.objectStore(META_STORE).put(oe);
}
}
fe.objectStore(META_STORE).get(META_STORE).onsuccess = function(_) {
oe = _.target.result || {
id: META_STORE
};
storeMetaDocIfReady();
};
countDocs(fe, (function(_) {
le = _;
storeMetaDocIfReady();
}));
if (!blobSupportPromise) blobSupportPromise = checkBlobSupport(fe);
blobSupportPromise.then((function(_) {
ue = _;
completeSetup();
}));
fe.oncomplete = function() {
he = true;
completeSetup();
};
fe.onabort = idbError(ne);
};
le.onerror = function(_) {
var ee = _.target.error && _.target.error.message;
if (!ee) ee = "Failed to open indexedDB, are you in private browsing mode?"; else if (-1 !== ee.indexOf("stored database is a higher version")) ee = new Error('This DB was created with the newer "indexeddb" adapter, but you are trying to open it with the older "idb" adapter');
guardedConsole("error", ee);
ne(createError(IDB_ERROR, ee));
};
}
IdbPouch.valid = function() {
try {
return "undefined" != typeof indexedDB && "undefined" != typeof IDBKeyRange;
} catch (_) {
return false;
}
};
function index(_) {
_.adapter("idb", IdbPouch, true);
}
var index_es_default2 = index, IDB_NULL = Number.MIN_SAFE_INTEGER, IDB_FALSE = Number.MIN_SAFE_INTEGER + 1, IDB_TRUE = Number.MIN_SAFE_INTEGER + 2, TEST_KEY_INVALID = /^[^a-zA-Z_$]|[^a-zA-Z0-9_$]+/, TEST_PATH_INVALID = /\\.|(^|\.)[^a-zA-Z_$]|[^a-zA-Z0-9_$.]+/;
function needsSanitise(_, ee) {
if (ee) return TEST_PATH_INVALID.test(_); else return TEST_KEY_INVALID.test(_);
}
var KEY_INVALID = new RegExp(TEST_KEY_INVALID.source, "g"), PATH_INVALID = new RegExp(TEST_PATH_INVALID.source, "g"), SLASH = "\\".charCodeAt(0), IS_DOT = ".".charCodeAt(0);
function sanitise(_, ee) {
var correctCharacters = function(_) {
for (var ne = "", ie = 0; ie < _.length; ie++) {
var re = _.charCodeAt(ie);
if (re === IS_DOT && ee && 0 === ie) ne += "."; else if (re === SLASH && ee) continue; else ne += "_c" + re + "_";
}
return ne;
};
if (ee) return _.replace(PATH_INVALID, correctCharacters); else return _.replace(KEY_INVALID, correctCharacters);
}
function needsRewrite(_) {
for (var ee of Object.keys(_)) if (needsSanitise(ee)) return true; else if (null === _[ee] || "boolean" == typeof _[ee]) return true; else if ("object" == typeof _[ee]) return needsRewrite(_[ee]);
}
function rewrite(_) {
if (!needsRewrite(_)) return false;
var ee = Array.isArray(_), ne = ee ? [] : {};
Object.keys(_).forEach((function(ie) {
var re = ee ? ie : sanitise(ie);
if (null === _[ie]) ne[re] = IDB_NULL; else if ("boolean" == typeof _[ie]) ne[re] = _[ie] ? IDB_TRUE : IDB_FALSE; else if ("object" == typeof _[ie]) ne[re] = rewrite(_[ie]); else ne[re] = _[ie];
}));
return ne;
}
var DOC_STORE2 = "docs", META_STORE2 = "meta";
function idbError2(_) {
return function(ee) {
var ne = "unknown_error";
if (ee.target && ee.target.error) ne = ee.target.error.name || ee.target.error.message;
_(createError(IDB_ERROR, ne, ee.type));
};
}
function processAttachment(_, ee, ne, ie) {
delete ne._attachments[_].stub;
if (ie) {
ne._attachments[_].data = ee.attachments[ne._attachments[_].digest].data;
return Promise.resolve();
}
return new Promise((function(ie) {
readAsBinaryString(ee.attachments[ne._attachments[_].digest].data, (function(ee) {
ne._attachments[_].data = thisBtoa(ee);
delete ne._attachments[_].length;
ie();
}));
}));
}
function rawIndexFields(_, ee) {
return (_.views[ee].options && _.views[ee].options.def && _.views[ee].options.def.fields || []).map((function(_) {
if ("string" == typeof _) return _; else return Object.keys(_)[0];
}));
}
function isPartialFilterView(_, ee) {
return ee in _.views && _.views[ee].options && _.views[ee].options.def && _.views[ee].options.def.partial_filter_selector;
}
function naturalIndexName(_) {
return "_find_idx/" + _.join("/");
}
function correctIndexFields(_) {
return [ "deleted" ].concat(_.map((function(_) {
if ([ "_id", "_rev", "_deleted", "_attachments" ].includes(_)) return _.substr(1); else return "data." + sanitise(_, true);
})));
}
var POUCHDB_IDB_VERSION = 1, versionMultiplier = Math.pow(10, 13);
function createIdbVersion() {
return versionMultiplier * POUCHDB_IDB_VERSION + (new Date).getTime();
}
function getPouchDbVersion(_) {
return Math.floor(_ / versionMultiplier);
}
function maintainNativeIndexes(_, ee) {
var ne = _.transaction.objectStore(DOC_STORE2);
ne.getAll(IDBKeyRange.bound("_design/", "_design/")).onsuccess = function(_) {
var ie = _.target.result, re = Array.from(ne.indexNames), se = ie.filter((function(_) {
return 0 === _.deleted && _.revs[_.rev].data.views;
})).map((function(_) {
return _.revs[_.rev].data;
})).reduce((function(_, ee) {
return Object.keys(ee.views).reduce((function(_, ne) {
var ie = rawIndexFields(ee, ne);
if (ie && ie.length > 0) _[naturalIndexName(ie)] = correctIndexFields(ie);
return _;
}), _);
}), {}), oe = Object.keys(se), le = [ "seq" ];
re.forEach((function(_) {
if (-1 === le.indexOf(_) && -1 === oe.indexOf(_)) ne.deleteIndex(_);
}));
var ue = oe.filter((function(_) {
return -1 === re.indexOf(_);
}));
try {
ue.forEach((function(_) {
ne.createIndex(_, se[_]);
}));
} catch (_) {
ee(_);
}
};
}
function upgradePouchDbSchema(_, ee) {
if (ee < 1) {
_.createObjectStore(DOC_STORE2, {
keyPath: "id"
}).createIndex("seq", "seq", {
unique: true
});
_.createObjectStore(META_STORE2, {
keyPath: "id"
});
}
}
function openDatabase(_, ee, ne, ie, re) {
var se = ne.versionchanged ? indexedDB.open(ne.name) : indexedDB.open(ne.name, createIdbVersion());
se.onupgradeneeded = function(_) {
if (_.oldVersion > 0 && _.oldVersion < versionMultiplier) throw new Error('Incorrect adapter: you should specify the "idb" adapter to open this DB'); else if (0 === _.oldVersion && _.newVersion < versionMultiplier) {
indexedDB.deleteDatabase(ne.name);
throw new Error("Database was deleted while open");
}
upgradePouchDbSchema(_.target.result, getPouchDbVersion(_.oldVersion));
maintainNativeIndexes(se, re);
};
se.onblocked = function(_) {
console.error("onblocked, this should never happen", _);
};
se.onsuccess = function(ee) {
var re = ee.target.result;
re.onabort = function(ee) {
console.error("Database has a global failure", ee.target.error);
delete _[ne.name];
re.close();
};
re.onversionchange = function() {
console.log("Database was made stale, closing handle");
_[ne.name].versionchanged = true;
re.close();
};
re.onclose = function() {
console.log("Database was made stale, closing handle");
if (ne.name in _) _[ne.name].versionchanged = true;
};
var se = {
id: META_STORE2
}, oe = re.transaction([ META_STORE2 ], "readwrite");
oe.oncomplete = function() {
ie({
idb: re,
metadata: se
});
};
var le = oe.objectStore(META_STORE2);
le.get(META_STORE2).onsuccess = function(_) {
var ee = false;
if (!("doc_count" in (se = _.target.result || se))) {
ee = true;
se.doc_count = 0;
}
if (!("seq" in se)) {
ee = true;
se.seq = 0;
}
if (!("db_uuid" in se)) {
ee = true;
se.db_uuid = uuid();
}
if (ee) le.put(se);
};
};
se.onerror = function(_) {
re(_.target.error);
};
}
function setup(_, ee, ne) {
if (!_[ne.name] || _[ne.name].versionchanged) {
ne.versionchanged = _[ne.name] && _[ne.name].versionchanged;
_[ne.name] = new Promise((function(ie, re) {
openDatabase(_, ee, ne, ie, re);
}));
}
return _[ne.name];
}
function info(_, ee) {
ee(null, {
doc_count: _.doc_count,
update_seq: _.seq
});
}
function get(_, ee, ne, ie) {
if (_.error) return ie(_.error);
_.txn.objectStore(DOC_STORE2).get(ee).onsuccess = function(ee) {
var re, se = ee.target.result;
if (!ne.rev) re = se && se.rev; else re = ne.latest ? latest(ne.rev, se) : ne.rev;
if (se && (!se.deleted || ne.rev) && re in se.revs) {
var oe = se.revs[re].data;
oe._id = se.id;
oe._rev = re;
ie(null, {
doc: oe,
metadata: se,
ctx: _
});
} else ie(createError(MISSING_DOC, "missing"));
};
}
function parseAttachment(_, ee, ne) {
if (ee.binary) return ne(null, _); else readAsBinaryString(_, (function(_) {
ne(null, thisBtoa(_));
}));
}
function getAttachment(_, ee, ne, ie, re, se) {
if (_.error) return se(_.error);
var oe;
_.txn.objectStore(DOC_STORE2).get(ee).onsuccess = function(_) {
var ee = _.target.result, ie = ee.revs[re.rev || ee.rev].data._attachments[ne].digest;
oe = ee.attachments[ie].data;
};
_.txn.oncomplete = function() {
parseAttachment(oe, re, se);
};
_.txn.onabort = se;
}
function bulkDocs(_, ee, ne, ie, re, se, oe) {
var le, ue, de, fe = [], he = [], pe = re.revs_limit || 1e3, ge = -1 === re.name.indexOf("-mrview-");
const me = re.auto_compaction;
function docsRevsLimit(_) {
return /^_local/.test(_.id) ? 1 : pe;
}
function revHasAttachment(_, ee, ne) {
return _.revs[ee] && _.revs[ee].data._attachments && Object.values(_.revs[ee].data._attachments).find((function(_) {
return _.digest === ne;
}));
}
function convertDocFormat(_) {
var ee = {
id: _.metadata.id,
rev: _.metadata.rev,
rev_tree: _.metadata.rev_tree,
revs: _.metadata.revs || {}
};
ee.revs[ee.rev] = {
data: _.data,
deleted: _.metadata.deleted
};
return ee;
}
function updateSeq(_) {
if (_ === de) le.objectStore(META_STORE2).put(ie);
}
for (var ye = 0, ve = ee.docs.length; ye < ve; ye++) {
var Se;
try {
Se = parseDoc(ee.docs[ye], ne.new_edits, re);
} catch (_) {
Se = _;
}
if (Se.error) return oe(Se);
he.push(convertDocFormat(Se));
}
(function preProcessAttachments() {
var _ = he.map((function(_) {
var ee = _.revs[_.rev].data;
if (!ee._attachments) return Promise.resolve(ee);
var ne = Object.keys(ee._attachments).map((function(_) {
ee._attachments[_].name = _;
return function preProcessAttachment(_) {
if (_.stub) return Promise.resolve(_);
var ee;
if ("string" == typeof _.data) {
if ((ee = function parseBase642(_) {
try {
return atob(_);
} catch (_) {
return {
error: createError(BAD_ARG, "Attachment is not a valid base64 string")
};
}
}(_.data)).error) return Promise.reject(ee.error);
_.data = binStringToBluffer(ee, _.content_type);
} else ee = _.data;
return new Promise((function(ne) {
binaryMd5(ee, (function(ie) {
_.digest = "md5-" + ie;
_.length = ee.size || ee.length || 0;
ne(_);
}));
}));
}(ee._attachments[_]);
}));
return Promise.all(ne).then((function(_) {
var ne = {};
_.forEach((function(_) {
ne[_.name] = _;
delete _.name;
}));
ee._attachments = ne;
return ee;
}));
}));
return Promise.all(_);
})().then((function() {
_._openTransactionSafely([ DOC_STORE2, META_STORE2 ], "readwrite", (function(_, ee) {
if (_) return oe(_);
(le = ee).onabort = function() {
oe(ue || createError(UNKNOWN_ERROR, "transaction was aborted"));
};
le.ontimeout = idbError2(oe);
le.oncomplete = function() {
se.notify(re.name);
oe(null, fe);
};
(function fetchExistingDocs(_, ee) {
var se = 0, oe = {};
function readDone(le) {
if (le.target.result) oe[le.target.result.id] = le.target.result;
if (++se === ee.length) (function processDocs2(_, ee, se) {
ee.forEach((function(ee, oe) {
var le;
if ("was_delete" in ne && !Object.prototype.hasOwnProperty.call(se, ee.id)) le = createError(MISSING_DOC, "deleted"); else if (ne.new_edits && !Object.prototype.hasOwnProperty.call(se, ee.id) && function rootIsMissing2(_) {
return "missing" === _.rev_tree[0].ids[1].status;
}(ee)) le = createError(REV_CONFLICT); else if (Object.prototype.hasOwnProperty.call(se, ee.id)) {
le = function update2(_, ee, ie) {
if (ee.rev in ie.revs && !ne.new_edits) return false;
var se = /^1-/.test(ee.rev);
if (ie.deleted && !ee.deleted && ne.new_edits && se) {
var oe = ee.revs[ee.rev].data;
oe._rev = ie.rev;
oe._id = ie.id;
ee = convertDocFormat(parseDoc(oe, ne.new_edits, re));
}
var le = merge(ie.rev_tree, ee.rev_tree[0], docsRevsLimit(ee));
ee.stemmedRevs = le.stemmedRevs;
ee.rev_tree = le.tree;
var ue = ie.revs;
ue[ee.rev] = ee.revs[ee.rev];
ee.revs = ue;
ee.attachments = ie.attachments;
if (ne.new_edits && (ie.deleted && ee.deleted || !ie.deleted && "new_leaf" !== le.conflicts || ie.deleted && !ee.deleted && "new_branch" === le.conflicts || ie.rev === ee.rev)) return createError(REV_CONFLICT);
ee.wasDeleted = ie.deleted;
return ee;
}(0, ee, se[ee.id]);
if (false == le) return;
} else {
var he = merge([], ee.rev_tree[0], docsRevsLimit(ee));
ee.rev_tree = he.tree;
ee.stemmedRevs = he.stemmedRevs;
(le = ee).isNewDoc = true;
le.wasDeleted = ee.revs[ee.rev].deleted ? 1 : 0;
}
if (le.error) fe[oe] = le; else {
se[le.id] = le;
de = oe;
(function write(_, ee, ne) {
var re = winningRev(ee), se = ee.rev, oe = /^_local/.test(ee.id), le = ee.revs[re].data;
const de = ee.isNewDoc;
if (ge) {
var he = rewrite(le);
if (he) {
ee.data = he;
delete ee.data._attachments;
} else ee.data = le;
} else ee.data = le;
ee.rev = re;
ee.deleted = ee.revs[re].deleted ? 1 : 0;
if (!oe) {
ee.seq = ++ie.seq;
var pe = 0;
if (ee.isNewDoc) pe = ee.deleted ? 0 : 1; else if (ee.wasDeleted !== ee.deleted) pe = ee.deleted ? -1 : 1;
ie.doc_count += pe;
}
delete ee.isNewDoc;
delete ee.wasDeleted;
let ye = ee.stemmedRevs || [];
if (me && !de) {
const _ = compactTree(ee);
if (_.length) ye = ye.concat(_);
}
if (ye.length) ye.forEach((function(_) {
delete ee.revs[_];
}));
delete ee.stemmedRevs;
if (!("attachments" in ee)) ee.attachments = {};
if (le._attachments) for (var ve in le._attachments) {
var Se = le._attachments[ve];
if (Se.stub) {
if (!(Se.digest in ee.attachments)) {
ue = createError(MISSING_STUB);
_.abort();
return;
}
if (revHasAttachment(ee, se, Se.digest)) ee.attachments[Se.digest].revs[se] = true;
} else {
ee.attachments[Se.digest] = Se;
ee.attachments[Se.digest].revs = {};
ee.attachments[Se.digest].revs[se] = true;
le._attachments[ve] = {
stub: true,
digest: Se.digest,
content_type: Se.content_type,
length: Se.length,
revpos: parseInt(se, 10)
};
}
}
if (!oe || !ee.deleted) _.objectStore(DOC_STORE2).put(ee).onsuccess = function() {
fe[ne] = {
ok: true,
id: ee.id,
rev: se
};
updateSeq(ne);
}; else {
_.objectStore(DOC_STORE2).delete(ee.id).onsuccess = function() {
fe[ne] = {
ok: true,
id: ee.id,
rev: "0-0"
};
};
updateSeq(ne);
}
})(_, le, oe);
}
}));
})(_, ee, oe);
}
ee.forEach((function(ee) {
_.objectStore(DOC_STORE2).get(ee.id).onsuccess = readDone;
}));
})(le, he);
}));
})).catch((function(_) {
oe(_);
}));
}
function allDocsKeys2(_, ee, ne) {
var ie = new Array(_.length), re = 0;
_.forEach((function(se, oe) {
ee.get(se).onsuccess = function(ee) {
if (ee.target.result) ie[oe] = ee.target.result; else ie[oe] = {
key: se,
error: "not_found"
};
if (++re === _.length) ie.forEach((function(_) {
ne(_);
}));
};
}));
}
function createKeyRange2(_, ee, ne, ie, re) {
try {
if (_ && ee) if (re) return IDBKeyRange.bound(ee, _, !ne, false); else return IDBKeyRange.bound(_, ee, false, !ne); else if (_) if (re) return IDBKeyRange.upperBound(_); else return IDBKeyRange.lowerBound(_); else if (ee) if (re) return IDBKeyRange.lowerBound(ee, !ne); else return IDBKeyRange.upperBound(ee, !ne); else if (ie) return IDBKeyRange.only(ie);
} catch (_) {
return {
error: _
};
}
return null;
}
function handleKeyRangeError(_, ee, ne, ie) {
if ("DataError" === ne.name && 0 === ne.code) {
var re = {
total_rows: ee.doc_count,
offset: _.skip,
rows: []
};
if (_.update_seq) re.update_seq = ee.seq;
return ie(null, re);
}
ie(createError(IDB_ERROR, ne.name, ne.message));
}
function allDocs(_, ee, ne, ie) {
if (_.error) return ie(_.error);
if (0 === ne.limit) {
var re = {
total_rows: ee.doc_count,
offset: ne.skip,
rows: []
};
if (ne.update_seq) re.update_seq = ee.seq;
return ie(null, re);
}
var se, oe = [], le = [], ue = "startkey" in ne ? ne.startkey : false, de = "endkey" in ne ? ne.endkey : false, fe = "key" in ne ? ne.key : false, he = "keys" in ne ? ne.keys : false, pe = ne.skip || 0, ge = "number" == typeof ne.limit ? ne.limit : -1, me = false !== ne.inclusive_end, ye = "descending" in ne && ne.descending ? "prev" : null;
if (!he) if ((se = createKeyRange2(ue, de, me, fe, ye)) && se.error) return handleKeyRangeError(ne, ee, se.error, ie);
var ve = _.txn.objectStore(DOC_STORE2);
_.txn.oncomplete = function onTxnComplete() {
Promise.all(le).then((function() {
var _ = {
total_rows: ee.doc_count,
offset: 0,
rows: oe
};
if (ne.update_seq) _.update_seq = ee.seq;
ie(null, _);
}));
};
if (he) return allDocsKeys2(ne.keys, ve, allDocsInner);
function allDocsInner(_) {
if (_.error && he) {
oe.push(_);
return true;
}
var ee = {
id: _.id,
key: _.id,
value: {
rev: _.rev
}
};
if (_.deleted) {
if (he) {
oe.push(ee);
ee.value.deleted = true;
ee.doc = null;
}
} else if (pe-- <= 0) {
oe.push(ee);
if (ne.include_docs) (function include_doc(_, ee) {
var ie = ee.revs[ee.rev].data;
_.doc = ie;
_.doc._id = ee.id;
_.doc._rev = ee.rev;
if (ne.conflicts) {
var re = collectConflicts(ee);
if (re.length) _.doc._conflicts = re;
}
if (ne.attachments && ie._attachments) for (var se in ie._attachments) le.push(processAttachment(se, ee, _.doc, ne.binary));
})(ee, _);
if (0 == --ge) return false;
}
return true;
}
(ye ? ve.openCursor(se, ye) : ve.openCursor(se)).onsuccess = function(_) {
var ee = _.target.result && _.target.result.value;
if (ee) {
if (/^_local/.test(ee.id)) return _.target.result.continue();
if (allDocsInner(ee)) _.target.result.continue();
}
};
}
function changes2(_, ee, ne, ie, re) {
if (_.error) return re.complete(_.error);
if (re.continuous) {
var se = ie.name + ":" + uuid();
ee.addListener(ie.name, se, ne, re);
ee.notify(ie.name);
return {
cancel: function() {
ee.removeListener(ie.name, se);
}
};
}
var oe = "limit" in re ? re.limit : -1;
if (0 === oe) oe = 1;
var le, ue = _.txn.objectStore(DOC_STORE2).index("seq"), de = filterChange(re), fe = 0, he = re.since || 0, pe = [], ge = [];
if (re.descending) le = ue.openCursor(null, "prev"); else le = ue.openCursor(IDBKeyRange.lowerBound(re.since, true));
_.txn.oncomplete = function onTxnComplete() {
Promise.all(ge).then((function() {
re.complete(null, {
results: pe,
last_seq: he
});
}));
};
le.onsuccess = function onReqSuccess(_) {
if (_.target.result) {
var ee = _.target.result, ne = ee.value;
ne.data = ne.revs[ne.rev].data;
ne.data._id = ne.id;
ne.data._rev = ne.rev;
if (ne.deleted) ne.data._deleted = true;
if (re.doc_ids && -1 === re.doc_ids.indexOf(ne.id)) return ee.continue();
var ie = re.processChange(ne.data, ne, re);
ie.seq = ne.seq;
he = ne.seq;
var se = de(ie);
if ("object" == typeof se) return re.complete(se);
if (se) {
fe++;
if (re.return_docs) pe.push(ie);
if (re.include_docs && re.attachments && ne.data._attachments) {
var le = [];
for (var ue in ne.data._attachments) {
var me = processAttachment(ue, ne, ie.doc, re.binary);
le.push(me);
ge.push(me);
}
Promise.all(le).then((function() {
re.onChange(ie);
}));
} else re.onChange(ie);
}
if (fe !== oe) ee.continue();
}
};
}
function getRevisionTree(_, ee, ne) {
if (_.error) return ne(_.error);
_.txn.objectStore(DOC_STORE2).get(ee).onsuccess = function(_) {
if (!_.target.result) ne(createError(MISSING_DOC)); else ne(null, _.target.result.rev_tree);
};
}
function doCompaction(_, ee, ne, ie) {
if (_.error) return ie(_.error);
var re = _.txn.objectStore(DOC_STORE2);
re.get(ee).onsuccess = function(_) {
var ee = _.target.result;
traverseRevTree(ee.rev_tree, (function(_, ee, ie, re, se) {
var oe = ee + "-" + ie;
if (-1 !== ne.indexOf(oe)) se.status = "missing";
}));
var ie = [];
ne.forEach((function(_) {
if (_ in ee.revs) {
if (ee.revs[_].data._attachments) for (var ne in ee.revs[_].data._attachments) ie.push(ee.revs[_].data._attachments[ne].digest);
delete ee.revs[_];
}
}));
ie.forEach((function(_) {
ne.forEach((function(ne) {
delete ee.attachments[_].revs[ne];
}));
if (!Object.keys(ee.attachments[_].revs).length) delete ee.attachments[_];
}));
re.put(ee);
};
_.txn.oncomplete = function() {
ie();
};
}
function destroy(_, ee, ne, ie) {
ne.removeAllListeners(_.name);
function doDestroy() {
indexedDB.deleteDatabase(_.name).onsuccess = function() {
delete ee[_.name];
ie(null, {
ok: true
});
};
}
if (_.name in ee) ee[_.name].then((function(_) {
_.idb.close();
doDestroy();
})); else doDestroy();
}
var COUCH_COLLATE_LO = null, COUCH_COLLATE_HI = "", IDB_COLLATE_LO = Number.NEGATIVE_INFINITY, IDB_COLLATE_HI = [ [ [ [ [ [ [ [ [ [ [ [] ] ] ] ] ] ] ] ] ] ] ];
function externaliseRecord(_) {
var ee = _.revs[_.rev].data;
ee._id = _.id;
ee._rev = _.rev;
if (_.deleted) ee._deleted = true;
return ee;
}
function generateKeyRange(_) {
function defined(_, ee) {
return void 0 !== _[ee];
}
function convert(_, ee) {
return [ 0 ].concat(_).map((function(_) {
if (null === _ && ee) return IDB_NULL; else if (true === _) return IDB_TRUE; else if (false === _) return IDB_FALSE;
if (!ee) if (_ === COUCH_COLLATE_LO) return IDB_COLLATE_LO; else if (Object.prototype.hasOwnProperty.call(_, COUCH_COLLATE_HI)) return IDB_COLLATE_HI;
return _;
}));
}
if (!defined(_, "inclusive_end")) _.inclusive_end = true;
if (!defined(_, "inclusive_start")) _.inclusive_start = true;
if (_.descending) {
var ee = _.startkey, ne = _.inclusive_start;
_.startkey = _.endkey;
_.endkey = ee;
_.inclusive_start = _.inclusive_end;
_.inclusive_end = ne;
}
try {
if (defined(_, "key")) return IDBKeyRange.only(convert(_.key, true));
if (defined(_, "startkey") && !defined(_, "endkey")) return IDBKeyRange.bound(convert(_.startkey), [ 1 ], !_.inclusive_start, true);
if (!defined(_, "startkey") && defined(_, "endkey")) return IDBKeyRange.upperBound(convert(_.endkey), !_.inclusive_end);
if (defined(_, "startkey") && defined(_, "endkey")) return IDBKeyRange.bound(convert(_.startkey), convert(_.endkey), !_.inclusive_start, !_.inclusive_end); else return IDBKeyRange.only([ 0 ]);
} catch (ee) {
console.error("Could not generate keyRange", ee, _);
throw Error("Could not generate key range with " + JSON.stringify(_));
}
}
function getIndexHandle(_, ee, ne) {
var ie = naturalIndexName(ee);
return new Promise((function(re) {
_._openTransactionSafely([ DOC_STORE2 ], "readonly", (function(se, oe) {
if (se) return idbError2(ne)(se);
oe.onabort = idbError2(ne);
oe.ontimeout = idbError2(ne);
if (-1 === Array.from(oe.objectStore(DOC_STORE2).indexNames).indexOf(ie)) _._freshen().then((function() {
return getIndexHandle(_, ee, ne);
})).then(re); else re(oe.objectStore(DOC_STORE2).index(ie));
}));
}));
}
function query(_, ee, ne, ie) {
var re = this, se = ee.split("/");
return new Promise((function(_, oe) {
re.get("_design/" + se[0]).then((function(le) {
if (isPartialFilterView(le, se[1])) return ie(ee, ne).then(_, oe);
var ue = rawIndexFields(le, se[1]);
if (!ue) throw new Error("ddoc " + le._id + " with view " + se[1] + " does not have map.options.def.fields defined.");
var de = ne.skip, fe = Number.isInteger(ne.limit) && ne.limit;
return getIndexHandle(re, ue, oe).then((function(ee) {
var ie = generateKeyRange(ne), re = ee.openCursor(ie, ne.descending ? "prev" : "next"), se = [];
re.onerror = idbError2(oe);
re.onsuccess = function(ee) {
var ne = ee.target.result;
if (!ne || 0 === fe) return _({
rows: se
});
if (!de) {
if (fe) fe -= 1;
se.push({
doc: externaliseRecord(ne.value)
});
ne.continue();
} else {
ne.advance(de);
de = false;
}
};
}));
})).catch(oe);
}));
}
function viewCleanup(_, ee) {
return ee();
}
function purgeAttachments(_, ee) {
if (!_.attachments) return {};
for (let ne in _.attachments) {
const ie = _.attachments[ne];
for (let _ of ee) if (ie.revs[_]) delete ie.revs[_];
if (0 === Object.keys(ie.revs).length) delete _.attachments[ne];
}
return _.attachments;
}
function purge(_, ee, ne, ie) {
if (_.error) return ie(_.error);
const re = _.txn.objectStore(DOC_STORE2), se = [];
let oe = false;
re.get(ee).onsuccess = _ => {
const ee = _.target.result;
for (const _ of ne) {
ee.rev_tree = removeLeafFromRevTree(ee.rev_tree, _);
delete ee.revs[_];
se.push(_);
}
if (0 !== ee.rev_tree.length) {
ee.rev = winningRev(ee);
ee.data = ee.revs[ee.rev].data;
ee.attachments = purgeAttachments(ee, ne);
re.put(ee);
} else {
re.delete(ee.id);
oe = true;
}
};
_.txn.oncomplete = function() {
ie(null, {
ok: true,
deletedRevs: se,
documentWasRemovedCompletely: oe
});
};
}
var ADAPTER_NAME = "indexeddb", idbChanges = new Changes, openDatabases = {};
function IdbPouch2(_, ee) {
if (_.view_adapter) console.log("Please note that the indexeddb adapter manages _find indexes itself, therefore it is not using your specified view_adapter");
var ne = this, ie = {}, $ = function(ee) {
return function() {
var re = Array.prototype.slice.call(arguments);
setup(openDatabases, ne, _).then((function(_) {
ie = _.metadata;
re.unshift(_.idb);
ee.apply(ne, re);
})).catch((function(_) {
var ee = re.pop();
if ("function" == typeof ee) ee(_); else console.error(_);
}));
};
}, $p = function(ee) {
return function() {
var re = Array.prototype.slice.call(arguments);
return setup(openDatabases, ne, _).then((function(_) {
ie = _.metadata;
re.unshift(_.idb);
return ee.apply(ne, re);
}));
};
}, $t2 = function(ee, re, se) {
re = re || [ DOC_STORE2 ];
se = se || "readonly";
return function() {
var oe = Array.prototype.slice.call(arguments), le = {};
setup(openDatabases, ne, _).then((function(_) {
ie = _.metadata;
le.txn = _.idb.transaction(re, se);
})).catch((function(_) {
console.error("Failed to establish transaction safely");
console.error(_);
le.error = _;
})).then((function() {
oe.unshift(le);
ee.apply(ne, oe);
}));
};
};
ne._openTransactionSafely = function(_, ee, ne) {
$t2((function(_, ee) {
ee(_.error, _.txn);
}), _, ee)(ne);
};
ne._remote = false;
ne.type = function() {
return ADAPTER_NAME;
};
ne._id = $((function(_, ee) {
ee(null, ie.db_uuid);
}));
ne._info = $((function(_, ee) {
return info(ie, ee);
}));
ne._get = $t2(get);
ne._bulkDocs = $((function(ee, re, se, oe) {
bulkDocs(ne, re, se, ie, _, idbChanges, oe);
}));
ne._allDocs = $t2((function(_, ee, ne) {
allDocs(_, ie, ee, ne);
}));
ne._getAttachment = $t2(getAttachment);
ne._changes = $t2((function(ee, ie) {
changes2(ee, idbChanges, ne, _, ie);
}));
ne._getRevisionTree = $t2(getRevisionTree);
ne._doCompaction = $t2(doCompaction, [ DOC_STORE2 ], "readwrite");
ne._customFindAbstractMapper = {
query: $p(query),
viewCleanup: $p(viewCleanup)
};
ne._destroy = function(ee, ne) {
return destroy(_, openDatabases, idbChanges, ne);
};
ne._close = $((function(ee, ne) {
delete openDatabases[_.name];
ee.close();
ne();
}));
ne._freshen = function() {
return new Promise((function(_) {
ne._close((function() {
$(_)();
}));
}));
};
ne._purge = $t2(purge, [ DOC_STORE2 ], "readwrite");
setTimeout((function() {
ee(null, ne);
}));
}
IdbPouch2.valid = function() {
return true;
};
function index2(_) {
_.adapter(ADAPTER_NAME, IdbPouch2, true);
}
var index_es_default3 = index2;
function pool(_, ee) {
return new Promise((function(ne, ie) {
var re, se = 0, oe = 0, le = 0, ue = _.length;
function runNext() {
se++;
_[oe++]().then(onSuccess, onError);
}
function doNext() {
if (++le === ue) if (re) ie(re); else ne(); else runNextBatch();
}
function onSuccess() {
se--;
doNext();
}
function onError(_) {
se--;
re = re || _;
doNext();
}
function runNextBatch() {
for (;se < ee && oe < ue; ) runNext();
}
runNextBatch();
}));
}
var CHANGES_BATCH_SIZE = 25, MAX_SIMULTANEOUS_REVS = 50, CHANGES_TIMEOUT_BUFFER = 5e3, DEFAULT_HEARTBEAT = 1e4, supportsBulkGetMap = {};
function readAttachmentsAsBlobOrBuffer(_) {
let ee = _.doc || _.ok, ne = ee && ee._attachments;
if (ne) Object.keys(ne).forEach((function(_) {
let ee = ne[_];
ee.data = b64ToBluffer(ee.data, ee.content_type);
}));
}
function encodeDocId(_) {
if (/^_design/.test(_)) return "_design/" + encodeURIComponent(_.slice(8));
if (/^_local/.test(_)) return "_local/" + encodeURIComponent(_.slice(7)); else return encodeURIComponent(_);
}
function preprocessAttachments2(_) {
if (!_._attachments || !Object.keys(_._attachments)) return Promise.resolve(); else return Promise.all(Object.keys(_._attachments).map((function(ee) {
let ne = _._attachments[ee];
if (ne.data && "string" != typeof ne.data) return new Promise((function(_) {
blobToBase64(ne.data, _);
})).then((function(_) {
ne.data = _;
}));
})));
}
function hasUrlPrefix(_) {
if (!_.prefix) return false;
let ee = parseUri(_.prefix).protocol;
return "http" === ee || "https" === ee;
}
function getHost(_, ee) {
if (hasUrlPrefix(ee)) {
let ne = ee.name.substr(ee.prefix.length);
_ = ee.prefix.replace(/\/?$/, "/") + encodeURIComponent(ne);
}
let ne = parseUri(_);
if (ne.user || ne.password) ne.auth = {
username: ne.user,
password: ne.password
};
let ie = ne.path.replace(/(^\/|\/$)/g, "").split("/");
ne.db = ie.pop();
if (-1 === ne.db.indexOf("%")) ne.db = encodeURIComponent(ne.db);
ne.path = ie.join("/");
return ne;
}
function genDBUrl(_, ee) {
return genUrl(_, _.db + "/" + ee);
}
function genUrl(_, ee) {
let ne = !_.path ? "" : "/";
return _.protocol + "://" + _.host + (_.port ? ":" + _.port : "") + "/" + _.path + ne + ee;
}
function paramsToStr(_) {
return "?" + Object.keys(_).map((function(ee) {
return ee + "=" + encodeURIComponent(_[ee]);
})).join("&");
}
function shouldCacheBust(_) {
let ee = "undefined" != typeof navigator && navigator.userAgent ? navigator.userAgent.toLowerCase() : "", ne = -1 !== ee.indexOf("msie"), ie = -1 !== ee.indexOf("trident"), re = -1 !== ee.indexOf("edge"), se = !("method" in _) || "GET" === _.method;
return (ne || ie || re) && se;
}
function HttpPouch(_, ee) {
let ne = this, ie = getHost(_.name, _), re = genDBUrl(ie, "");
_ = clone(_);
const ourFetch = async function(ee, ne) {
(ne = ne || {}).headers = ne.headers || new h;
ne.credentials = "include";
if (_.auth || ie.auth) {
let ee = _.auth || ie.auth, re = ee.username + ":" + ee.password, se = thisBtoa(unescape(encodeURIComponent(re)));
ne.headers.set("Authorization", "Basic " + se);
}
let re = _.headers || {};
Object.keys(re).forEach((function(_) {
ne.headers.append(_, re[_]);
}));
if (shouldCacheBust(ne)) ee += (-1 === ee.indexOf("?") ? "?" : "&") + "_nonce=" + Date.now();
let se = _.fetch || f2;
return await se(ee, ne);
};
function adapterFun$$1(_, ee) {
return adapterFun(_, (function(..._) {
setup2().then((function() {
return ee.apply(this, _);
})).catch((function(ee) {
_.pop()(ee);
}));
})).bind(ne);
}
async function fetchJSON(_, ee) {
let ne = {};
(ee = ee || {}).headers = ee.headers || new h;
if (!ee.headers.get("Content-Type")) ee.headers.set("Content-Type", "application/json");
if (!ee.headers.get("Accept")) ee.headers.set("Accept", "application/json");
const ie = await ourFetch(_, ee);
ne.ok = ie.ok;
ne.status = ie.status;
const re = await ie.json();
ne.data = re;
if (!ne.ok) {
ne.data.status = ne.status;
throw generateErrorFromResponse(ne.data);
}
if (Array.isArray(ne.data)) ne.data = ne.data.map((function(_) {
if (_.error || _.missing) return generateErrorFromResponse(_); else return _;
}));
return ne;
}
let se;
async function setup2() {
if (_.skip_setup) return Promise.resolve();
if (se) return se;
se = fetchJSON(re).catch((function(_) {
if (_ && _.status && 404 === _.status) {
explainError(404, "PouchDB is just detecting if the remote exists.");
return fetchJSON(re, {
method: "PUT"
});
} else return Promise.reject(_);
})).catch((function(_) {
if (_ && _.status && 412 === _.status) return true; else return Promise.reject(_);
}));
se.catch((function() {
se = null;
}));
return se;
}
(0, import_immediate.default)((function() {
ee(null, ne);
}));
ne._remote = true;
ne.type = function() {
return "http";
};
ne.id = adapterFun$$1("id", (async function(_) {
let ee;
try {
const _ = await ourFetch(genUrl(ie, ""));
ee = await _.json();
} catch (_) {
ee = {};
}
_(null, ee && ee.uuid ? ee.uuid + ie.db : genDBUrl(ie, ""));
}));
ne.compact = adapterFun$$1("compact", (async function(_, ee) {
if ("function" == typeof _) {
ee = _;
_ = {};
}
_ = clone(_);
await fetchJSON(genDBUrl(ie, "_compact"), {
method: "POST"
});
(function ping() {
ne.info((function(ne, ie) {
if (ie && !ie.compact_running) ee(null, {
ok: true
}); else setTimeout(ping, _.interval || 200);
}));
})();
}));
ne.bulkGet = adapterFun("bulkGet", (function(_, ee) {
let ne = this;
async function doBulkGet(ee) {
let ne = {};
if (_.revs) ne.revs = true;
if (_.attachments) ne.attachments = true;
if (_.latest) ne.latest = true;
try {
const re = await fetchJSON(genDBUrl(ie, "_bulk_get" + paramsToStr(ne)), {
method: "POST",
body: JSON.stringify({
docs: _.docs
})
});
if (_.attachments && _.binary) re.data.results.forEach((function(_) {
_.docs.forEach(readAttachmentsAsBlobOrBuffer);
}));
ee(null, re.data);
} catch (_) {
ee(_);
}
}
function doBulkGetShim() {
let ie = MAX_SIMULTANEOUS_REVS, re = Math.ceil(_.docs.length / ie), se = 0, oe = new Array(re);
function onResult(_) {
return function(ne, ie) {
oe[_] = ie.results;
if (++se === re) ee(null, {
results: flatten(oe)
});
};
}
for (let ee = 0; ee < re; ee++) {
let re = pick(_, [ "revs", "attachments", "binary", "latest" ]);
re.docs = _.docs.slice(ee * ie, Math.min(_.docs.length, (ee + 1) * ie));
bulkGet(ne, re, onResult(ee));
}
}
let re = genUrl(ie, ""), se = supportsBulkGetMap[re];
if ("boolean" != typeof se) doBulkGet((function(_, ne) {
if (_) {
supportsBulkGetMap[re] = false;
explainError(_.status, "PouchDB is just detecting if the remote supports the _bulk_get API.");
doBulkGetShim();
} else {
supportsBulkGetMap[re] = true;
ee(null, ne);
}
})); else if (se) doBulkGet(ee); else doBulkGetShim();
}));
ne._info = async function(_) {
try {
await setup2();
const ee = await ourFetch(genDBUrl(ie, "")), ne = await ee.json();
ne.host = genDBUrl(ie, "");
_(null, ne);
} catch (ee) {
_(ee);
}
};
ne.fetch = async function(_, ee) {
await setup2();
const ne = "/" === _.substring(0, 1) ? genUrl(ie, _.substring(1)) : genDBUrl(ie, _);
return ourFetch(ne, ee);
};
ne.get = adapterFun$$1("get", (async function(_, ee, ne) {
if ("function" == typeof ee) {
ne = ee;
ee = {};
}
let re = {};
if ((ee = clone(ee)).revs) re.revs = true;
if (ee.revs_info) re.revs_info = true;
if (ee.latest) re.latest = true;
if (ee.open_revs) {
if ("all" !== ee.open_revs) ee.open_revs = JSON.stringify(ee.open_revs);
re.open_revs = ee.open_revs;
}
if (ee.rev) re.rev = ee.rev;
if (ee.conflicts) re.conflicts = ee.conflicts;
if (ee.update_seq) re.update_seq = ee.update_seq;
_ = encodeDocId(_);
function fetchAttachments(_) {
let ne = _._attachments, re = ne && Object.keys(ne);
if (ne && re.length) return pool(re.map((function(re) {
return function() {
return async function fetchData(re) {
const se = ne[re], oe = encodeDocId(_._id) + "/" + encodeAttachmentId(re) + "?rev=" + _._rev, le = await ourFetch(genDBUrl(ie, oe));
let ue, de;
if ("buffer" in le) ue = await le.buffer(); else ue = await le.blob();
if (ee.binary) {
let _ = Object.getOwnPropertyDescriptor(ue.__proto__, "type");
if (!_ || _.set) ue.type = se.content_type;
de = ue;
} else de = await new Promise((function(_) {
blobToBase64(ue, _);
}));
delete se.stub;
delete se.length;
se.data = de;
}(re);
};
})), 5);
}
const se = genDBUrl(ie, _ + paramsToStr(re));
try {
const _ = await fetchJSON(se);
if (ee.attachments) await function fetchAllAttachments(_) {
if (Array.isArray(_)) return Promise.all(_.map((function(_) {
if (_.ok) return fetchAttachments(_.ok);
}))); else return fetchAttachments(_);
}(_.data);
ne(null, _.data);
} catch (ee) {
ee.docId = _;
ne(ee);
}
}));
ne.remove = adapterFun$$1("remove", (async function(_, ee, ne, re) {
let se;
if ("string" == typeof ee) {
se = {
_id: _,
_rev: ee
};
if ("function" == typeof ne) {
re = ne;
ne = {};
}
} else {
se = _;
if ("function" == typeof ee) {
re = ee;
ne = {};
} else {
re = ne;
ne = ee;
}
}
const oe = se._rev || ne.rev, le = genDBUrl(ie, encodeDocId(se._id)) + "?rev=" + oe;
try {
re(null, (await fetchJSON(le, {
method: "DELETE"
})).data);
} catch (_) {
re(_);
}
}));
function encodeAttachmentId(_) {
return _.split("/").map(encodeURIComponent).join("/");
}
ne.getAttachment = adapterFun$$1("getAttachment", (async function(_, ee, ne, re) {
if ("function" == typeof ne) {
re = ne;
ne = {};
}
const se = ne.rev ? "?rev=" + ne.rev : "", oe = genDBUrl(ie, encodeDocId(_)) + "/" + encodeAttachmentId(ee) + se;
let le;
try {
const _ = await ourFetch(oe, {
method: "GET"
});
if (!_.ok) throw _;
le = _.headers.get("content-type");
let ee;
if ("undefined" != typeof process && !process.browser && "function" == typeof _.buffer) ee = await _.buffer(); else ee = await _.blob();
if ("undefined" != typeof process && !process.browser) {
var ue = Object.getOwnPropertyDescriptor(ee.__proto__, "type");
if (!ue || ue.set) ee.type = le;
}
re(null, ee);
} catch (_) {
re(_);
}
}));
ne.removeAttachment = adapterFun$$1("removeAttachment", (async function(_, ee, ne, re) {
const se = genDBUrl(ie, encodeDocId(_) + "/" + encodeAttachmentId(ee)) + "?rev=" + ne;
try {
re(null, (await fetchJSON(se, {
method: "DELETE"
})).data);
} catch (_) {
re(_);
}
}));
ne.putAttachment = adapterFun$$1("putAttachment", (async function(_, ee, ne, re, se, oe) {
if ("function" == typeof se) {
oe = se;
se = re;
re = ne;
ne = null;
}
const le = encodeDocId(_) + "/" + encodeAttachmentId(ee);
let ue = genDBUrl(ie, le);
if (ne) ue += "?rev=" + ne;
if ("string" == typeof re) {
let _;
try {
_ = thisAtob(re);
} catch (_) {
return oe(createError(BAD_ARG, "Attachment is not a valid base64 string"));
}
re = _ ? binStringToBluffer(_, se) : "";
}
try {
oe(null, (await fetchJSON(ue, {
headers: new h({
"Content-Type": se
}),
method: "PUT",
body: re
})).data);
} catch (_) {
oe(_);
}
}));
ne._bulkDocs = async function(_, ee, ne) {
_.new_edits = ee.new_edits;
try {
await setup2();
await Promise.all(_.docs.map(preprocessAttachments2));
ne(null, (await fetchJSON(genDBUrl(ie, "_bulk_docs"), {
method: "POST",
body: JSON.stringify(_)
})).data);
} catch (_) {
ne(_);
}
};
ne._put = async function(_, ee, ne) {
try {
await setup2();
await preprocessAttachments2(_);
ne(null, (await fetchJSON(genDBUrl(ie, encodeDocId(_._id)), {
method: "PUT",
body: JSON.stringify(_)
})).data);
} catch (ee) {
ee.docId = _ && _._id;
ne(ee);
}
};
ne.allDocs = adapterFun$$1("allDocs", (async function(_, ee) {
if ("function" == typeof _) {
ee = _;
_ = {};
}
let ne, re = {}, se = "GET";
if ((_ = clone(_)).conflicts) re.conflicts = true;
if (_.update_seq) re.update_seq = true;
if (_.descending) re.descending = true;
if (_.include_docs) re.include_docs = true;
if (_.attachments) re.attachments = true;
if (_.key) re.key = JSON.stringify(_.key);
if (_.start_key) _.startkey = _.start_key;
if (_.startkey) re.startkey = JSON.stringify(_.startkey);
if (_.end_key) _.endkey = _.end_key;
if (_.endkey) re.endkey = JSON.stringify(_.endkey);
if ("undefined" != typeof _.inclusive_end) re.inclusive_end = !!_.inclusive_end;
if ("undefined" != typeof _.limit) re.limit = _.limit;
if ("undefined" != typeof _.skip) re.skip = _.skip;
let oe = paramsToStr(re);
if ("undefined" != typeof _.keys) {
se = "POST";
ne = {
keys: _.keys
};
}
try {
const re = await fetchJSON(genDBUrl(ie, "_all_docs" + oe), {
method: se,
body: JSON.stringify(ne)
});
if (_.include_docs && _.attachments && _.binary) re.data.rows.forEach(readAttachmentsAsBlobOrBuffer);
ee(null, re.data);
} catch (_) {
ee(_);
}
}));
ne._changes = function(_) {
let ee = "batch_size" in _ ? _.batch_size : CHANGES_BATCH_SIZE;
if ((_ = clone(_)).continuous && !("heartbeat" in _)) _.heartbeat = DEFAULT_HEARTBEAT;
let ne = "timeout" in _ ? _.timeout : 3e4;
if ("timeout" in _ && _.timeout && ne - _.timeout < CHANGES_TIMEOUT_BUFFER) ne = _.timeout + CHANGES_TIMEOUT_BUFFER;
if ("heartbeat" in _ && _.heartbeat && ne - _.heartbeat < CHANGES_TIMEOUT_BUFFER) ne = _.heartbeat + CHANGES_TIMEOUT_BUFFER;
let re = {};
if ("timeout" in _ && _.timeout) re.timeout = _.timeout;
let se = "undefined" != typeof _.limit ? _.limit : false, oe = se;
if (_.style) re.style = _.style;
if (_.include_docs || _.filter && "function" == typeof _.filter) re.include_docs = true;
if (_.attachments) re.attachments = true;
if (_.continuous) re.feed = "longpoll";
if (_.seq_interval) re.seq_interval = _.seq_interval;
if (_.conflicts) re.conflicts = true;
if (_.descending) re.descending = true;
if (_.update_seq) re.update_seq = true;
if ("heartbeat" in _) if (_.heartbeat) re.heartbeat = _.heartbeat;
if (_.filter && "string" == typeof _.filter) re.filter = _.filter;
if (_.view && "string" == typeof _.view) {
re.filter = "_view";
re.view = _.view;
}
if (_.query_params && "object" == typeof _.query_params) for (let ee in _.query_params) if (Object.prototype.hasOwnProperty.call(_.query_params, ee)) re[ee] = _.query_params[ee];
let le, ue = "GET";
if (_.doc_ids) {
re.filter = "_doc_ids";
ue = "POST";
le = {
doc_ids: _.doc_ids
};
} else if (_.selector) {
re.filter = "_selector";
ue = "POST";
le = {
selector: _.selector
};
}
let de, fe = new a;
const fetchData = async function(ne, he) {
if (_.aborted) return;
re.since = ne;
if ("object" == typeof re.since) re.since = JSON.stringify(re.since);
if (_.descending) {
if (se) re.limit = oe;
} else re.limit = !se || oe > ee ? ee : oe;
let pe = genDBUrl(ie, "_changes" + paramsToStr(re)), ge = {
signal: fe.signal,
method: ue,
body: JSON.stringify(le)
};
de = ne;
if (!_.aborted) try {
await setup2();
he(null, (await fetchJSON(pe, ge)).data);
} catch (_) {
he(_);
}
};
let he = {
results: []
};
const fetched = function(ne, ie) {
if (_.aborted) return;
let re = 0;
if (ie && ie.results) {
re = ie.results.length;
he.last_seq = ie.last_seq;
let ee = null, ne = null;
if ("number" == typeof ie.pending) ee = ie.pending;
if ("string" == typeof he.last_seq || "number" == typeof he.last_seq) ne = he.last_seq;
({}).query = _.query_params;
ie.results = ie.results.filter((function(ie) {
oe--;
let re = filterChange(_)(ie);
if (re) {
if (_.include_docs && _.attachments && _.binary) readAttachmentsAsBlobOrBuffer(ie);
if (_.return_docs) he.results.push(ie);
_.onChange(ie, ee, ne);
}
return re;
}));
} else if (ne) {
_.aborted = true;
_.complete(ne);
return;
}
if (ie && ie.last_seq) de = ie.last_seq;
let le = se && oe <= 0 || ie && re < ee || _.descending;
if (_.continuous && !(se && oe <= 0) || !le) (0, import_immediate.default)((function() {
fetchData(de, fetched);
})); else _.complete(null, he);
};
fetchData(_.since || 0, fetched);
return {
cancel: function() {
_.aborted = true;
fe.abort();
}
};
};
ne.revsDiff = adapterFun$$1("revsDiff", (async function(_, ee, ne) {
if ("function" == typeof ee) {
ne = ee;
ee = {};
}
try {
ne(null, (await fetchJSON(genDBUrl(ie, "_revs_diff"), {
method: "POST",
body: JSON.stringify(_)
})).data);
} catch (_) {
ne(_);
}
}));
ne._close = function(_) {
_();
};
ne._destroy = async function(_, ee) {
try {
ee(null, await fetchJSON(genDBUrl(ie, ""), {
method: "DELETE"
}));
} catch (_) {
if (404 === _.status) ee(null, {
ok: true
}); else ee(_);
}
};
}
HttpPouch.valid = function() {
return true;
};
function index3(_) {
_.adapter("http", HttpPouch, false);
_.adapter("https", HttpPouch, false);
}
var index_es_default4 = index3, QueryParseError = class _QueryParseError extends Error {
constructor(_) {
super();
this.status = 400;
this.name = "query_parse_error";
this.message = _;
this.error = true;
try {
Error.captureStackTrace(this, _QueryParseError);
} catch (_) {}
}
}, NotFoundError = class _NotFoundError extends Error {
constructor(_) {
super();
this.status = 404;
this.name = "not_found";
this.message = _;
this.error = true;
try {
Error.captureStackTrace(this, _NotFoundError);
} catch (_) {}
}
}, BuiltInError = class _BuiltInError extends Error {
constructor(_) {
super();
this.status = 500;
this.name = "invalid_value";
this.message = _;
this.error = true;
try {
Error.captureStackTrace(this, _BuiltInError);
} catch (_) {}
}
};
function promisedCallback(_, ee) {
if (ee) _.then((function(_) {
(0, import_immediate.default)((function() {
ee(null, _);
}));
}), (function(_) {
(0, import_immediate.default)((function() {
ee(_);
}));
}));
return _;
}
function callbackify(_) {
return function(...ee) {
var ne = ee.pop(), ie = _.apply(this, ee);
if ("function" == typeof ne) promisedCallback(ie, ne);
return ie;
};
}
function fin(_, ee) {
return _.then((function(_) {
return ee().then((function() {
return _;
}));
}), (function(_) {
return ee().then((function() {
throw _;
}));
}));
}
function sequentialize(_, ee) {
return function() {
var ne = arguments, ie = this;
return _.add((function() {
return ee.apply(ie, ne);
}));
};
}
function uniq(_) {
var ee = new ExportedSet(_), ne = new Array(ee.size), ie = -1;
ee.forEach((function(_) {
ne[++ie] = _;
}));
return ne;
}
function mapToKeysArray(_) {
var ee = new Array(_.size), ne = -1;
_.forEach((function(_, ie) {
ee[++ne] = ie;
}));
return ee;
}
var TaskQueue2 = class {
constructor() {
this.promise = new Promise((function(_) {
_();
}));
}
add(_) {
this.promise = this.promise.catch((function() {})).then((function() {
return _();
}));
return this.promise;
}
finish() {
return this.promise;
}
};
function stringify2(_) {
if (!_) return "undefined";
switch (typeof _) {
case "function":
return _.toString();
case "string":
return _.toString();
default:
return JSON.stringify(_);
}
}
function createViewSignature(_, ee) {
return stringify2(_) + stringify2(ee) + "undefined";
}
async function createView(_, ee, ne, ie, re, se) {
const oe = createViewSignature(ne, ie);
let le;
if (!re) {
le = _._cachedViews = _._cachedViews || {};
if (le[oe]) return le[oe];
}
const ue = _.info().then((async function(ue) {
const de = ue.db_name + "-mrview-" + (re ? "temp" : stringMd5(oe));
await upsert(_, "_local/" + se, (function diffFunction(_) {
_.views = _.views || {};
let ne = ee;
if (-1 === ne.indexOf("/")) ne = ee + "/" + ee;
const ie = _.views[ne] = _.views[ne] || {};
if (!ie[de]) {
ie[de] = true;
return _;
}
}));
const fe = (await _.registerDependentDatabase(de)).db;
fe.auto_compaction = true;
const he = {
name: de,
db: fe,
sourceDB: _,
adapter: _.adapter,
mapFun: ne,
reduceFun: ie
};
let pe;
try {
pe = await he.db.get("_local/lastSeq");
} catch (_) {
if (404 !== _.status) throw _;
}
he.seq = pe ? pe.seq : 0;
if (le) he.db.once("destroyed", (function() {
delete le[oe];
}));
return he;
}));
if (le) le[oe] = ue;
return ue;
}
var persistentQueues = {}, tempViewQueue = new TaskQueue2, CHANGES_BATCH_SIZE2 = 50;
function parseViewName(_) {
return -1 === _.indexOf("/") ? [ _, _ ] : _.split("/");
}
function isGenOne(_) {
return 1 === _.length && /^1-/.test(_[0].rev);
}
function emitError(_, ee, ne) {
try {
_.emit("error", ee);
} catch (_) {
guardedConsole("error", "The user's map/reduce function threw an uncaught error.\nYou can debug this error by doing:\nmyDatabase.on('error', function (err) { debugger; });\nPlease double-check your map/reduce function.");
guardedConsole("error", ee, ne);
}
}
function createAbstractMapReduce(_, ee, ne, ie) {
function tryMap(_, ee, ne) {
try {
ee(ne);
} catch (ie) {
emitError(_, ie, {
fun: ee,
doc: ne
});
}
}
function tryReduce(_, ee, ne, ie, re) {
try {
return {
output: ee(ne, ie, re)
};
} catch (se) {
emitError(_, se, {
fun: ee,
keys: ne,
values: ie,
rereduce: re
});
return {
error: se
};
}
}
function sortByKeyThenValue(_, ee) {
const ne = collate(_.key, ee.key);
return 0 !== ne ? ne : collate(_.value, ee.value);
}
function sliceResults(_, ee, ne) {
ne = ne || 0;
if ("number" == typeof ee) return _.slice(ne, ee + ne); else if (ne > 0) return _.slice(ne);
return _;
}
function rowToDocId(_) {
const ee = _.value;
return ee && "object" == typeof ee && ee._id || _.id;
}
function postprocessAttachments(_) {
return function(ee) {
if (_.include_docs && _.attachments && _.binary) (function readAttachmentsAsBlobOrBuffer2(_) {
_.rows.forEach((function(_) {
const ee = _.doc && _.doc._attachments;
if (ee) Object.keys(ee).forEach((function(_) {
const ne = ee[_];
ee[_].data = b64ToBluffer(ne.data, ne.content_type);
}));
}));
})(ee);
return ee;
};
}
function addHttpParam(_, ee, ne, ie) {
let re = ee[_];
if ("undefined" != typeof re) {
if (ie) re = encodeURIComponent(JSON.stringify(re));
ne.push(_ + "=" + re);
}
}
function coerceInteger(_) {
if ("undefined" != typeof _) {
const ee = Number(_);
if (!isNaN(ee) && ee === parseInt(_, 10)) return ee; else return _;
}
}
function checkQueryParseError(_, ee) {
const ne = _.descending ? "endkey" : "startkey", ie = _.descending ? "startkey" : "endkey";
if ("undefined" != typeof _[ne] && "undefined" != typeof _[ie] && collate(_[ne], _[ie]) > 0) throw new QueryParseError("No rows can match your key range, reverse your start_key and end_key or set {descending : true}"); else if (ee.reduce && false !== _.reduce) if (_.include_docs) throw new QueryParseError("{include_docs:true} is invalid for reduce"); else if (_.keys && _.keys.length > 1 && !_.group && !_.group_level) throw new QueryParseError("Multi-key fetches for reduce views must use {group: true}");
[ "group_level", "limit", "skip" ].forEach((function(ee) {
const ne = function checkPositiveInteger(_) {
if (_) {
if ("number" != typeof _) return new QueryParseError(`Invalid value for integer: "${_}"`);
if (_ < 0) return new QueryParseError(`Invalid value for positive integer: "${_}"`);
}
}(_[ee]);
if (ne) throw ne;
}));
}
function defaultsTo(_) {
return function(ee) {
if (404 === ee.status) return _; else throw ee;
};
}
function getQueue(_) {
const ee = "string" == typeof _ ? _ : _.name;
let ne = persistentQueues[ee];
if (!ne) ne = persistentQueues[ee] = new TaskQueue2;
return ne;
}
async function updateView(_, ne) {
return sequentialize(getQueue(_), (function() {
return async function updateViewInQueue(_, ne) {
let ie, re, se;
const oe = ee(_.mapFun, (function emit2(_, ee) {
const ne = {
id: re._id,
key: normalizeKey(_)
};
if ("undefined" != typeof ee && null !== ee) ne.value = normalizeKey(ee);
ie.push(ne);
}));
let le = _.seq || 0, ue = 0;
const de = {
view: _.name,
indexed_docs: ue
};
_.sourceDB.emit("indexing", de);
const fe = new TaskQueue2;
function createIndexableKeysToKeyValues(_) {
const ee = new ExportedMap;
let ne;
for (let ie = 0, re = _.length; ie < re; ie++) {
const re = _[ie], se = [ re.key, re.id ];
if (ie > 0 && 0 === collate(re.key, ne)) se.push(ie);
ee.set(toIndexableString(se), re);
ne = re.key;
}
return ee;
}
try {
await function createTask() {
return _.sourceDB.info().then((function(ee) {
se = _.sourceDB.activeTasks.add({
name: "view_indexing",
total_items: ee.update_seq - le
});
}));
}();
await async function processNextBatch() {
return function processBatch(ee, de) {
var he = ee.results;
if (!he.length && !de.length) return;
for (let _ of de) if (he.findIndex((function(ee) {
return ee.id === _.docId;
})) < 0) {
const ee = {
_id: _.docId,
doc: {
_id: _.docId,
_deleted: 1
},
changes: []
};
if (_.doc) {
ee.doc = _.doc;
ee.changes.push({
rev: _.doc._rev
});
}
he.push(ee);
}
var pe = function createDocIdsToChangesAndEmits(ee) {
const ne = new ExportedMap;
for (let se = 0, ue = ee.length; se < ue; se++) {
const ue = ee[se];
if ("_" !== ue.doc._id[0]) {
ie = [];
re = ue.doc;
if (!re._deleted) tryMap(_.sourceDB, oe, re);
ie.sort(sortByKeyThenValue);
const ee = createIndexableKeysToKeyValues(ie);
ne.set(ue.doc._id, [ ee, ue.changes ]);
}
le = ue.seq;
}
return ne;
}(he);
fe.add(function processChange2(ee, ne) {
return function() {
return function saveKeyValues(_, ee, ne) {
var ie = "_local/lastSeq";
return _.db.get(ie).catch(defaultsTo({
_id: ie,
seq: 0
})).then((function(ie) {
var re = mapToKeysArray(ee);
return Promise.all(re.map((function(ne) {
return async function getDocsToPersist(_, ee, ne) {
const ie = "_local/doc_" + _, re = {
_id: ie,
keys: []
}, se = ne.get(_), oe = se[0], le = se[1], ue = await function getMetaDoc() {
if (isGenOne(le)) return Promise.resolve(re); else return ee.db.get(ie).catch(defaultsTo(re));
}();
return function processKeyValueDocs(_, ee) {
const ne = [], ie = new ExportedSet;
for (let _ = 0, re = ee.rows.length; _ < re; _++) {
const re = ee.rows[_].doc;
if (re) {
ne.push(re);
ie.add(re._id);
re._deleted = !oe.has(re._id);
if (!re._deleted) {
const _ = oe.get(re._id);
if ("value" in _) re.value = _.value;
}
}
}
const re = mapToKeysArray(oe);
re.forEach((function(_) {
if (!ie.has(_)) {
const ee = {
_id: _
}, ie = oe.get(_);
if ("value" in ie) ee.value = ie.value;
ne.push(ee);
}
}));
_.keys = uniq(re.concat(_.keys));
ne.push(_);
return ne;
}(ue, await function getKeyValueDocs(_) {
if (!_.keys.length) return Promise.resolve({
rows: []
}); else return ee.db.allDocs({
keys: _.keys,
include_docs: true
});
}(ue));
}(ne, _, ee);
}))).then((function(ee) {
var re = flatten(ee);
ie.seq = ne;
re.push(ie);
return _.db.bulkDocs({
docs: re
});
})).then((() => function updatePurgeSeq(_) {
return _.sourceDB.get("_local/purges").then((function(ee) {
const ne = ee.purgeSeq;
return _.db.get("_local/purgeSeq").then((function(_) {
return _._rev;
})).catch((function(_) {
if (404 !== _.status) throw _;
})).then((function(ee) {
return _.db.put({
_id: "_local/purgeSeq",
_rev: ee,
purgeSeq: ne
});
}));
})).catch((function(_) {
if (404 !== _.status) throw _;
}));
}(_)));
}));
}(_, ee, ne);
};
}(pe, le));
ue += he.length;
const ge = {
view: _.name,
last_seq: ee.last_seq,
results_count: he.length,
indexed_docs: ue
};
_.sourceDB.emit("indexing", ge);
_.sourceDB.activeTasks.update(se, {
completed_items: ue
});
if (!(he.length < ne.changes_batch_size)) return processNextBatch(); else return;
}(await _.sourceDB.changes({
return_docs: true,
conflicts: true,
include_docs: true,
style: "all_docs",
since: le,
limit: ne.changes_batch_size
}), await function getRecentPurges() {
return _.db.get("_local/purgeSeq").then((function(_) {
return _.purgeSeq;
})).catch((function(_) {
if (_ && 404 !== _.status) throw _;
return -1;
})).then((function(ee) {
return _.sourceDB.get("_local/purges").then((function(ne) {
const ie = ne.purges.filter((function(_, ne) {
return ne > ee;
})).map((_ => _.docId)), re = ie.filter((function(_, ee) {
return ie.indexOf(_) === ee;
}));
return Promise.all(re.map((function(ee) {
return _.sourceDB.get(ee).then((function(_) {
return {
docId: ee,
doc: _
};
})).catch((function(_) {
if (404 !== _.status) throw _;
return {
docId: ee
};
}));
})));
})).catch((function(_) {
if (_ && 404 !== _.status) throw _;
return [];
}));
}));
}());
}();
await fe.finish();
_.seq = le;
_.sourceDB.activeTasks.remove(se);
} catch (ee) {
_.sourceDB.activeTasks.remove(se, ee);
}
}(_, ne);
}))();
}
function queryView(_, ee) {
return sequentialize(getQueue(_), (function() {
return async function queryViewInQueue(_, ee) {
let ie;
const re = _.reduceFun && false !== ee.reduce, se = ee.skip || 0;
if ("undefined" != typeof ee.keys && !ee.keys.length) {
ee.limit = 0;
delete ee.keys;
}
async function fetchFromView(ee) {
ee.include_docs = true;
const ne = await _.db.allDocs(ee);
ie = ne.total_rows;
return ne.rows.map((function(_) {
if ("value" in _.doc && "object" == typeof _.doc.value && null !== _.doc.value) {
const ee = Object.keys(_.doc.value).sort(), ne = [ "id", "key", "value" ];
if (!(ee < ne || ee > ne)) return _.doc.value;
}
const ee = parseIndexableString(_.doc._id);
return {
key: ee[0],
id: ee[1],
value: "value" in _.doc ? _.doc.value : null
};
}));
}
async function onMapResultsReady(oe) {
let le;
if (re) le = function reduceView(_, ee, ie) {
if (0 === ie.group_level) delete ie.group_level;
const re = ie.group || ie.group_level, se = ne(_.reduceFun), oe = [], le = isNaN(ie.group_level) ? Number.POSITIVE_INFINITY : ie.group_level;
ee.forEach((function(_) {
const ee = oe[oe.length - 1];
let ne = re ? _.key : null;
if (re && Array.isArray(ne)) ne = ne.slice(0, le);
if (!ee || 0 !== collate(ee.groupKey, ne)) oe.push({
keys: [ [ _.key, _.id ] ],
values: [ _.value ],
groupKey: ne
}); else {
ee.keys.push([ _.key, _.id ]);
ee.values.push(_.value);
}
}));
ee = [];
for (let ne = 0, ie = oe.length; ne < ie; ne++) {
const ie = oe[ne], re = tryReduce(_.sourceDB, se, ie.keys, ie.values, false);
if (re.error && re.error instanceof BuiltInError) throw re.error;
ee.push({
value: re.error ? null : re.output,
key: ie.groupKey
});
}
return {
rows: sliceResults(ee, ie.limit, ie.skip)
};
}(_, oe, ee); else if ("undefined" == typeof ee.keys) le = {
total_rows: ie,
offset: se,
rows: oe
}; else le = {
total_rows: ie,
offset: se,
rows: sliceResults(oe, ee.limit, ee.skip)
};
if (ee.update_seq) le.update_seq = _.seq;
if (ee.include_docs) {
const ne = uniq(oe.map(rowToDocId)), ie = await _.sourceDB.allDocs({
keys: ne,
include_docs: true,
conflicts: ee.conflicts,
attachments: ee.attachments,
binary: ee.binary
});
var ue = new ExportedMap;
ie.rows.forEach((function(_) {
ue.set(_.id, _.doc);
}));
oe.forEach((function(_) {
var ee = rowToDocId(_), ne = ue.get(ee);
if (ne) _.doc = ne;
}));
return le;
} else return le;
}
if ("undefined" != typeof ee.keys) {
const _ = ee.keys.map((function(_) {
const ne = {
startkey: toIndexableString([ _ ]),
endkey: toIndexableString([ _, {} ])
};
if (ee.update_seq) ne.update_seq = true;
return fetchFromView(ne);
}));
return onMapResultsReady(flatten(await Promise.all(_)));
} else {
const _ = {
descending: ee.descending
};
if (ee.update_seq) _.update_seq = true;
let ne, ie;
if ("start_key" in ee) ne = ee.start_key;
if ("startkey" in ee) ne = ee.startkey;
if ("end_key" in ee) ie = ee.end_key;
if ("endkey" in ee) ie = ee.endkey;
if ("undefined" != typeof ne) _.startkey = ee.descending ? toIndexableString([ ne, {} ]) : toIndexableString([ ne ]);
if ("undefined" != typeof ie) {
let ne = false !== ee.inclusive_end;
if (ee.descending) ne = !ne;
_.endkey = toIndexableString(ne ? [ ie, {} ] : [ ie ]);
}
if ("undefined" != typeof ee.key) {
const ne = toIndexableString([ ee.key ]), ie = toIndexableString([ ee.key, {} ]);
if (_.descending) {
_.endkey = ne;
_.startkey = ie;
} else {
_.startkey = ne;
_.endkey = ie;
}
}
if (!re) {
if ("number" == typeof ee.limit) _.limit = ee.limit;
_.skip = se;
}
return onMapResultsReady(await fetchFromView(_));
}
}(_, ee);
}))();
}
return {
query: function abstractQuery(ee, ne, re) {
const se = this;
if ("function" == typeof ne) {
re = ne;
ne = {};
}
ne = ne ? function coerceOptions(_) {
_.group_level = coerceInteger(_.group_level);
_.limit = coerceInteger(_.limit);
_.skip = coerceInteger(_.skip);
return _;
}(ne) : {};
if ("function" == typeof ee) ee = {
map: ee
};
const oe = Promise.resolve().then((function() {
return async function queryPromised(ee, ne, re) {
if ("function" == typeof ee._query) return function customQuery(_, ee, ne) {
return new Promise((function(ie, re) {
_._query(ee, ne, (function(_, ee) {
if (_) return re(_);
ie(ee);
}));
}));
}(ee, ne, re);
if (isRemote(ee)) return async function httpQuery(_, ee, ne) {
let ie, re, se = [], oe = "GET";
addHttpParam("reduce", ne, se);
addHttpParam("include_docs", ne, se);
addHttpParam("attachments", ne, se);
addHttpParam("limit", ne, se);
addHttpParam("descending", ne, se);
addHttpParam("group", ne, se);
addHttpParam("group_level", ne, se);
addHttpParam("skip", ne, se);
addHttpParam("stale", ne, se);
addHttpParam("conflicts", ne, se);
addHttpParam("startkey", ne, se, true);
addHttpParam("start_key", ne, se, true);
addHttpParam("endkey", ne, se, true);
addHttpParam("end_key", ne, se, true);
addHttpParam("inclusive_end", ne, se);
addHttpParam("key", ne, se, true);
addHttpParam("update_seq", ne, se);
se = se.join("&");
se = "" === se ? "" : "?" + se;
if ("undefined" != typeof ne.keys) {
const _ = 2e3, re = `keys=${encodeURIComponent(JSON.stringify(ne.keys))}`;
if (re.length + se.length + 1 <= _) se += ("?" === se[0] ? "&" : "?") + re; else {
oe = "POST";
if ("string" == typeof ee) ie = {
keys: ne.keys
}; else ee.keys = ne.keys;
}
}
if ("string" == typeof ee) {
const le = parseViewName(ee), ue = await _.fetch("_design/" + le[0] + "/_view/" + le[1] + se, {
headers: new h({
"Content-Type": "application/json"
}),
method: oe,
body: JSON.stringify(ie)
});
re = ue.ok;
const de = await ue.json();
if (!re) {
de.status = ue.status;
throw generateErrorFromResponse(de);
}
de.rows.forEach((function(_) {
if (_.value && _.value.error && "builtin_reduce_error" === _.value.error) throw new Error(_.reason);
}));
return new Promise((function(_) {
_(de);
})).then(postprocessAttachments(ne));
}
ie = ie || {};
Object.keys(ee).forEach((function(_) {
if (Array.isArray(ee[_])) ie[_] = ee[_]; else ie[_] = ee[_].toString();
}));
const le = await _.fetch("_temp_view" + se, {
headers: new h({
"Content-Type": "application/json"
}),
method: "POST",
body: JSON.stringify(ie)
});
re = le.ok;
const ue = await le.json();
if (!re) {
ue.status = le.status;
throw generateErrorFromResponse(ue);
}
return new Promise((function(_) {
_(ue);
})).then(postprocessAttachments(ne));
}(ee, ne, re);
const se = {
changes_batch_size: ee.__opts.view_update_changes_batch_size || CHANGES_BATCH_SIZE2
};
if ("string" != typeof ne) {
checkQueryParseError(re, ne);
tempViewQueue.add((async function() {
const ie = await createView(ee, "temp_view/temp_view", ne.map, ne.reduce, true, _);
return fin(updateView(ie, se).then((function() {
return queryView(ie, re);
})), (function() {
return ie.db.destroy();
}));
}));
return tempViewQueue.finish();
} else {
const oe = ne, le = parseViewName(oe), ue = le[0], de = le[1], fe = await ee.get("_design/" + ue);
if (!(ne = fe.views && fe.views[de])) throw new NotFoundError(`ddoc ${fe._id} has no view named ${de}`);
ie(fe, de);
checkQueryParseError(re, ne);
const he = await createView(ee, oe, ne.map, ne.reduce, false, _);
if ("ok" === re.stale || "update_after" === re.stale) {
if ("update_after" === re.stale) (0, import_immediate.default)((function() {
updateView(he, se);
}));
return queryView(he, re);
} else {
await updateView(he, se);
return queryView(he, re);
}
}
}(se, ee, ne);
}));
promisedCallback(oe, re);
return oe;
},
viewCleanup: callbackify((function() {
const ee = this;
if ("function" == typeof ee._viewCleanup) return function customViewCleanup(_) {
return new Promise((function(ee, ne) {
_._viewCleanup((function(_, ie) {
if (_) return ne(_);
ee(ie);
}));
}));
}(ee);
if (isRemote(ee)) return async function httpViewCleanup(_) {
return (await _.fetch("_view_cleanup", {
headers: new h({
"Content-Type": "application/json"
}),
method: "POST"
})).json();
}(ee); else return async function localViewCleanup(ee) {
try {
const ne = await ee.get("_local/" + _), ie = new ExportedMap;
Object.keys(ne.views).forEach((function(_) {
const ee = parseViewName(_), ne = "_design/" + ee[0], re = ee[1];
let se = ie.get(ne);
if (!se) {
se = new ExportedSet;
ie.set(ne, se);
}
se.add(re);
}));
const re = {
keys: mapToKeysArray(ie),
include_docs: true
}, se = await ee.allDocs(re), oe = {};
se.rows.forEach((function(_) {
const ee = _.key.substring(8);
ie.get(_.key).forEach((function(ie) {
let re = ee + "/" + ie;
if (!ne.views[re]) re = ie;
const se = Object.keys(ne.views[re]), le = _.doc && _.doc.views && _.doc.views[ie];
se.forEach((function(_) {
oe[_] = oe[_] || le;
}));
}));
}));
const le = Object.keys(oe).filter((function(_) {
return !oe[_];
})).map((function(_) {
return sequentialize(getQueue(_), (function() {
return new ee.constructor(_, ee.__opts).destroy();
}))();
}));
return Promise.all(le).then((function() {
return {
ok: true
};
}));
} catch (_) {
if (404 === _.status) return {
ok: true
}; else throw _;
}
}(ee);
}))
};
}
var index_es_default5 = createAbstractMapReduce;
function createBuiltInError(_) {
return new BuiltInError("builtin " + _ + " function requires map values to be numbers or number arrays");
}
function sum(_) {
for (var ee = 0, ne = 0, ie = _.length; ne < ie; ne++) {
var re = _[ne];
if ("number" != typeof re) if (Array.isArray(re)) {
ee = "number" == typeof ee ? [ ee ] : ee;
for (var se = 0, oe = re.length; se < oe; se++) {
var le = re[se];
if ("number" != typeof le) throw createBuiltInError("_sum"); else if ("undefined" == typeof ee[se]) ee.push(le); else ee[se] += le;
}
} else throw createBuiltInError("_sum"); else if ("number" == typeof ee) ee += re; else ee[0] += re;
}
return ee;
}
var log = guardedConsole.bind(null, "log"), isArray = Array.isArray, toJSON = JSON.parse;
function evalFunctionWithEval(_, ee) {
return scopeEval("return (" + _.replace(/;\s*$/, "") + ");", {
emit: ee,
sum,
log,
isArray,
toJSON
});
}
var builtInReduce = {
_sum: function(_, ee) {
return sum(ee);
},
_count: function(_, ee) {
return ee.length;
},
_stats: function(_, ee) {
return {
sum: sum(ee),
min: Math.min.apply(null, ee),
max: Math.max.apply(null, ee),
count: ee.length,
sumsqr: function sumsqr(_) {
for (var ee = 0, ne = 0, ie = _.length; ne < ie; ne++) {
var re = _[ne];
ee += re * re;
}
return ee;
}(ee)
};
}
};
function getBuiltIn(_) {
if (/^_sum/.test(_)) return builtInReduce._sum; else if (/^_count/.test(_)) return builtInReduce._count; else if (/^_stats/.test(_)) return builtInReduce._stats; else if (/^_/.test(_)) throw new Error(_ + " is not a supported reduce function.");
}
function mapper(_, ee) {
if ("function" == typeof _ && 2 === _.length) {
var ne = _;
return function(_) {
return ne(_, ee);
};
} else return evalFunctionWithEval(_.toString(), ee);
}
function reducer(_) {
var ee = _.toString(), ne = getBuiltIn(ee);
if (ne) return ne; else return evalFunctionWithEval(ee);
}
function ddocValidator(_, ee) {
var ne = _.views && _.views[ee];
if ("string" != typeof ne.map) throw new NotFoundError("ddoc " + _._id + " has no string view named " + ee + ", instead found object of type: " + typeof ne.map);
}
var localDocName = "mrviews", abstract = index_es_default5(localDocName, mapper, reducer, ddocValidator);
function query2(_, ee, ne) {
return abstract.query.call(this, _, ee, ne);
}
function viewCleanup2(_) {
return abstract.viewCleanup.call(this, _);
}
var index4 = {
query: query2,
viewCleanup: viewCleanup2
}, index_browser_es_default2 = index4, CHECKPOINT_VERSION = 1, REPLICATOR = "pouchdb", CHECKPOINT_HISTORY_SIZE = 5, LOWEST_SEQ = 0;
function updateCheckpoint(_, ee, ne, ie, re) {
return _.get(ee).catch((function(ne) {
if (404 === ne.status) {
if ("http" === _.adapter || "https" === _.adapter) explainError(404, "PouchDB is just checking if a remote checkpoint exists.");
return {
session_id: ie,
_id: ee,
history: [],
replicator: REPLICATOR,
version: CHECKPOINT_VERSION
};
}
throw ne;
})).then((function(se) {
if (!re.cancelled) if (se.last_seq !== ne) {
se.history = (se.history || []).filter((function(_) {
return _.session_id !== ie;
}));
se.history.unshift({
last_seq: ne,
session_id: ie
});
se.history = se.history.slice(0, CHECKPOINT_HISTORY_SIZE);
se.version = CHECKPOINT_VERSION;
se.replicator = REPLICATOR;
se.session_id = ie;
se.last_seq = ne;
return _.put(se).catch((function(se) {
if (409 === se.status) return updateCheckpoint(_, ee, ne, ie, re);
throw se;
}));
}
}));
}
var CheckpointerInternal = class {
constructor(_, ee, ne, ie, re) {
this.src = _;
this.target = ee;
this.id = ne;
this.returnValue = ie;
this.opts = re || {};
}
writeCheckpoint(_, ee) {
var ne = this;
return this.updateTarget(_, ee).then((function() {
return ne.updateSource(_, ee);
}));
}
updateTarget(_, ee) {
if (this.opts.writeTargetCheckpoint) return updateCheckpoint(this.target, this.id, _, ee, this.returnValue); else return Promise.resolve(true);
}
updateSource(_, ee) {
if (this.opts.writeSourceCheckpoint) {
var ne = this;
return updateCheckpoint(this.src, this.id, _, ee, this.returnValue).catch((function(_) {
if (isForbiddenError(_)) {
ne.opts.writeSourceCheckpoint = false;
return true;
}
throw _;
}));
} else return Promise.resolve(true);
}
getCheckpoint() {
var _ = this;
if (_.opts && _.opts.writeSourceCheckpoint && !_.opts.writeTargetCheckpoint) return _.src.get(_.id).then((function(_) {
return _.last_seq || LOWEST_SEQ;
})).catch((function(_) {
if (404 !== _.status) throw _;
return LOWEST_SEQ;
})); else return _.target.get(_.id).then((function(ee) {
if (_.opts && _.opts.writeTargetCheckpoint && !_.opts.writeSourceCheckpoint) return ee.last_seq || LOWEST_SEQ; else return _.src.get(_.id).then((function(_) {
if (ee.version !== _.version) return LOWEST_SEQ;
var ne;
if (ee.version) ne = ee.version.toString(); else ne = "undefined";
if (ne in comparisons) return comparisons[ne](ee, _); else return LOWEST_SEQ;
}), (function(ne) {
if (404 === ne.status && ee.last_seq) return _.src.put({
_id: _.id,
last_seq: LOWEST_SEQ
}).then((function() {
return LOWEST_SEQ;
}), (function(ne) {
if (isForbiddenError(ne)) {
_.opts.writeSourceCheckpoint = false;
return ee.last_seq;
}
return LOWEST_SEQ;
}));
throw ne;
}));
})).catch((function(_) {
if (404 !== _.status) throw _;
return LOWEST_SEQ;
}));
}
}, comparisons = {
undefined: function(_, ee) {
if (0 === collate(_.last_seq, ee.last_seq)) return ee.last_seq; else return 0;
},
1: function(_, ee) {
return compareReplicationLogs(ee, _).last_seq;
}
};
function compareReplicationLogs(_, ee) {
if (_.session_id === ee.session_id) return {
last_seq: _.last_seq,
history: _.history
}; else return compareReplicationHistory(_.history, ee.history);
}
function compareReplicationHistory(_, ee) {
var ne = _[0], ie = _.slice(1), re = ee[0], se = ee.slice(1);
if (!ne || 0 === ee.length) return {
last_seq: LOWEST_SEQ,
history: []
};
if (hasSessionId(ne.session_id, ee)) return {
last_seq: ne.last_seq,
history: _
};
if (hasSessionId(re.session_id, ie)) return {
last_seq: re.last_seq,
history: se
}; else return compareReplicationHistory(ie, se);
}
function hasSessionId(_, ee) {
var ne = ee[0], ie = ee.slice(1);
if (!_ || 0 === ee.length) return false;
if (_ === ne.session_id) return true; else return hasSessionId(_, ie);
}
function isForbiddenError(_) {
return "number" == typeof _.status && 4 === Math.floor(_.status / 100);
}
function Checkpointer(_, ee, ne, ie, re) {
if (!(this instanceof CheckpointerInternal)) return new CheckpointerInternal(_, ee, ne, ie, re); else return Checkpointer;
}
var index_es_default6 = Checkpointer;
function sortObjectPropertiesByKey(_) {
return Object.keys(_).sort(collate).reduce((function(ee, ne) {
ee[ne] = _[ne];
return ee;
}), {});
}
function generateReplicationId(_, ee, ne) {
var ie = ne.doc_ids ? ne.doc_ids.sort(collate) : "", re = ne.filter ? ne.filter.toString() : "", se = "", oe = "", le = "";
if (ne.selector) le = JSON.stringify(ne.selector);
if (ne.filter && ne.query_params) se = JSON.stringify(sortObjectPropertiesByKey(ne.query_params));
if (ne.filter && "_view" === ne.filter) oe = ne.view.toString();
return Promise.all([ _.id(), ee.id() ]).then((function(_) {
var ee = _[0] + _[1] + re + oe + se + ie + le;
return new Promise((function(_) {
binaryMd5(ee, _);
}));
})).then((function(_) {
return "_local/" + (_ = _.replace(/\//g, ".").replace(/\+/g, "_"));
}));
}
var index_es_default7 = generateReplicationId, import_events3 = __toESM(require_events());
function fileHasChanged(_, ee, ne) {
return !_._attachments || !_._attachments[ne] || _._attachments[ne].digest !== ee._attachments[ne].digest;
}
function getDocAttachments(_, ee) {
var ne = Object.keys(ee._attachments);
return Promise.all(ne.map((function(ne) {
return _.getAttachment(ee._id, ne, {
rev: ee._rev
});
})));
}
function getDocAttachmentsFromTargetOrSource(_, ee, ne) {
var ie = isRemote(ee) && !isRemote(_), re = Object.keys(ne._attachments);
if (!ie) return getDocAttachments(ee, ne); else return _.get(ne._id).then((function(ie) {
return Promise.all(re.map((function(re) {
if (fileHasChanged(ie, ne, re)) return ee.getAttachment(ne._id, re); else return _.getAttachment(ie._id, re);
})));
})).catch((function(_) {
if (404 !== _.status) throw _;
return getDocAttachments(ee, ne);
}));
}
function createBulkGetOpts(_) {
var ee = [];
Object.keys(_).forEach((function(ne) {
_[ne].missing.forEach((function(_) {
ee.push({
id: ne,
rev: _
});
}));
}));
return {
docs: ee,
revs: true,
latest: true
};
}
function getDocs(_, ee, ne, ie) {
ne = clone(ne);
var re = [], se = true;
return Promise.resolve().then((function getAllDocs() {
var oe = createBulkGetOpts(ne);
if (oe.docs.length) return _.bulkGet(oe).then((function(ne) {
if (ie.cancelled) throw new Error("cancelled");
return Promise.all(ne.results.map((function(ne) {
return Promise.all(ne.docs.map((function(ne) {
var ie = ne.ok;
if (ne.error) se = false;
if (!ie || !ie._attachments) return ie; else return getDocAttachmentsFromTargetOrSource(ee, _, ie).then((function(_) {
var ee = Object.keys(ie._attachments);
_.forEach((function(_, ne) {
var re = ie._attachments[ee[ne]];
delete re.stub;
delete re.length;
re.data = _;
}));
return ie;
}));
})));
}))).then((function(_) {
re = re.concat(flatten(_).filter(Boolean));
}));
}));
})).then((function returnResult() {
return {
ok: se,
docs: re
};
}));
}
var STARTING_BACK_OFF = 0;
function backOff(_, ee, ne, ie) {
if (false !== _.retry) {
if ("function" != typeof _.back_off_function) _.back_off_function = defaultBackOff;
ee.emit("requestError", ne);
if ("active" === ee.state || "pending" === ee.state) {
ee.emit("paused", ne);
ee.state = "stopped";
var re = function backoffTimeSet() {
_.current_back_off = STARTING_BACK_OFF;
};
ee.once("paused", (function removeBackOffTimeSet() {
ee.removeListener("active", re);
}));
ee.once("active", re);
}
_.current_back_off = _.current_back_off || STARTING_BACK_OFF;
_.current_back_off = _.back_off_function(_.current_back_off);
setTimeout(ie, _.current_back_off);
} else {
ee.emit("error", ne);
ee.removeAllListeners();
}
}
function replicate(_, ee, ne, ie, re) {
var se, oe, le, ue, de = [], fe = {
seq: 0,
changes: [],
docs: []
}, he = false, pe = false, ge = false, me = 0, ye = 0, ve = ne.continuous || ne.live || false, Se = ne.batch_size || 100, Ee = ne.batches_limit || 10, Ce = ne.style || "all_docs", we = false, Oe = ne.doc_ids, ke = ne.selector, xe = [], Ae = uuid();
re = re || {
ok: true,
start_time: (new Date).toISOString(),
docs_read: 0,
docs_written: 0,
doc_write_failures: 0,
errors: []
};
var Le = {};
ie.ready(_, ee);
function initCheckpointer() {
if (le) return Promise.resolve(); else return index_es_default7(_, ee, ne).then((function(re) {
oe = re;
var se = {};
if (false === ne.checkpoint) se = {
writeSourceCheckpoint: false,
writeTargetCheckpoint: false
}; else if ("source" === ne.checkpoint) se = {
writeSourceCheckpoint: true,
writeTargetCheckpoint: false
}; else if ("target" === ne.checkpoint) se = {
writeSourceCheckpoint: false,
writeTargetCheckpoint: true
}; else se = {
writeSourceCheckpoint: true,
writeTargetCheckpoint: true
};
le = new index_es_default6(_, ee, oe, ie, se);
}));
}
function writeDocs() {
xe = [];
if (0 !== se.docs.length) {
var _ = se.docs, oe = {
timeout: ne.timeout
};
return ee.bulkDocs({
docs: _,
new_edits: false
}, oe).then((function(ee) {
if (ie.cancelled) {
completeReplication();
throw new Error("cancelled");
}
var ne = Object.create(null);
ee.forEach((function(_) {
if (_.error) ne[_.id] = _;
}));
var se = Object.keys(ne).length;
re.doc_write_failures += se;
re.docs_written += _.length - se;
_.forEach((function(_) {
var ee = ne[_._id];
if (ee) {
re.errors.push(ee);
var se = (ee.name || "").toLowerCase();
if ("unauthorized" === se || "forbidden" === se) ie.emit("denied", clone(ee)); else throw ee;
} else xe.push(_);
}));
}), (function(ee) {
re.doc_write_failures += _.length;
throw ee;
}));
}
}
function finishBatch() {
if (se.error) throw new Error("There was a problem getting docs.");
re.last_seq = ye = se.seq;
var ee = clone(re);
if (xe.length) {
ee.docs = xe;
if ("number" == typeof se.pending) {
ee.pending = se.pending;
delete se.pending;
}
ie.emit("change", ee);
}
he = true;
_.info().then((function(ee) {
var ne = _.activeTasks.get(ue);
if (se && ne) {
var ie = ne.completed_items || 0, re = parseInt(ee.update_seq, 10) - parseInt(me, 10);
_.activeTasks.update(ue, {
completed_items: ie + se.changes.length,
total_items: re
});
}
}));
return le.writeCheckpoint(se.seq, Ae).then((function() {
ie.emit("checkpoint", {
checkpoint: se.seq
});
he = false;
if (ie.cancelled) {
completeReplication();
throw new Error("cancelled");
}
se = void 0;
getChanges();
})).catch((function(_) {
onCheckpointError(_);
throw _;
}));
}
function getBatchDocs() {
return getDocs(_, ee, se.diffs, ie).then((function(_) {
se.error = !_.ok;
_.docs.forEach((function(_) {
delete se.diffs[_._id];
re.docs_read++;
se.docs.push(_);
}));
}));
}
function startNextBatch() {
if (!ie.cancelled && !se) if (0 !== de.length) {
se = de.shift();
ie.emit("checkpoint", {
start_next_batch: se.seq
});
(function getDiffs() {
var _ = {};
se.changes.forEach((function(ee) {
ie.emit("checkpoint", {
revs_diff: ee
});
if ("_user/" !== ee.id) _[ee.id] = ee.changes.map((function(_) {
return _.rev;
}));
}));
return ee.revsDiff(_).then((function(_) {
if (ie.cancelled) {
completeReplication();
throw new Error("cancelled");
}
se.diffs = _;
}));
})().then(getBatchDocs).then(writeDocs).then(finishBatch).then(startNextBatch).catch((function(_) {
abortReplication("batch processing terminated with error", _);
}));
} else processPendingBatch(true);
}
function processPendingBatch(_) {
if (0 !== fe.changes.length) {
if (_ || pe || fe.changes.length >= Se) {
de.push(fe);
fe = {
seq: 0,
changes: [],
docs: []
};
if ("pending" === ie.state || "stopped" === ie.state) {
ie.state = "active";
ie.emit("active");
}
startNextBatch();
}
} else if (0 === de.length && !se) {
if (ve && Le.live || pe) {
ie.state = "pending";
ie.emit("paused");
}
if (pe) completeReplication();
}
}
function abortReplication(_, ee) {
if (!ge) {
if (!ee.message) ee.message = _;
re.ok = false;
re.status = "aborting";
de = [];
fe = {
seq: 0,
changes: [],
docs: []
};
completeReplication(ee);
}
}
function completeReplication(se) {
if (!ge) {
if (ie.cancelled) {
re.status = "cancelled";
if (he) return;
}
re.status = re.status || "complete";
re.end_time = (new Date).toISOString();
re.last_seq = ye;
ge = true;
_.activeTasks.remove(ue, se);
if (se) {
(se = createError(se)).result = re;
var oe = (se.name || "").toLowerCase();
if ("unauthorized" === oe || "forbidden" === oe) {
ie.emit("error", se);
ie.removeAllListeners();
} else backOff(ne, ie, se, (function() {
replicate(_, ee, ne, ie);
}));
} else {
ie.emit("complete", re);
ie.removeAllListeners();
}
}
}
function onChange(ee, re, se) {
if (ie.cancelled) return completeReplication();
if ("number" == typeof re) fe.pending = re;
if (filterChange(ne)(ee)) {
fe.seq = ee.seq || se;
fe.changes.push(ee);
ie.emit("checkpoint", {
pending_batch: fe.seq
});
(0, import_immediate.default)((function() {
processPendingBatch(0 === de.length && Le.live);
}));
} else {
var oe = _.activeTasks.get(ue);
if (oe) {
var le = oe.completed_items || 0;
_.activeTasks.update(ue, {
completed_items: ++le
});
}
}
}
function onChangesComplete(_) {
we = false;
if (ie.cancelled) return completeReplication();
if (_.results.length > 0) {
Le.since = _.results[_.results.length - 1].seq;
getChanges();
processPendingBatch(true);
} else {
var complete = function() {
if (ve) {
Le.live = true;
getChanges();
} else pe = true;
processPendingBatch(true);
};
if (!se && 0 === _.results.length) {
he = true;
le.writeCheckpoint(_.last_seq, Ae).then((function() {
he = false;
re.last_seq = ye = _.last_seq;
if (ie.cancelled) {
completeReplication();
throw new Error("cancelled");
} else complete();
})).catch(onCheckpointError);
} else complete();
}
}
function onChangesError(_) {
we = false;
if (ie.cancelled) return completeReplication();
abortReplication("changes rejected", _);
}
function getChanges() {
if (!we && !pe && de.length < Ee) {
we = true;
if (ie._changes) {
ie.removeListener("cancel", ie._abortChanges);
ie._changes.cancel();
}
ie.once("cancel", abortChanges);
var ee = _.changes(Le).on("change", onChange);
ee.then(removeListener, removeListener);
ee.then(onChangesComplete).catch(onChangesError);
if (ne.retry) {
ie._changes = ee;
ie._abortChanges = abortChanges;
}
}
function abortChanges() {
ee.cancel();
}
function removeListener() {
ie.removeListener("cancel", abortChanges);
}
}
function createTask(ee) {
return _.info().then((function(ie) {
var re = "undefined" == typeof ne.since ? parseInt(ie.update_seq, 10) - parseInt(ee, 10) : parseInt(ie.update_seq, 10);
ue = _.activeTasks.add({
name: `${ve ? "continuous " : ""}replication from ${ie.db_name}`,
total_items: re
});
return ee;
}));
}
function startChanges() {
initCheckpointer().then((function() {
if (!ie.cancelled) return le.getCheckpoint().then(createTask).then((function(_) {
me = _;
Le = {
since: ye = _,
limit: Se,
batch_size: Se,
style: Ce,
doc_ids: Oe,
selector: ke,
return_docs: true
};
if (ne.filter) if ("string" != typeof ne.filter) Le.include_docs = true; else Le.filter = ne.filter;
if ("heartbeat" in ne) Le.heartbeat = ne.heartbeat;
if ("timeout" in ne) Le.timeout = ne.timeout;
if (ne.query_params) Le.query_params = ne.query_params;
if (ne.view) Le.view = ne.view;
getChanges();
})); else completeReplication();
})).catch((function(_) {
abortReplication("getCheckpoint rejected with ", _);
}));
}
function onCheckpointError(_) {
he = false;
abortReplication("writeCheckpoint completed with error", _);
}
if (!ie.cancelled) {
if (!ie._addedListeners) {
ie.once("cancel", completeReplication);
if ("function" == typeof ne.complete) {
ie.once("error", ne.complete);
ie.once("complete", (function(_) {
ne.complete(null, _);
}));
}
ie._addedListeners = true;
}
if ("undefined" == typeof ne.since) startChanges(); else initCheckpointer().then((function() {
he = true;
return le.writeCheckpoint(ne.since, Ae);
})).then((function() {
he = false;
if (!ie.cancelled) {
ye = ne.since;
startChanges();
} else completeReplication();
})).catch(onCheckpointError);
} else completeReplication();
}
var Replication = class extends import_events3.default {
constructor() {
super();
this.cancelled = false;
this.state = "pending";
const _ = new Promise(((_, ee) => {
this.once("complete", _);
this.once("error", ee);
}));
this.then = function(ee, ne) {
return _.then(ee, ne);
};
this.catch = function(ee) {
return _.catch(ee);
};
this.catch((function() {}));
}
cancel() {
this.cancelled = true;
this.state = "cancelled";
this.emit("cancel");
}
ready(_, ee) {
if (this._readyCalled) return;
this._readyCalled = true;
const onDestroy2 = () => {
this.cancel();
};
_.once("destroyed", onDestroy2);
ee.once("destroyed", onDestroy2);
function cleanup() {
_.removeListener("destroyed", onDestroy2);
ee.removeListener("destroyed", onDestroy2);
}
this.once("complete", cleanup);
this.once("error", cleanup);
}
};
function toPouch(_, ee) {
var ne = ee.PouchConstructor;
if ("string" == typeof _) return new ne(_, ee); else return _;
}
function replicateWrapper(_, ee, ne, ie) {
if ("function" == typeof ne) {
ie = ne;
ne = {};
}
if ("undefined" == typeof ne) ne = {};
if (ne.doc_ids && !Array.isArray(ne.doc_ids)) throw createError(BAD_REQUEST, "`doc_ids` filter parameter is not a list.");
ne.complete = ie;
(ne = clone(ne)).continuous = ne.continuous || ne.live;
ne.retry = "retry" in ne ? ne.retry : false;
ne.PouchConstructor = ne.PouchConstructor || this;
var re = new Replication(ne);
replicate(toPouch(_, ne), toPouch(ee, ne), ne, re);
return re;
}
function sync(_, ee, ne, ie) {
if ("function" == typeof ne) {
ie = ne;
ne = {};
}
if ("undefined" == typeof ne) ne = {};
(ne = clone(ne)).PouchConstructor = ne.PouchConstructor || this;
_ = toPouch(_, ne);
ee = toPouch(ee, ne);
return new Sync(_, ee, ne, ie);
}
var Sync = class extends import_events3.default {
constructor(_, ee, ne, ie) {
super();
this.canceled = false;
const re = ne.push ? assign$2({}, ne, ne.push) : ne, se = ne.pull ? assign$2({}, ne, ne.pull) : ne;
this.push = replicateWrapper(_, ee, re);
this.pull = replicateWrapper(ee, _, se);
this.pushPaused = true;
this.pullPaused = true;
const pullChange = _ => {
this.emit("change", {
direction: "pull",
change: _
});
}, pushChange = _ => {
this.emit("change", {
direction: "push",
change: _
});
}, pushDenied = _ => {
this.emit("denied", {
direction: "push",
doc: _
});
}, pullDenied = _ => {
this.emit("denied", {
direction: "pull",
doc: _
});
}, pushPaused = () => {
this.pushPaused = true;
if (this.pullPaused) this.emit("paused");
}, pullPaused = () => {
this.pullPaused = true;
if (this.pushPaused) this.emit("paused");
}, pushActive = () => {
this.pushPaused = false;
if (this.pullPaused) this.emit("active", {
direction: "push"
});
}, pullActive = () => {
this.pullPaused = false;
if (this.pushPaused) this.emit("active", {
direction: "pull"
});
};
let oe = {};
const removeAll = _ => (ee, ne) => {
if ("change" === ee && (ne === pullChange || ne === pushChange) || "denied" === ee && (ne === pullDenied || ne === pushDenied) || "paused" === ee && (ne === pullPaused || ne === pushPaused) || "active" === ee && (ne === pullActive || ne === pushActive)) {
if (!(ee in oe)) oe[ee] = {};
oe[ee][_] = true;
if (2 === Object.keys(oe[ee]).length) this.removeAllListeners(ee);
}
};
if (ne.live) {
this.push.on("complete", this.pull.cancel.bind(this.pull));
this.pull.on("complete", this.push.cancel.bind(this.push));
}
function addOneListener(_, ee, ne) {
if (-1 == _.listeners(ee).indexOf(ne)) _.on(ee, ne);
}
this.on("newListener", (function(_) {
if ("change" === _) {
addOneListener(this.pull, "change", pullChange);
addOneListener(this.push, "change", pushChange);
} else if ("denied" === _) {
addOneListener(this.pull, "denied", pullDenied);
addOneListener(this.push, "denied", pushDenied);
} else if ("active" === _) {
addOneListener(this.pull, "active", pullActive);
addOneListener(this.push, "active", pushActive);
} else if ("paused" === _) {
addOneListener(this.pull, "paused", pullPaused);
addOneListener(this.push, "paused", pushPaused);
}
}));
this.on("removeListener", (function(_) {
if ("change" === _) {
this.pull.removeListener("change", pullChange);
this.push.removeListener("change", pushChange);
} else if ("denied" === _) {
this.pull.removeListener("denied", pullDenied);
this.push.removeListener("denied", pushDenied);
} else if ("active" === _) {
this.pull.removeListener("active", pullActive);
this.push.removeListener("active", pushActive);
} else if ("paused" === _) {
this.pull.removeListener("paused", pullPaused);
this.push.removeListener("paused", pushPaused);
}
}));
this.pull.on("removeListener", removeAll("pull"));
this.push.on("removeListener", removeAll("push"));
const le = Promise.all([ this.push, this.pull ]).then((_ => {
const ee = {
push: _[0],
pull: _[1]
};
this.emit("complete", ee);
if (ie) ie(null, ee);
this.removeAllListeners();
return ee;
}), (_ => {
this.cancel();
if (ie) ie(_); else this.emit("error", _);
this.removeAllListeners();
if (ie) throw _;
}));
this.then = function(_, ee) {
return le.then(_, ee);
};
this.catch = function(_) {
return le.catch(_);
};
}
cancel() {
if (!this.canceled) {
this.canceled = true;
this.push.cancel();
this.pull.cancel();
}
}
};
function replication(_) {
_.replicate = replicateWrapper;
_.sync = sync;
Object.defineProperty(_.prototype, "replicate", {
get: function() {
var _ = this;
if ("undefined" == typeof this.replicateMethods) this.replicateMethods = {
from: function(ee, ne, ie) {
return _.constructor.replicate(ee, _, ne, ie);
},
to: function(ee, ne, ie) {
return _.constructor.replicate(_, ee, ne, ie);
}
};
return this.replicateMethods;
}
});
_.prototype.sync = function(_, ee, ne) {
return this.constructor.sync(this, _, ee, ne);
};
}
var index_es_default8 = replication;
function massageCreateIndexRequest(_) {
if (!(_ = clone(_)).index) _.index = {};
[ "type", "name", "ddoc" ].forEach((function(ee) {
if (_.index[ee]) {
_[ee] = _.index[ee];
delete _.index[ee];
}
}));
if (_.fields) {
_.index.fields = _.fields;
delete _.fields;
}
if (!_.type) _.type = "json";
return _;
}
function checkFieldValueType(_, ee, ne) {
var ie = "", re = ee, se = true;
if (-1 !== [ "$in", "$nin", "$or", "$and", "$mod", "$nor", "$all" ].indexOf(_)) if (!Array.isArray(ee)) ie = "Query operator " + _ + " must be an array.";
if (-1 !== [ "$not", "$elemMatch", "$allMatch" ].indexOf(_)) if (!(!Array.isArray(ee) && "object" == typeof ee && null !== ee)) ie = "Query operator " + _ + " must be an object.";
if ("$mod" === _ && Array.isArray(ee)) if (2 !== ee.length) ie = "Query operator $mod must be in the format [divisor, remainder], where divisor and remainder are both integers."; else {
var oe = ee[0], le = ee[1];
if (0 === oe) {
ie = "Query operator $mod's divisor cannot be 0, cannot divide by zero.";
se = false;
}
if ("number" != typeof oe || parseInt(oe, 10) !== oe) {
ie = "Query operator $mod's divisor is not an integer.";
re = oe;
}
if (parseInt(le, 10) !== le) {
ie = "Query operator $mod's remainder is not an integer.";
re = le;
}
}
if ("$exists" === _) if ("boolean" != typeof ee) ie = "Query operator $exists must be a boolean.";
if ("$type" === _) {
var ue = [ "null", "boolean", "number", "string", "array", "object" ], de = '"' + ue.slice(0, ue.length - 1).join('", "') + '", or "' + ue[ue.length - 1] + '"';
if ("string" != typeof ee) ie = "Query operator $type must be a string. Supported values: " + de + "."; else if (-1 == ue.indexOf(ee)) ie = "Query operator $type must be a string. Supported values: " + de + ".";
}
if ("$size" === _) if (parseInt(ee, 10) !== ee) ie = "Query operator $size must be a integer.";
if ("$regex" === _) if ("string" != typeof ee) if (ne) ie = "Query operator $regex must be a string."; else if (!(ee instanceof RegExp)) ie = "Query operator $regex must be a string or an instance of a javascript regular expression.";
if (ie) {
if (se) ie += " Received" + (null === re ? " " : Array.isArray(re) ? " array" : " " + typeof re) + ": " + ("object" == typeof re && null !== re ? JSON.stringify(re, null, "\t") : re);
throw new Error(ie);
}
}
var requireValidation = [ "$all", "$allMatch", "$and", "$elemMatch", "$exists", "$in", "$mod", "$nin", "$nor", "$not", "$or", "$regex", "$size", "$type" ], arrayTypeComparisonOperators = [ "$in", "$nin", "$mod", "$all" ], equalityOperators = [ "$eq", "$gt", "$gte", "$lt", "$lte" ];
function validateSelector(_, ee) {
if (Array.isArray(_)) {
for (var ne of _) if ("object" == typeof ne && null !== oe) validateSelector(ne, ee);
} else for (var ie = Object.keys(_), re = 0; re < ie.length; re++) {
var se = ie[re], oe = _[se];
if (-1 !== requireValidation.indexOf(se)) checkFieldValueType(se, oe, ee);
if (-1 === equalityOperators.indexOf(se)) if (-1 === arrayTypeComparisonOperators.indexOf(se)) if ("object" == typeof oe && null !== oe) validateSelector(oe, ee);
}
}
function dbFetch(_, ee, ne, ie) {
var re, se;
ne.headers = new h({
"Content-type": "application/json"
});
_.fetch(ee, ne).then((function(_) {
re = _.status;
se = _.ok;
return _.json();
})).then((function(_) {
if (!se) {
_.status = re;
var ee = generateErrorFromResponse(_);
ie(ee);
} else ie(null, _);
})).catch(ie);
}
function createIndex(_, ee, ne) {
ee = massageCreateIndexRequest(ee);
dbFetch(_, "_index", {
method: "POST",
body: JSON.stringify(ee)
}, ne);
}
function find(_, ee, ne) {
validateSelector(ee.selector, true);
dbFetch(_, "_find", {
method: "POST",
body: JSON.stringify(ee)
}, ne);
}
function explain(_, ee, ne) {
dbFetch(_, "_explain", {
method: "POST",
body: JSON.stringify(ee)
}, ne);
}
function getIndexes(_, ee) {
dbFetch(_, "_index", {
method: "GET"
}, ee);
}
function deleteIndex(_, ee, ne) {
var ie = ee.ddoc, re = ee.type || "json", se = ee.name;
if (!ie) return ne(new Error("you must provide an index's ddoc"));
if (!se) return ne(new Error("you must provide an index's name"));
dbFetch(_, "_index/" + [ ie, re, se ].map(encodeURIComponent).join("/"), {
method: "DELETE"
}, ne);
}
function callbackify2(_) {
return function(...ee) {
var ne = ee.pop(), ie = _.apply(this, ee);
promisedCallback2(ie, ne);
return ie;
};
}
function promisedCallback2(_, ee) {
_.then((function(_) {
(0, import_immediate.default)((function() {
ee(null, _);
}));
}), (function(_) {
(0, import_immediate.default)((function() {
ee(_);
}));
}));
return _;
}
var flatten2 = function(..._) {
for (var ee = [], ne = 0, ie = _.length; ne < ie; ne++) {
var re = _[ne];
if (Array.isArray(re)) ee = ee.concat(flatten2.apply(null, re)); else ee.push(re);
}
return ee;
};
function mergeObjects(_) {
for (var ee = {}, ne = 0, ie = _.length; ne < ie; ne++) ee = assign$2(ee, _[ne]);
return ee;
}
function pick2(_, ee) {
for (var ne = {}, ie = 0, re = ee.length; ie < re; ie++) {
var se = parseField(ee[ie]), oe = getFieldFromDoc(_, se);
if ("undefined" != typeof oe) setFieldInDoc(ne, se, oe);
}
return ne;
}
function oneArrayIsSubArrayOfOther(_, ee) {
for (var ne = 0, ie = Math.min(_.length, ee.length); ne < ie; ne++) if (_[ne] !== ee[ne]) return false;
return true;
}
function oneArrayIsStrictSubArrayOfOther(_, ee) {
if (_.length > ee.length) return false; else return oneArrayIsSubArrayOfOther(_, ee);
}
function oneSetIsSubArrayOfOther(_, ee) {
_ = _.slice();
for (var ne = 0, ie = ee.length; ne < ie; ne++) {
var re = ee[ne];
if (!_.length) break;
var se = _.indexOf(re);
if (-1 === se) return false; else _.splice(se, 1);
}
return true;
}
function arrayToObject(_) {
for (var ee = {}, ne = 0, ie = _.length; ne < ie; ne++) ee[_[ne]] = true;
return ee;
}
function max2(_, ee) {
for (var ne = null, ie = -1, re = 0, se = _.length; re < se; re++) {
var oe = _[re], le = ee(oe);
if (le > ie) {
ie = le;
ne = oe;
}
}
return ne;
}
function arrayEquals(_, ee) {
if (_.length !== ee.length) return false;
for (var ne = 0, ie = _.length; ne < ie; ne++) if (_[ne] !== ee[ne]) return false;
return true;
}
function uniq2(_) {
for (var ee = {}, ne = 0; ne < _.length; ne++) ee["$" + _[ne]] = true;
return Object.keys(ee).map((function(_) {
return _.substring(1);
}));
}
function createDeepMultiMapper(_, ee, ne) {
return function(ie) {
if (!ne || matchesSelector(ie, ne)) {
for (var re = [], se = 0, oe = _.length; se < oe; se++) {
for (var le = parseField(_[se]), ue = ie, de = 0, fe = le.length; de < fe; de++) if ("undefined" == typeof (ue = ue[le[de]])) return;
re.push(ue);
}
ee(re);
}
};
}
function createDeepSingleMapper(_, ee, ne) {
var ie = parseField(_);
return function(_) {
if (!ne || matchesSelector(_, ne)) {
for (var re = _, se = 0, oe = ie.length; se < oe; se++) if ("undefined" == typeof (re = re[ie[se]])) return;
ee(re);
}
};
}
function createShallowSingleMapper(_, ee, ne) {
return function(ie) {
if (!ne || matchesSelector(ie, ne)) ee(ie[_]);
};
}
function createShallowMultiMapper(_, ee, ne) {
return function(ie) {
if (!ne || matchesSelector(ie, ne)) {
for (var re = [], se = 0, oe = _.length; se < oe; se++) re.push(ie[_[se]]);
ee(re);
}
};
}
function checkShallow(_) {
for (var ee = 0, ne = _.length; ee < ne; ee++) if (-1 !== _[ee].indexOf(".")) return false;
return true;
}
function createMapper(_, ee, ne) {
var ie = checkShallow(_), re = 1 === _.length;
if (ie) if (re) return createShallowSingleMapper(_[0], ee, ne); else return createShallowMultiMapper(_, ee, ne); else if (re) return createDeepSingleMapper(_[0], ee, ne); else return createDeepMultiMapper(_, ee, ne);
}
function mapper2(_, ee) {
return createMapper(Object.keys(_.fields), ee, _.partial_filter_selector);
}
function reducer2() {
throw new Error("reduce not supported");
}
function ddocValidator2(_, ee) {
var ne = _.views[ee];
if (!ne.map || !ne.map.fields) throw new Error("ddoc " + _._id + " with view " + ee + " doesn't have map.fields defined. maybe it wasn't created by this plugin?");
}
var abstractMapper = index_es_default5("indexes", mapper2, reducer2, ddocValidator2);
function abstractMapper$1(_) {
if (_._customFindAbstractMapper) return {
query: function addQueryFallback(ee, ne) {
var ie = abstractMapper.query.bind(this);
return _._customFindAbstractMapper.query.call(this, ee, ne, ie);
},
viewCleanup: function addViewCleanupFallback() {
var ee = abstractMapper.viewCleanup.bind(this);
return _._customFindAbstractMapper.viewCleanup.call(this, ee);
}
}; else return abstractMapper;
}
function massageSort(_) {
if (!Array.isArray(_)) throw new Error("invalid sort json - should be an array");
return _.map((function(_) {
if ("string" == typeof _) {
var ee = {};
ee[_] = "asc";
return ee;
} else return _;
}));
}
function massageUseIndex(_) {
var ee = [];
if ("string" == typeof _) ee.push(_); else ee = _;
return ee.map((function(_) {
return _.replace("_design/", "");
}));
}
function massageIndexDef(_) {
_.fields = _.fields.map((function(_) {
if ("string" == typeof _) {
var ee = {};
ee[_] = "asc";
return ee;
}
return _;
}));
if (_.partial_filter_selector) _.partial_filter_selector = massageSelector(_.partial_filter_selector);
return _;
}
function getKeyFromDoc(_, ee) {
for (var ne = [], ie = 0; ie < ee.def.fields.length; ie++) {
var re = getKey(ee.def.fields[ie]);
ne.push(getFieldFromDoc(_, parseField(re)));
}
return ne;
}
function filterInclusiveStart(_, ee, ne) {
for (var ie = ne.def.fields, re = 0, se = _.length; re < se; re++) {
var oe = getKeyFromDoc(_[re].doc, ne);
if (1 === ie.length) oe = oe[0]; else for (;oe.length > ee.length; ) oe.pop();
if (Math.abs(collate(oe, ee)) > 0) break;
}
return re > 0 ? _.slice(re) : _;
}
function reverseOptions(_) {
var ee = clone(_);
delete ee.startkey;
delete ee.endkey;
delete ee.inclusive_start;
delete ee.inclusive_end;
if ("endkey" in _) ee.startkey = _.endkey;
if ("startkey" in _) ee.endkey = _.startkey;
if ("inclusive_start" in _) ee.inclusive_end = _.inclusive_start;
if ("inclusive_end" in _) ee.inclusive_start = _.inclusive_end;
return ee;
}
function validateIndex(_) {
var ee = _.fields.filter((function(_) {
return "asc" === getValue(_);
}));
if (0 !== ee.length && ee.length !== _.fields.length) throw new Error("unsupported mixed sorting");
}
function validateSort(_, ee) {
if (ee.defaultUsed && _.sort) {
var ne = _.sort.filter((function(_) {
return "_id" !== Object.keys(_)[0];
})).map((function(_) {
return Object.keys(_)[0];
}));
if (ne.length > 0) throw new Error('Cannot sort on field(s) "' + ne.join(",") + '" when using the default index');
}
if (!ee.defaultUsed) ;
}
function validateFindRequest(_) {
if ("object" != typeof _.selector) throw new Error("you must provide a selector when you find()");
}
function getUserFields(_, ee) {
var ne, ie = Object.keys(_), re = ee ? ee.map(getKey) : [];
if (ie.length >= re.length) ne = ie; else ne = re;
if (0 === re.length) return {
fields: ne
}; else return {
fields: ne = ne.sort((function(_, ee) {
var ne = re.indexOf(_);
if (-1 === ne) ne = Number.MAX_VALUE;
var ie = re.indexOf(ee);
if (-1 === ie) ie = Number.MAX_VALUE;
return ne < ie ? -1 : ne > ie ? 1 : 0;
})),
sortOrder: ee.map(getKey)
};
}
function createIndex$1(_, ee) {
var ne, ie = clone((ee = massageCreateIndexRequest(ee)).index);
ee.index = massageIndexDef(ee.index);
validateIndex(ee.index);
function getMd5() {
return ne || (ne = stringMd5(JSON.stringify(ee)));
}
var re = ee.name || "idx-" + getMd5(), se = ee.ddoc || "idx-" + getMd5(), oe = "_design/" + se, le = false, ue = false;
_.constructor.emit("debug", [ "find", "creating index", oe ]);
return upsert(_, oe, (function updateDdoc(_) {
if (_._rev && "query" !== _.language) le = true;
_.language = "query";
_.views = _.views || {};
if (ue = !!_.views[re]) return false;
_.views[re] = {
map: {
fields: mergeObjects(ee.index.fields),
partial_filter_selector: ee.index.partial_filter_selector
},
reduce: "_count",
options: {
def: ie
}
};
return _;
})).then((function() {
if (le) throw new Error('invalid language for ddoc with id "' + oe + '" (should be "query")');
})).then((function() {
var ee = se + "/" + re;
return abstractMapper$1(_).query.call(_, ee, {
limit: 0,
reduce: false
}).then((function() {
return {
id: oe,
name: re,
result: ue ? "exists" : "created"
};
}));
}));
}
function getIndexes$1(_) {
return _.allDocs({
startkey: "_design/",
endkey: "_design/",
include_docs: true
}).then((function(_) {
var ee = {
indexes: [ {
ddoc: null,
name: "_all_docs",
type: "special",
def: {
fields: [ {
_id: "asc"
} ]
}
} ]
};
ee.indexes = flatten2(ee.indexes, _.rows.filter((function(_) {
return "query" === _.doc.language;
})).map((function(_) {
return (void 0 !== _.doc.views ? Object.keys(_.doc.views) : []).map((function(ee) {
var ne = _.doc.views[ee];
return {
ddoc: _.id,
name: ee,
type: "json",
def: massageIndexDef(ne.options.def)
};
}));
})));
ee.indexes.sort((function(_, ee) {
return compare(_.name, ee.name);
}));
ee.total_rows = ee.indexes.length;
return ee;
}));
}
var COLLATE_LO = null, COLLATE_HI = {
"": {}
}, SHORT_CIRCUIT_QUERY = {
queryOpts: {
limit: 0,
startkey: COLLATE_HI,
endkey: COLLATE_LO
},
inMemoryFields: []
};
function checkFieldInIndex(_, ee) {
for (var ne = _.def.fields.map(getKey), ie = 0, re = ne.length; ie < re; ie++) if (ee === ne[ie]) return true;
return false;
}
function userOperatorLosesPrecision(_, ee) {
return "$eq" !== getKey(_[ee]);
}
function sortFieldsByIndex(_, ee) {
var ne = ee.def.fields.map(getKey);
return _.slice().sort((function(_, ee) {
var ie = ne.indexOf(_), re = ne.indexOf(ee);
if (-1 === ie) ie = Number.MAX_VALUE;
if (-1 === re) re = Number.MAX_VALUE;
return compare(ie, re);
}));
}
function getBasicInMemoryFields(_, ee, ne) {
for (var ie = false, re = 0, se = (ne = sortFieldsByIndex(ne, _)).length; re < se; re++) {
var oe = ne[re];
if (ie || !checkFieldInIndex(_, oe)) return ne.slice(re);
if (re < se - 1 && userOperatorLosesPrecision(ee, oe)) ie = true;
}
return [];
}
function getInMemoryFieldsFromNe(_) {
var ee = [];
Object.keys(_).forEach((function(ne) {
var ie = _[ne];
Object.keys(ie).forEach((function(_) {
if ("$ne" === _) ee.push(ne);
}));
}));
return ee;
}
function getInMemoryFields(_, ee, ne, ie) {
return sortFieldsByIndex(uniq2(flatten2(_, getBasicInMemoryFields(ee, ne, ie), getInMemoryFieldsFromNe(ne))), ee);
}
function checkIndexFieldsMatch(_, ee, ne) {
if (ee) {
var ie = oneArrayIsStrictSubArrayOfOther(ee, _), re = oneArrayIsSubArrayOfOther(ne, _);
return ie && re;
}
return oneSetIsSubArrayOfOther(ne, _);
}
var logicalMatchers = [ "$eq", "$gt", "$gte", "$lt", "$lte" ];
function isNonLogicalMatcher(_) {
return -1 === logicalMatchers.indexOf(_);
}
function checkFieldsLogicallySound(_, ee) {
var ne = ee[_[0]];
if ("undefined" == typeof ne) return true; else return !(1 === Object.keys(ne).length && "$ne" === getKey(ne));
}
function checkIndexMatches(_, ee, ne, ie) {
var re = _.def.fields.map(getKey);
if (!checkIndexFieldsMatch(re, ee, ne)) return false; else return checkFieldsLogicallySound(re, ie);
}
function findMatchingIndexes(_, ee, ne, ie) {
return ie.filter((function(ie) {
return checkIndexMatches(ie, ne, ee, _);
}));
}
function findBestMatchingIndex(_, ee, ne, ie, re) {
var se = findMatchingIndexes(_, ee, ne, ie);
if (0 === se.length) {
if (re) throw {
error: "no_usable_index",
message: "There is no index available for this selector."
};
var oe = ie[0];
oe.defaultUsed = true;
return oe;
}
if (1 === se.length && !re) return se[0];
var le = arrayToObject(ee);
if (re) {
var ue = "_design/" + re[0], de = 2 === re.length ? re[1] : false, fe = se.find((function(_) {
if (de && _.ddoc === ue && de === _.name) return true;
if (_.ddoc === ue) return true; else return false;
}));
if (!fe) throw {
error: "unknown_error",
message: "Could not find that index or could not use that index for the query"
};
return fe;
}
return max2(se, (function scoreIndex(_) {
for (var ee = _.def.fields.map(getKey), ne = 0, ie = 0, re = ee.length; ie < re; ie++) {
var se = ee[ie];
if (le[se]) ne++;
}
return ne;
}));
}
function getSingleFieldQueryOptsFor(_, ee) {
switch (_) {
case "$eq":
return {
key: ee
};
case "$lte":
return {
endkey: ee
};
case "$gte":
return {
startkey: ee
};
case "$lt":
return {
endkey: ee,
inclusive_end: false
};
case "$gt":
return {
startkey: ee,
inclusive_start: false
};
}
return {
startkey: COLLATE_LO
};
}
function getSingleFieldCoreQueryPlan(_, ee) {
var ne, ie = getKey(ee.def.fields[0]), re = _[ie] || {}, se = [];
Object.keys(re).forEach((function(_) {
if (isNonLogicalMatcher(_)) se.push(ie);
var ee = getSingleFieldQueryOptsFor(_, re[_]);
if (ne) ne = mergeObjects([ ne, ee ]); else ne = ee;
}));
return {
queryOpts: ne,
inMemoryFields: se
};
}
function getMultiFieldCoreQueryPlan(_, ee) {
switch (_) {
case "$eq":
return {
startkey: ee,
endkey: ee
};
case "$lte":
return {
endkey: ee
};
case "$gte":
return {
startkey: ee
};
case "$lt":
return {
endkey: ee,
inclusive_end: false
};
case "$gt":
return {
startkey: ee,
inclusive_start: false
};
}
}
function getMultiFieldQueryOpts(_, ee) {
var ne, ie, re = ee.def.fields.map(getKey), se = [], oe = [], le = [];
function finish(_) {
if (false !== ne) oe.push(COLLATE_LO);
if (false !== ie) le.push(COLLATE_HI);
se = re.slice(_);
}
for (var ue = 0, de = re.length; ue < de; ue++) {
var fe = _[re[ue]];
if (!fe || !Object.keys(fe).length) {
finish(ue);
break;
} else if (Object.keys(fe).some(isNonLogicalMatcher)) {
finish(ue);
break;
} else if (ue > 0) {
var he = "$gt" in fe || "$gte" in fe || "$lt" in fe || "$lte" in fe, pe = Object.keys(_[re[ue - 1]]), ge = arrayEquals(pe, [ "$eq" ]), me = arrayEquals(pe, Object.keys(fe));
if (he && !ge && !me) {
finish(ue);
break;
}
}
for (var ye = Object.keys(fe), ve = null, Se = 0; Se < ye.length; Se++) {
var Ee = ye[Se], Ce = getMultiFieldCoreQueryPlan(Ee, fe[Ee]);
if (ve) ve = mergeObjects([ ve, Ce ]); else ve = Ce;
}
oe.push("startkey" in ve ? ve.startkey : COLLATE_LO);
le.push("endkey" in ve ? ve.endkey : COLLATE_HI);
if ("inclusive_start" in ve) ne = ve.inclusive_start;
if ("inclusive_end" in ve) ie = ve.inclusive_end;
}
var we = {
startkey: oe,
endkey: le
};
if ("undefined" != typeof ne) we.inclusive_start = ne;
if ("undefined" != typeof ie) we.inclusive_end = ie;
return {
queryOpts: we,
inMemoryFields: se
};
}
function shouldShortCircuit(_) {
return Object.keys(_).map((function(ee) {
return _[ee];
})).some((function(_) {
return "object" == typeof _ && 0 === Object.keys(_).length;
}));
}
function getDefaultQueryPlan(_) {
return {
queryOpts: {
startkey: null
},
inMemoryFields: [ Object.keys(_) ]
};
}
function getCoreQueryPlan(_, ee) {
if (ee.defaultUsed) return getDefaultQueryPlan(_, ee);
if (1 === ee.def.fields.length) return getSingleFieldCoreQueryPlan(_, ee); else return getMultiFieldQueryOpts(_, ee);
}
function planQuery(_, ee) {
var ne = _.selector, ie = _.sort;
if (shouldShortCircuit(ne)) return assign$2({}, SHORT_CIRCUIT_QUERY, {
index: ee[0]
});
var re = getUserFields(ne, ie), se = re.fields, oe = findBestMatchingIndex(ne, se, re.sortOrder, ee, _.use_index), le = getCoreQueryPlan(ne, oe);
return {
queryOpts: le.queryOpts,
index: oe,
inMemoryFields: getInMemoryFields(le.inMemoryFields, oe, ne, se)
};
}
function indexToSignature(_) {
return _.ddoc.substring(8) + "/" + _.name;
}
function doAllDocs(_, ee) {
var ne = clone(ee);
if (ne.descending) {
if ("endkey" in ne && "string" != typeof ne.endkey) ne.endkey = "";
if ("startkey" in ne && "string" != typeof ne.startkey) ne.limit = 0;
} else {
if ("startkey" in ne && "string" != typeof ne.startkey) ne.startkey = "";
if ("endkey" in ne && "string" != typeof ne.endkey) ne.limit = 0;
}
if ("key" in ne && "string" != typeof ne.key) ne.limit = 0;
if (ne.limit > 0 && ne.indexes_count) {
ne.original_limit = ne.limit;
ne.limit += ne.indexes_count;
}
return _.allDocs(ne).then((function(_) {
_.rows = _.rows.filter((function(_) {
return !/^_design\//.test(_.id);
}));
if (ne.original_limit) ne.limit = ne.original_limit;
_.rows = _.rows.slice(0, ne.limit);
return _;
}));
}
function find$1(_, ee, ne) {
if (ee.selector) {
validateSelector(ee.selector, false);
ee.selector = massageSelector(ee.selector);
}
if (ee.sort) ee.sort = massageSort(ee.sort);
if (ee.use_index) ee.use_index = massageUseIndex(ee.use_index);
validateFindRequest(ee);
return getIndexes$1(_).then((function(ie) {
_.constructor.emit("debug", [ "find", "planning query", ee ]);
var re = planQuery(ee, ie.indexes);
_.constructor.emit("debug", [ "find", "query plan", re ]);
var se = re.index;
validateSort(ee, se);
var oe = assign$2({
include_docs: true,
reduce: false,
indexes_count: ie.total_rows
}, re.queryOpts);
if ("startkey" in oe && "endkey" in oe && collate(oe.startkey, oe.endkey) > 0) return {
docs: []
};
if (ee.sort && "string" != typeof ee.sort[0] && "desc" === getValue(ee.sort[0])) {
oe.descending = true;
oe = reverseOptions(oe);
}
if (!re.inMemoryFields.length) {
if ("limit" in ee) oe.limit = ee.limit;
if ("skip" in ee) oe.skip = ee.skip;
}
if (ne) return Promise.resolve(re, oe); else return Promise.resolve().then((function() {
if ("_all_docs" === se.name) return doAllDocs(_, oe); else {
var ee = indexToSignature(se);
return abstractMapper$1(_).query.call(_, ee, oe);
}
})).then((function(_) {
if (false === oe.inclusive_start) _.rows = filterInclusiveStart(_.rows, oe.startkey, se);
if (re.inMemoryFields.length) _.rows = filterInMemoryFields(_.rows, ee, re.inMemoryFields);
var ne = {
docs: _.rows.map((function(_) {
var ne = _.doc;
if (ee.fields) return pick2(ne, ee.fields); else return ne;
}))
};
if (se.defaultUsed) ne.warning = "No matching index found, create an index to optimize query time.";
return ne;
}));
}));
}
function explain$1(_, ee) {
return find$1(_, ee, true).then((function(ne) {
return {
dbname: _.name,
index: ne.index,
selector: ee.selector,
range: {
start_key: ne.queryOpts.startkey,
end_key: ne.queryOpts.endkey
},
opts: {
use_index: ee.use_index || [],
bookmark: "nil",
limit: ee.limit,
skip: ee.skip,
sort: ee.sort || {},
fields: ee.fields,
conflicts: false,
r: [ 49 ]
},
limit: ee.limit,
skip: ee.skip || 0,
fields: ee.fields
};
}));
}
function deleteIndex$1(_, ee) {
if (!ee.ddoc) throw new Error("you must supply an index.ddoc when deleting");
if (!ee.name) throw new Error("you must supply an index.name when deleting");
var ne = ee.ddoc, ie = ee.name;
return upsert(_, ne, (function deltaFun(_) {
if (1 === Object.keys(_.views).length && _.views[ie]) return {
_id: ne,
_deleted: true
};
delete _.views[ie];
return _;
})).then((function() {
return abstractMapper$1(_).viewCleanup.apply(_);
})).then((function() {
return {
ok: true
};
}));
}
var createIndexAsCallback = callbackify2(createIndex$1), findAsCallback = callbackify2(find$1), explainAsCallback = callbackify2(explain$1), getIndexesAsCallback = callbackify2(getIndexes$1), deleteIndexAsCallback = callbackify2(deleteIndex$1), plugin = {};
plugin.createIndex = toPromise((function(_, ee) {
if ("object" != typeof _) return ee(new Error("you must provide an index to create"));
(isRemote(this) ? createIndex : createIndexAsCallback)(this, _, ee);
}));
plugin.find = toPromise((function(_, ee) {
if ("undefined" == typeof ee) {
ee = _;
_ = void 0;
}
if ("object" != typeof _) return ee(new Error("you must provide search parameters to find()"));
(isRemote(this) ? find : findAsCallback)(this, _, ee);
}));
plugin.explain = toPromise((function(_, ee) {
if ("undefined" == typeof ee) {
ee = _;
_ = void 0;
}
if ("object" != typeof _) return ee(new Error("you must provide search parameters to explain()"));
(isRemote(this) ? explain : explainAsCallback)(this, _, ee);
}));
plugin.getIndexes = toPromise((function(_) {
(isRemote(this) ? getIndexes : getIndexesAsCallback)(this, _);
}));
plugin.deleteIndex = toPromise((function(_, ee) {
if ("object" != typeof _) return ee(new Error("you must provide an index to delete"));
(isRemote(this) ? deleteIndex : deleteIndexAsCallback)(this, _, ee);
}));
var index_browser_es_default3 = plugin, import_transform_pouch = __toESM(require_transform_pouch(), 1);
function unwrapTaskResult(_) {
if ("ok" in _) return _.ok;
if ("err" in _) return _.err;
throw new Error("Argument Exception: Could not unwrap");
}
function isTaskWaiting(_) {
if (_ instanceof Promise) return false;
if (_ instanceof Function) return true;
throw new Error("Invalid state");
}
async function wrapEachProcess(_, ee) {
try {
return {
key: _,
ok: await ee
};
} catch (ee) {
return {
key: _,
err: ee instanceof Error ? ee : new Error(`${ee}`)
};
}
}
async function* processAllTasksWithConcurrencyLimit(_, ee) {
const ne = new Map;
let ie = 0;
const re = ee.reverse();
for (;re.length > 0 || ne.size > 0; ) {
e: for (;ne.size < _ && re.length > 0; ) {
const _ = re.pop();
if (void 0 === _) break e;
ie++;
const ee = wrapEachProcess(ie, isTaskWaiting(_) ? _() : _);
ne.set(ie, ee);
}
const ee = await Promise.race(ne.values());
ne.delete(ee.key);
yield ee;
}
}
async function mapAllTasksWithConcurrencyLimit(_, ee) {
const ne = new Map;
for await (const ie of processAllTasksWithConcurrencyLimit(_, ee)) ne.set(ie.key, ie);
return [ ...ne.entries() ].sort(((_, ee) => _[0] - ee[0])).map((_ => _[1]));
}
var tasks = {};
function scheduleTask(_, ee, ne, ie) {
if (!ie || !(_ in tasks)) {
cancelTask(_);
tasks[_] = setTimeout((async () => {
delete tasks[_];
await ne();
}), ee);
}
}
function cancelTask(_) {
if (_ in tasks) {
clearTimeout(tasks[_]);
delete tasks[_];
}
}
function cancelAllTasks() {
for (const _ in tasks) {
clearTimeout(tasks[_]);
delete tasks[_];
}
}
var intervals = {};
function cancelAllPeriodicTask() {
for (const _ in intervals) {
clearInterval(intervals[_]);
delete intervals[_];
}
}
var waitingItems = new Map;
function waitForTimeout(_, ee) {
if (waitingItems.has(_)) return waitingItems.get(_).timeoutPromise.promise;
const ne = promiseWithResolver(), ie = setTimeout((() => {
finishWaitingForTimeout(_, true);
}), ee);
waitingItems.set(_, {
waitFrom: Date.now(),
timeout: ee,
timeoutPromise: ne,
timer: ie
});
return ne.promise;
}
function finishWaitingForTimeout(_, ee = false) {
const ne = waitingItems.get(_);
if (ne) {
if (ne.timer) clearTimeout(ne.timer);
ne.timeoutPromise.resolve(ee);
waitingItems.delete(_);
return true;
}
return false;
}
function finishAllWaitingForTimeout(_, ee) {
for (const [ne, ie] of waitingItems) if (ne.startsWith(_)) finishWaitingForTimeout(ne, ee);
}
function isWaitingForTimeout(_) {
return waitingItems.has(_);
}
index_es_default.plugin(index_es_default2).plugin(index_es_default3).plugin(index_es_default4).plugin(index_browser_es_default2).plugin(index_es_default8).plugin(index_browser_es_default3).plugin(import_transform_pouch.default);
function appendPurgeSeqs(_, ee) {
return _.get("_local/purges").then((function(ne) {
for (const [ie, re] of ee) {
const ee = ne.purgeSeq + 1;
ne.purges.push({
docId: ie,
rev: re,
purgeSeq: ee
});
if (ne.purges.length > _.purged_infos_limit) ne.purges.splice(0, ne.purges.length - _.purged_infos_limit);
ne.purgeSeq = ee;
}
return ne;
})).catch((function(_) {
if (404 !== _.status) throw _;
return {
_id: "_local/purges",
purges: ee.map((([_, ee], ne) => ({
docId: _,
rev: ee,
purgeSeq: ne
}))),
purgeSeq: ee.length
};
})).then((function(ee) {
return _.put(ee);
}));
}
index_es_default.prototype.purgeMulti = adapterFun("_purgeMulti", (function(_, ee) {
if ("undefined" == typeof this._purge) return ee(createError(UNKNOWN_ERROR, "Purge is not implemented in the " + this.adapter + " adapter."));
const ne = this, ie = _.map((_ => () => new Promise(((ee, ie) => {
const [re, se] = _;
ne._getRevisionTree(re, ((ie, oe) => {
if (ie) return ee([ _, ie ]);
if (!oe) return ee([ _, createError(MISSING_DOC) ]);
let le;
try {
le = findPathToLeaf(oe, se);
} catch (ne) {
return ee([ _, ne.message || ne ]);
}
ne._purge(re, le, ((ne, ie) => {
if (ne) return ee([ _, ne ]); else return ee([ _, ie ]);
}));
}));
}))));
(async () => {
const _ = (await mapAllTasksWithConcurrencyLimit(1, ie)).map((_ => unwrapTaskResult(_)));
await appendPurgeSeqs(ne, _.filter((_ => "ok" in _[1])).map((_ => _[0])));
return Object.fromEntries(_.map((_ => [ _[0][0], _[1] ])));
})().then((_ => ee(void 0, _))).catch((_ => ee(_)));
}));
var import_diff_match_patch2 = __toESM(require_diff_match_patch(), 1), ConflictResolveModal = class extends import_obsidian.Modal {
constructor(_, ee, ne) {
super(_);
this.response = CANCELLED;
this.isClosed = false;
this.consumed = false;
this.result = ne;
this.filename = ee;
sendValue("cancel-resolve-conflict:" + this.filename, true);
}
onOpen() {
const {contentEl: _} = this;
sendValue("cancel-resolve-conflict:" + this.filename, true);
setTimeout((async () => {
if (await waitForValue("cancel-resolve-conflict:" + this.filename)) this.sendResponse(CANCELLED);
}), 10);
this.titleEl.setText("Conflicting changes");
_.empty();
_.createEl("span", {
text: this.filename
});
const ee = _.createDiv("");
ee.addClass("op-scrollable");
let ne = "";
for (const _ of this.result.diff) {
const ee = _[0], ie = _[1];
if (ee == import_diff_match_patch2.DIFF_DELETE) ne += "" + escapeStringToHTML(ie).replace(/\n/g, "\n") + ""; else if (ee == import_diff_match_patch2.DIFF_EQUAL) ne += "" + escapeStringToHTML(ie).replace(/\n/g, "\n") + ""; else if (ee == import_diff_match_patch2.DIFF_INSERT) ne += "" + escapeStringToHTML(ie).replace(/\n/g, "\n") + "";
}
ne = ne.replace(/\n/g, "
");
ee.innerHTML = ne;
const ie = _.createDiv(""), re = new Date(this.result.left.mtime).toLocaleString() + (this.result.left.deleted ? " (Deleted)" : ""), se = new Date(this.result.right.mtime).toLocaleString() + (this.result.right.deleted ? " (Deleted)" : "");
ie.innerHTML = `\nA:${re}
B:${se}
\n `;
_.createEl("button", {
text: "Keep A"
}, (_ => _.addEventListener("click", (() => this.sendResponse(this.result.right.rev)))));
_.createEl("button", {
text: "Keep B"
}, (_ => _.addEventListener("click", (() => this.sendResponse(this.result.left.rev)))));
_.createEl("button", {
text: "Concat both"
}, (_ => _.addEventListener("click", (() => this.sendResponse(LEAVE_TO_SUBSEQUENT)))));
_.createEl("button", {
text: "Not now"
}, (_ => _.addEventListener("click", (() => this.sendResponse(CANCELLED)))));
}
sendResponse(_) {
this.response = _;
this.close();
}
onClose() {
const {contentEl: _} = this;
_.empty();
if (!this.consumed) {
this.consumed = true;
sendValue("close-resolve-conflict:" + this.filename, this.response);
sendValue("cancel-resolve-conflict:" + this.filename, false);
}
}
async waitForResult() {
await delay(100);
const _ = await waitForValue("close-resolve-conflict:" + this.filename);
if (_ === RESULT_TIMED_OUT) return CANCELLED; else return _;
}
}, import_obsidian4 = require("obsidian");
function noop2() {}
function assign(_, ee) {
for (const ne in ee) _[ne] = ee[ne];
return _;
}
function run(_) {
return _();
}
function blank_object() {
return Object.create(null);
}
function run_all(_) {
_.forEach(run);
}
function is_function(_) {
return "function" == typeof _;
}
function safe_not_equal(_, ee) {
return _ != _ ? ee == ee : _ !== ee || _ && "object" == typeof _ || "function" == typeof _;
}
function is_empty(_) {
return 0 === Object.keys(_).length;
}
function null_to_empty(_) {
return null == _ ? "" : _;
}
var globals = "undefined" != typeof window ? window : "undefined" != typeof globalThis ? globalThis : window, ResizeObserverSingleton = class _ResizeObserverSingleton {
constructor(_) {
__publicField(this, "_listeners", "WeakMap" in globals ? new WeakMap : void 0);
__publicField(this, "_observer");
__publicField(this, "options");
this.options = _;
}
observe(_, ee) {
this._listeners.set(_, ee);
this._getObserver().observe(_, this.options);
return () => {
this._listeners.delete(_);
this._observer.unobserve(_);
};
}
_getObserver() {
var _;
return null != (_ = this._observer) ? _ : this._observer = new ResizeObserver((_ => {
var ee;
for (const ne of _) {
_ResizeObserverSingleton.entries.set(ne.target, ne);
null == (ee = this._listeners.get(ne.target)) || ee(ne);
}
}));
}
};
ResizeObserverSingleton.entries = "WeakMap" in globals ? new WeakMap : void 0;
var current_component, is_hydrating = false;
function start_hydrating() {
is_hydrating = true;
}
function end_hydrating() {
is_hydrating = false;
}
function append(_, ee) {
_.appendChild(ee);
}
function append_styles(_, ee, ne) {
const ie = get_root_for_style(_);
if (!ie.getElementById(ee)) {
const _ = element("style");
_.id = ee;
_.textContent = ne;
append_stylesheet(ie, _);
}
}
function get_root_for_style(_) {
if (!_) return document;
const ee = _.getRootNode ? _.getRootNode() : _.ownerDocument;
if (ee && ee.host) return ee; else return _.ownerDocument;
}
function append_stylesheet(_, ee) {
append(_.head || _, ee);
return ee.sheet;
}
function insert(_, ee, ne) {
_.insertBefore(ee, ne || null);
}
function detach(_) {
if (_.parentNode) _.parentNode.removeChild(_);
}
function destroy_each(_, ee) {
for (let ne = 0; ne < _.length; ne += 1) if (_[ne]) _[ne].d(ee);
}
function element(_) {
return document.createElement(_);
}
function text(_) {
return document.createTextNode(_);
}
function space() {
return text(" ");
}
function empty() {
return text("");
}
function listen(_, ee, ne, ie) {
_.addEventListener(ee, ne, ie);
return () => _.removeEventListener(ee, ne, ie);
}
function attr(_, ee, ne) {
if (null == ne) _.removeAttribute(ee); else if (_.getAttribute(ee) !== ne) _.setAttribute(ee, ne);
}
function init_binding_group(_) {
let ee;
return {
p(...ne) {
ee = ne;
ee.forEach((ee => _.push(ee)));
},
r() {
ee.forEach((ee => _.splice(_.indexOf(ee), 1)));
}
};
}
function children(_) {
return Array.from(_.childNodes);
}
function set_data(_, ee) {
ee = "" + ee;
if (_.data !== ee) _.data = ee;
}
function set_input_value(_, ee) {
_.value = null == ee ? "" : ee;
}
function select_option(_, ee, ne) {
for (let ne = 0; ne < _.options.length; ne += 1) {
const ie = _.options[ne];
if (ie.__value === ee) {
ie.selected = true;
return;
}
}
if (!ne || void 0 !== ee) _.selectedIndex = -1;
}
function select_value(_) {
const ee = _.querySelector(":checked");
return ee && ee.__value;
}
function toggle_class(_, ee, ne) {
_.classList.toggle(ee, !!ne);
}
function get_custom_elements_slots(_) {
const ee = {};
_.childNodes.forEach((_ => {
ee[_.slot || "default"] = true;
}));
return ee;
}
function set_current_component(_) {
current_component = _;
}
function get_current_component() {
if (!current_component) throw new Error("Function called outside component initialization");
return current_component;
}
function onMount(_) {
get_current_component().$$.on_mount.push(_);
}
function onDestroy(_) {
get_current_component().$$.on_destroy.push(_);
}
var dirty_components = [], binding_callbacks = [], render_callbacks = [], flush_callbacks = [], resolved_promise = Promise.resolve(), update_scheduled = false;
function schedule_update() {
if (!update_scheduled) {
update_scheduled = true;
resolved_promise.then(flush);
}
}
function add_render_callback(_) {
render_callbacks.push(_);
}
var seen_callbacks = new Set, flushidx = 0;
function flush() {
if (0 !== flushidx) return;
const _ = current_component;
do {
try {
for (;flushidx < dirty_components.length; ) {
const _ = dirty_components[flushidx];
flushidx++;
set_current_component(_);
update(_.$$);
}
} catch (_) {
dirty_components.length = 0;
flushidx = 0;
throw _;
}
set_current_component(null);
dirty_components.length = 0;
flushidx = 0;
for (;binding_callbacks.length; ) binding_callbacks.pop()();
for (let _ = 0; _ < render_callbacks.length; _ += 1) {
const ee = render_callbacks[_];
if (!seen_callbacks.has(ee)) {
seen_callbacks.add(ee);
ee();
}
}
render_callbacks.length = 0;
} while (dirty_components.length);
for (;flush_callbacks.length; ) flush_callbacks.pop()();
update_scheduled = false;
seen_callbacks.clear();
set_current_component(_);
}
function update(_) {
if (null !== _.fragment) {
_.update();
run_all(_.before_update);
const ee = _.dirty;
_.dirty = [ -1 ];
_.fragment && _.fragment.p(_.ctx, ee);
_.after_update.forEach(add_render_callback);
}
}
function flush_render_callbacks(_) {
const ee = [], ne = [];
render_callbacks.forEach((ie => -1 === _.indexOf(ie) ? ee.push(ie) : ne.push(ie)));
ne.forEach((_ => _()));
render_callbacks = ee;
}
var outros, outroing = new Set;
function group_outros() {
outros = {
r: 0,
c: [],
p: outros
};
}
function check_outros() {
if (!outros.r) run_all(outros.c);
outros = outros.p;
}
function transition_in(_, ee) {
if (_ && _.i) {
outroing.delete(_);
_.i(ee);
}
}
function transition_out(_, ee, ne, ie) {
if (_ && _.o) {
if (outroing.has(_)) return;
outroing.add(_);
outros.c.push((() => {
outroing.delete(_);
if (ie) {
if (ne) _.d(1);
ie();
}
}));
_.o(ee);
} else if (ie) ie();
}
function ensure_array_like(_) {
return void 0 !== (null == _ ? void 0 : _.length) ? _ : Array.from(_);
}
function get_spread_update(_, ee) {
const ne = {}, ie = {}, re = {
$$scope: 1
};
let se = _.length;
for (;se--; ) {
const oe = _[se], le = ee[se];
if (le) {
for (const _ in oe) if (!(_ in le)) ie[_] = 1;
for (const _ in le) if (!re[_]) {
ne[_] = le[_];
re[_] = 1;
}
_[se] = le;
} else for (const _ in oe) re[_] = 1;
}
for (const _ in ie) if (!(_ in ne)) ne[_] = void 0;
return ne;
}
function get_spread_object(_) {
return "object" == typeof _ && null !== _ ? _ : {};
}
var SvelteElement, _boolean_attributes = [ "allowfullscreen", "allowpaymentrequest", "async", "autofocus", "autoplay", "checked", "controls", "default", "defer", "disabled", "formnovalidate", "hidden", "inert", "ismap", "loop", "multiple", "muted", "nomodule", "novalidate", "open", "playsinline", "readonly", "required", "reversed", "selected" ], boolean_attributes = new Set([ ..._boolean_attributes ]);
function create_component(_) {
_ && _.c();
}
function mount_component(_, ee, ne) {
const {fragment: ie, after_update: re} = _.$$;
ie && ie.m(ee, ne);
add_render_callback((() => {
const ee = _.$$.on_mount.map(run).filter(is_function);
if (_.$$.on_destroy) _.$$.on_destroy.push(...ee); else run_all(ee);
_.$$.on_mount = [];
}));
re.forEach(add_render_callback);
}
function destroy_component(_, ee) {
const ne = _.$$;
if (null !== ne.fragment) {
flush_render_callbacks(ne.after_update);
run_all(ne.on_destroy);
ne.fragment && ne.fragment.d(ee);
ne.on_destroy = ne.fragment = null;
ne.ctx = [];
}
}
function make_dirty(_, ee) {
if (-1 === _.$$.dirty[0]) {
dirty_components.push(_);
schedule_update();
_.$$.dirty.fill(0);
}
_.$$.dirty[ee / 31 | 0] |= 1 << ee % 31;
}
function init2(_, ee, ne, ie, re, se, oe = null, le = [ -1 ]) {
const ue = current_component;
set_current_component(_);
const de = _.$$ = {
fragment: null,
ctx: [],
props: se,
update: noop2,
not_equal: re,
bound: blank_object(),
on_mount: [],
on_destroy: [],
on_disconnect: [],
before_update: [],
after_update: [],
context: new Map(ee.context || (ue ? ue.$$.context : [])),
callbacks: blank_object(),
dirty: le,
skip_bound: false,
root: ee.target || ue.$$.root
};
oe && oe(de.root);
let fe = false;
de.ctx = ne ? ne(_, ee.props || {}, ((ee, ne, ...ie) => {
const se = ie.length ? ie[0] : ne;
if (de.ctx && re(de.ctx[ee], de.ctx[ee] = se)) {
if (!de.skip_bound && de.bound[ee]) de.bound[ee](se);
if (fe) make_dirty(_, ee);
}
return ne;
})) : [];
de.update();
fe = true;
run_all(de.before_update);
de.fragment = ie ? ie(de.ctx) : false;
if (ee.target) {
if (ee.hydrate) {
start_hydrating();
const _ = children(ee.target);
de.fragment && de.fragment.l(_);
_.forEach(detach);
} else de.fragment && de.fragment.c();
if (ee.intro) transition_in(_.$$.fragment);
mount_component(_, ee.target, ee.anchor);
end_hydrating();
flush();
}
set_current_component(ue);
}
if ("function" == typeof HTMLElement) SvelteElement = class extends HTMLElement {
constructor(_, ee, ne) {
super();
__publicField(this, "$$ctor");
__publicField(this, "$$s");
__publicField(this, "$$c");
__publicField(this, "$$cn", false);
__publicField(this, "$$d", {});
__publicField(this, "$$r", false);
__publicField(this, "$$p_d", {});
__publicField(this, "$$l", {});
__publicField(this, "$$l_u", new Map);
this.$$ctor = _;
this.$$s = ee;
if (ne) this.attachShadow({
mode: "open"
});
}
addEventListener(_, ee, ne) {
this.$$l[_] = this.$$l[_] || [];
this.$$l[_].push(ee);
if (this.$$c) {
const ne = this.$$c.$on(_, ee);
this.$$l_u.set(ee, ne);
}
super.addEventListener(_, ee, ne);
}
removeEventListener(_, ee, ne) {
super.removeEventListener(_, ee, ne);
if (this.$$c) {
const _ = this.$$l_u.get(ee);
if (_) {
_();
this.$$l_u.delete(ee);
}
}
}
async connectedCallback() {
this.$$cn = true;
if (!this.$$c) {
let create_slot = function(_) {
return () => {
let ee;
return {
c: function create() {
ee = element("slot");
if ("default" !== _) attr(ee, "name", _);
},
m: function mount(_, ne) {
insert(_, ee, ne);
},
d: function destroy2(_) {
if (_) detach(ee);
}
};
};
};
await Promise.resolve();
if (!this.$$cn || this.$$c) return;
const _ = {}, ee = get_custom_elements_slots(this);
for (const ne of this.$$s) if (ne in ee) _[ne] = [ create_slot(ne) ];
for (const _ of this.attributes) {
const ee = this.$$g_p(_.name);
if (!(ee in this.$$d)) this.$$d[ee] = get_custom_element_value(ee, _.value, this.$$p_d, "toProp");
}
for (const _ in this.$$p_d) if (!(_ in this.$$d) && void 0 !== this[_]) {
this.$$d[_] = this[_];
delete this[_];
}
this.$$c = new this.$$ctor({
target: this.shadowRoot || this,
props: {
...this.$$d,
$$slots: _,
$$scope: {
ctx: []
}
}
});
const reflect_attributes = () => {
this.$$r = true;
for (const _ in this.$$p_d) {
this.$$d[_] = this.$$c.$$.ctx[this.$$c.$$.props[_]];
if (this.$$p_d[_].reflect) {
const ee = get_custom_element_value(_, this.$$d[_], this.$$p_d, "toAttribute");
if (null == ee) this.removeAttribute(this.$$p_d[_].attribute || _); else this.setAttribute(this.$$p_d[_].attribute || _, ee);
}
}
this.$$r = false;
};
this.$$c.$$.after_update.push(reflect_attributes);
reflect_attributes();
for (const _ in this.$$l) for (const ee of this.$$l[_]) {
const ne = this.$$c.$on(_, ee);
this.$$l_u.set(ee, ne);
}
this.$$l = {};
}
}
attributeChangedCallback(_, ee, ne) {
var ie;
if (!this.$$r) {
_ = this.$$g_p(_);
this.$$d[_] = get_custom_element_value(_, ne, this.$$p_d, "toProp");
null == (ie = this.$$c) || ie.$set({
[_]: this.$$d[_]
});
}
}
disconnectedCallback() {
this.$$cn = false;
Promise.resolve().then((() => {
if (!this.$$cn && this.$$c) {
this.$$c.$destroy();
this.$$c = void 0;
}
}));
}
$$g_p(_) {
return Object.keys(this.$$p_d).find((ee => this.$$p_d[ee].attribute === _ || !this.$$p_d[ee].attribute && ee.toLowerCase() === _)) || _;
}
};
function get_custom_element_value(_, ee, ne, ie) {
var re;
const se = null == (re = ne[_]) ? void 0 : re.type;
ee = "Boolean" === se && "boolean" != typeof ee ? null != ee : ee;
if (!ie || !ne[_]) return ee; else if ("toAttribute" === ie) switch (se) {
case "Object":
case "Array":
return null == ee ? null : JSON.stringify(ee);
case "Boolean":
return ee ? "" : null;
case "Number":
return null == ee ? null : ee;
default:
return ee;
} else switch (se) {
case "Object":
case "Array":
return ee && JSON.parse(ee);
case "Boolean":
return ee;
case "Number":
return null != ee ? +ee : ee;
default:
return ee;
}
}
var SvelteComponent = class {
constructor() {
__publicField(this, "$$");
__publicField(this, "$$set");
}
$destroy() {
destroy_component(this, 1);
this.$destroy = noop2;
}
$on(_, ee) {
if (!is_function(ee)) return noop2;
const ne = this.$$.callbacks[_] || (this.$$.callbacks[_] = []);
ne.push(ee);
return () => {
const _ = ne.indexOf(ee);
if (-1 !== _) ne.splice(_, 1);
};
}
$set(_) {
if (this.$$set && !is_empty(_)) {
this.$$.skip_bound = true;
this.$$set(_);
this.$$.skip_bound = false;
}
}
}, PUBLIC_VERSION = "4";
if ("undefined" != typeof window) (window.__svelte || (window.__svelte = {
v: new Set
})).v.add(PUBLIC_VERSION);
var subscriber_queue = [];
function writable(_, ee = noop2) {
let ne;
const ie = new Set;
function set(ee) {
if (safe_not_equal(_, ee)) {
_ = ee;
if (ne) {
const ee = !subscriber_queue.length;
for (const ee of ie) {
ee[1]();
subscriber_queue.push(ee, _);
}
if (ee) {
for (let _ = 0; _ < subscriber_queue.length; _ += 2) subscriber_queue[_][0](subscriber_queue[_ + 1]);
subscriber_queue.length = 0;
}
}
}
}
function update2(ee) {
set(ee(_));
}
return {
set,
update: update2,
subscribe: function subscribe2(re, se = noop2) {
const oe = [ re, se ];
ie.add(oe);
if (1 === ie.size) ne = ee(set, update2) || noop2;
re(_);
return () => {
ie.delete(oe);
if (0 === ie.size && ne) {
ne();
ne = null;
}
};
}
};
}
var e, t = new Uint8Array([ 0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 2, 127, 127, 0, 96, 3, 127, 127, 127, 1, 127, 3, 3, 2, 1, 0, 5, 3, 1, 0, 1, 7, 23, 3, 3, 109, 101, 109, 2, 0, 5, 120, 120, 104, 51, 50, 0, 0, 5, 120, 120, 104, 54, 52, 0, 1, 10, 152, 9, 2, 242, 2, 1, 4, 127, 32, 0, 32, 1, 106, 33, 3, 32, 1, 32, 1, 65, 16, 79, 4, 127, 32, 3, 65, 16, 107, 33, 6, 32, 2, 65, 168, 136, 141, 161, 2, 106, 33, 1, 32, 2, 65, 137, 235, 208, 208, 7, 107, 33, 4, 32, 2, 65, 207, 140, 162, 142, 6, 106, 33, 5, 3, 64, 32, 1, 32, 0, 40, 2, 0, 65, 247, 148, 175, 175, 120, 108, 106, 65, 13, 119, 65, 177, 243, 221, 241, 121, 108, 33, 1, 32, 4, 32, 0, 65, 4, 106, 34, 0, 40, 2, 0, 65, 247, 148, 175, 175, 120, 108, 106, 65, 13, 119, 65, 177, 243, 221, 241, 121, 108, 33, 4, 32, 2, 32, 0, 65, 4, 106, 34, 0, 40, 2, 0, 65, 247, 148, 175, 175, 120, 108, 106, 65, 13, 119, 65, 177, 243, 221, 241, 121, 108, 33, 2, 32, 5, 32, 0, 65, 4, 106, 34, 0, 40, 2, 0, 65, 247, 148, 175, 175, 120, 108, 106, 65, 13, 119, 65, 177, 243, 221, 241, 121, 108, 33, 5, 32, 6, 32, 0, 65, 4, 106, 34, 0, 79, 13, 0, 11, 32, 2, 65, 12, 119, 32, 5, 65, 18, 119, 106, 32, 4, 65, 7, 119, 106, 32, 1, 65, 1, 119, 106, 5, 32, 2, 65, 177, 207, 217, 178, 1, 106, 11, 106, 33, 2, 3, 64, 32, 3, 32, 0, 65, 4, 106, 79, 4, 64, 32, 2, 32, 0, 40, 2, 0, 65, 189, 220, 202, 149, 124, 108, 106, 65, 17, 119, 65, 175, 214, 211, 190, 2, 108, 33, 2, 32, 0, 65, 4, 106, 33, 0, 12, 1, 11, 11, 3, 64, 32, 0, 32, 3, 73, 4, 64, 32, 2, 32, 0, 45, 0, 0, 65, 177, 207, 217, 178, 1, 108, 106, 65, 11, 119, 65, 177, 243, 221, 241, 121, 108, 33, 2, 32, 0, 65, 1, 106, 33, 0, 12, 1, 11, 11, 32, 2, 32, 2, 65, 15, 118, 115, 65, 247, 148, 175, 175, 120, 108, 34, 0, 65, 13, 118, 32, 0, 115, 65, 189, 220, 202, 149, 124, 108, 34, 0, 65, 16, 118, 32, 0, 115, 11, 161, 6, 2, 4, 126, 3, 127, 32, 0, 65, 4, 106, 53, 2, 0, 32, 0, 53, 2, 0, 66, 32, 134, 132, 33, 2, 32, 1, 32, 0, 65, 8, 106, 34, 6, 106, 33, 7, 32, 1, 65, 32, 79, 4, 126, 32, 7, 65, 32, 107, 33, 8, 32, 2, 66, 214, 235, 130, 238, 234, 253, 137, 245, 224, 0, 124, 33, 3, 32, 2, 66, 177, 169, 172, 193, 173, 184, 212, 166, 61, 125, 33, 4, 32, 2, 66, 249, 234, 208, 208, 231, 201, 161, 228, 225, 0, 124, 33, 5, 3, 64, 32, 3, 32, 6, 41, 3, 0, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 33, 3, 32, 4, 32, 6, 65, 8, 106, 34, 6, 41, 3, 0, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 33, 4, 32, 2, 32, 6, 65, 8, 106, 34, 6, 41, 3, 0, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 33, 2, 32, 5, 32, 6, 65, 8, 106, 34, 6, 41, 3, 0, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 33, 5, 32, 8, 32, 6, 65, 8, 106, 34, 6, 79, 13, 0, 11, 32, 2, 66, 12, 137, 32, 5, 66, 18, 137, 124, 32, 4, 66, 7, 137, 124, 32, 3, 66, 1, 137, 124, 32, 3, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 133, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 66, 157, 163, 181, 234, 131, 177, 141, 138, 250, 0, 125, 32, 4, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 133, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 66, 157, 163, 181, 234, 131, 177, 141, 138, 250, 0, 125, 32, 2, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 133, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 66, 157, 163, 181, 234, 131, 177, 141, 138, 250, 0, 125, 32, 5, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 133, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 66, 157, 163, 181, 234, 131, 177, 141, 138, 250, 0, 125, 5, 32, 2, 66, 197, 207, 217, 178, 241, 229, 186, 234, 39, 124, 11, 32, 1, 173, 124, 33, 2, 3, 64, 32, 7, 32, 6, 65, 8, 106, 79, 4, 64, 32, 2, 32, 6, 41, 3, 0, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 133, 66, 27, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 66, 157, 163, 181, 234, 131, 177, 141, 138, 250, 0, 125, 33, 2, 32, 6, 65, 8, 106, 33, 6, 12, 1, 11, 11, 32, 6, 65, 4, 106, 32, 7, 77, 4, 64, 32, 2, 32, 6, 53, 2, 0, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 133, 66, 23, 137, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 66, 249, 243, 221, 241, 153, 246, 153, 171, 22, 124, 33, 2, 32, 6, 65, 4, 106, 33, 6, 11, 3, 64, 32, 6, 32, 7, 73, 4, 64, 32, 2, 32, 6, 49, 0, 0, 66, 197, 207, 217, 178, 241, 229, 186, 234, 39, 126, 133, 66, 11, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 33, 2, 32, 6, 65, 1, 106, 33, 6, 12, 1, 11, 11, 32, 0, 32, 2, 32, 2, 66, 33, 136, 133, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 34, 2, 66, 29, 136, 32, 2, 133, 66, 249, 243, 221, 241, 153, 246, 153, 171, 22, 126, 34, 2, 66, 32, 136, 32, 2, 133, 34, 2, 66, 32, 136, 62, 2, 0, 32, 0, 65, 4, 106, 32, 2, 62, 2, 0, 11 ]);
function n(_, ee, ne) {
if (ee.buffer.byteLength < _.byteLength + ne) {
const ie = Math.ceil((_.byteLength + ne - ee.buffer.byteLength) / 65536);
ee.grow(ie);
}
new Uint8Array(ee.buffer, ne).set(_);
}
async function xxhash_wasm_default() {
const {instance: {exports: {mem: _, xxh32: ee, xxh64: ne}}} = await WebAssembly.instantiate(t);
function h3(ne) {
let ie = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0;
return n(ne, _, 0), ee(0, ne.byteLength, ie) >>> 0;
}
function c2(ee) {
let ie = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0, re = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : 0;
n(ee, _, 8);
const se = new DataView(_.buffer);
return se.setUint32(0, ie, true), se.setUint32(4, re, true), ne(0, ee.byteLength),
se;
}
return {
h32: function(_) {
let ee = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0;
e || (e = new TextEncoder);
return h3(e.encode(_), ee).toString(16);
},
h32Raw: h3,
h64: function(_) {
let ee = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0, ne = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : 0;
e || (e = new TextEncoder);
const ie = c2(e.encode(_), ee, ne);
return ie.getUint32(0, true).toString(16) + ie.getUint32(4, true).toString(16);
},
h64Raw: function(_) {
let ee = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0, ne = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : 0;
return new Uint8Array(c2(_, ee, ne).buffer, 0, 8);
}
};
}
var t2 = new Uint8Array([ 0, 97, 115, 109, 1, 0, 0, 0, 1, 48, 8, 96, 3, 127, 127, 127, 0, 96, 3, 127, 127, 127, 1, 127, 96, 2, 127, 127, 0, 96, 2, 127, 126, 0, 96, 1, 127, 1, 127, 96, 1, 127, 1, 126, 96, 3, 127, 127, 126, 1, 126, 96, 3, 126, 127, 127, 1, 126, 3, 11, 10, 1, 1, 2, 0, 4, 6, 7, 3, 0, 5, 5, 3, 1, 0, 1, 7, 85, 9, 3, 109, 101, 109, 2, 0, 5, 120, 120, 104, 51, 50, 0, 0, 6, 105, 110, 105, 116, 51, 50, 0, 2, 8, 117, 112, 100, 97, 116, 101, 51, 50, 0, 3, 8, 100, 105, 103, 101, 115, 116, 51, 50, 0, 4, 5, 120, 120, 104, 54, 52, 0, 5, 6, 105, 110, 105, 116, 54, 52, 0, 7, 8, 117, 112, 100, 97, 116, 101, 54, 52, 0, 8, 8, 100, 105, 103, 101, 115, 116, 54, 52, 0, 9, 10, 211, 23, 10, 242, 1, 1, 4, 127, 32, 0, 32, 1, 106, 33, 3, 32, 1, 65, 16, 79, 4, 127, 32, 3, 65, 16, 107, 33, 6, 32, 2, 65, 168, 136, 141, 161, 2, 106, 33, 3, 32, 2, 65, 247, 148, 175, 175, 120, 106, 33, 4, 32, 2, 65, 177, 243, 221, 241, 121, 107, 33, 5, 3, 64, 32, 0, 40, 2, 0, 65, 247, 148, 175, 175, 120, 108, 32, 3, 106, 65, 13, 119, 65, 177, 243, 221, 241, 121, 108, 33, 3, 32, 0, 65, 4, 106, 34, 0, 40, 2, 0, 65, 247, 148, 175, 175, 120, 108, 32, 4, 106, 65, 13, 119, 65, 177, 243, 221, 241, 121, 108, 33, 4, 32, 0, 65, 4, 106, 34, 0, 40, 2, 0, 65, 247, 148, 175, 175, 120, 108, 32, 2, 106, 65, 13, 119, 65, 177, 243, 221, 241, 121, 108, 33, 2, 32, 0, 65, 4, 106, 34, 0, 40, 2, 0, 65, 247, 148, 175, 175, 120, 108, 32, 5, 106, 65, 13, 119, 65, 177, 243, 221, 241, 121, 108, 33, 5, 32, 0, 65, 4, 106, 34, 0, 32, 6, 77, 13, 0, 11, 32, 2, 65, 12, 119, 32, 5, 65, 18, 119, 106, 32, 4, 65, 7, 119, 106, 32, 3, 65, 1, 119, 106, 5, 32, 2, 65, 177, 207, 217, 178, 1, 106, 11, 32, 1, 106, 32, 0, 32, 1, 65, 15, 113, 16, 1, 11, 146, 1, 0, 32, 1, 32, 2, 106, 33, 2, 3, 64, 32, 1, 65, 4, 106, 32, 2, 75, 69, 4, 64, 32, 1, 40, 2, 0, 65, 189, 220, 202, 149, 124, 108, 32, 0, 106, 65, 17, 119, 65, 175, 214, 211, 190, 2, 108, 33, 0, 32, 1, 65, 4, 106, 33, 1, 12, 1, 11, 11, 3, 64, 32, 1, 32, 2, 79, 69, 4, 64, 32, 1, 45, 0, 0, 65, 177, 207, 217, 178, 1, 108, 32, 0, 106, 65, 11, 119, 65, 177, 243, 221, 241, 121, 108, 33, 0, 32, 1, 65, 1, 106, 33, 1, 12, 1, 11, 11, 32, 0, 65, 15, 118, 32, 0, 115, 65, 247, 148, 175, 175, 120, 108, 34, 0, 32, 0, 65, 13, 118, 115, 65, 189, 220, 202, 149, 124, 108, 34, 0, 32, 0, 65, 16, 118, 115, 11, 63, 0, 32, 0, 65, 8, 106, 32, 1, 65, 168, 136, 141, 161, 2, 106, 54, 2, 0, 32, 0, 65, 12, 106, 32, 1, 65, 247, 148, 175, 175, 120, 106, 54, 2, 0, 32, 0, 65, 16, 106, 32, 1, 54, 2, 0, 32, 0, 65, 20, 106, 32, 1, 65, 177, 243, 221, 241, 121, 107, 54, 2, 0, 11, 211, 4, 1, 6, 127, 32, 1, 32, 2, 106, 33, 6, 32, 0, 65, 24, 106, 33, 5, 32, 0, 65, 40, 106, 40, 2, 0, 33, 3, 32, 0, 32, 0, 40, 2, 0, 32, 2, 106, 54, 2, 0, 32, 0, 65, 4, 106, 34, 4, 32, 4, 40, 2, 0, 32, 2, 65, 16, 79, 32, 0, 40, 2, 0, 65, 16, 79, 114, 114, 54, 2, 0, 32, 2, 32, 3, 106, 65, 16, 73, 4, 64, 32, 3, 32, 5, 106, 32, 1, 32, 2, 252, 10, 0, 0, 32, 0, 65, 40, 106, 32, 2, 32, 3, 106, 54, 2, 0, 15, 11, 32, 3, 4, 64, 32, 3, 32, 5, 106, 32, 1, 65, 16, 32, 3, 107, 34, 2, 252, 10, 0, 0, 32, 0, 65, 8, 106, 34, 3, 40, 2, 0, 32, 5, 40, 2, 0, 65, 247, 148, 175, 175, 120, 108, 106, 65, 13, 119, 65, 177, 243, 221, 241, 121, 108, 33, 4, 32, 3, 32, 4, 54, 2, 0, 32, 0, 65, 12, 106, 34, 3, 40, 2, 0, 32, 5, 65, 4, 106, 40, 2, 0, 65, 247, 148, 175, 175, 120, 108, 106, 65, 13, 119, 65, 177, 243, 221, 241, 121, 108, 33, 4, 32, 3, 32, 4, 54, 2, 0, 32, 0, 65, 16, 106, 34, 3, 40, 2, 0, 32, 5, 65, 8, 106, 40, 2, 0, 65, 247, 148, 175, 175, 120, 108, 106, 65, 13, 119, 65, 177, 243, 221, 241, 121, 108, 33, 4, 32, 3, 32, 4, 54, 2, 0, 32, 0, 65, 20, 106, 34, 3, 40, 2, 0, 32, 5, 65, 12, 106, 40, 2, 0, 65, 247, 148, 175, 175, 120, 108, 106, 65, 13, 119, 65, 177, 243, 221, 241, 121, 108, 33, 4, 32, 3, 32, 4, 54, 2, 0, 32, 0, 65, 40, 106, 65, 0, 54, 2, 0, 32, 1, 32, 2, 106, 33, 1, 11, 32, 1, 32, 6, 65, 16, 107, 77, 4, 64, 32, 6, 65, 16, 107, 33, 8, 32, 0, 65, 8, 106, 40, 2, 0, 33, 2, 32, 0, 65, 12, 106, 40, 2, 0, 33, 3, 32, 0, 65, 16, 106, 40, 2, 0, 33, 4, 32, 0, 65, 20, 106, 40, 2, 0, 33, 7, 3, 64, 32, 1, 40, 2, 0, 65, 247, 148, 175, 175, 120, 108, 32, 2, 106, 65, 13, 119, 65, 177, 243, 221, 241, 121, 108, 33, 2, 32, 1, 65, 4, 106, 34, 1, 40, 2, 0, 65, 247, 148, 175, 175, 120, 108, 32, 3, 106, 65, 13, 119, 65, 177, 243, 221, 241, 121, 108, 33, 3, 32, 1, 65, 4, 106, 34, 1, 40, 2, 0, 65, 247, 148, 175, 175, 120, 108, 32, 4, 106, 65, 13, 119, 65, 177, 243, 221, 241, 121, 108, 33, 4, 32, 1, 65, 4, 106, 34, 1, 40, 2, 0, 65, 247, 148, 175, 175, 120, 108, 32, 7, 106, 65, 13, 119, 65, 177, 243, 221, 241, 121, 108, 33, 7, 32, 1, 65, 4, 106, 34, 1, 32, 8, 77, 13, 0, 11, 32, 0, 65, 8, 106, 32, 2, 54, 2, 0, 32, 0, 65, 12, 106, 32, 3, 54, 2, 0, 32, 0, 65, 16, 106, 32, 4, 54, 2, 0, 32, 0, 65, 20, 106, 32, 7, 54, 2, 0, 11, 32, 1, 32, 6, 73, 4, 64, 32, 5, 32, 1, 32, 6, 32, 1, 107, 34, 1, 252, 10, 0, 0, 32, 0, 65, 40, 106, 32, 1, 54, 2, 0, 11, 11, 97, 1, 1, 127, 32, 0, 65, 16, 106, 40, 2, 0, 33, 1, 32, 0, 65, 4, 106, 40, 2, 0, 4, 127, 32, 1, 65, 12, 119, 32, 0, 65, 20, 106, 40, 2, 0, 65, 18, 119, 106, 32, 0, 65, 12, 106, 40, 2, 0, 65, 7, 119, 106, 32, 0, 65, 8, 106, 40, 2, 0, 65, 1, 119, 106, 5, 32, 1, 65, 177, 207, 217, 178, 1, 106, 11, 32, 0, 40, 2, 0, 106, 32, 0, 65, 24, 106, 32, 0, 65, 40, 106, 40, 2, 0, 16, 1, 11, 157, 4, 2, 1, 127, 3, 126, 32, 0, 32, 1, 106, 33, 3, 32, 1, 65, 32, 79, 4, 126, 32, 3, 65, 32, 107, 33, 3, 32, 2, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 124, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 124, 33, 4, 32, 2, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 124, 33, 5, 32, 2, 66, 0, 124, 33, 6, 32, 2, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 125, 33, 2, 3, 64, 32, 0, 41, 3, 0, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 32, 4, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 33, 4, 32, 0, 65, 8, 106, 34, 0, 41, 3, 0, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 32, 5, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 33, 5, 32, 0, 65, 8, 106, 34, 0, 41, 3, 0, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 32, 6, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 33, 6, 32, 0, 65, 8, 106, 34, 0, 41, 3, 0, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 32, 2, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 33, 2, 32, 0, 65, 8, 106, 34, 0, 32, 3, 77, 13, 0, 11, 32, 6, 66, 12, 137, 32, 2, 66, 18, 137, 124, 32, 5, 66, 7, 137, 124, 32, 4, 66, 1, 137, 124, 32, 4, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 66, 0, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 133, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 66, 227, 220, 202, 149, 252, 206, 242, 245, 133, 127, 124, 32, 5, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 66, 0, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 133, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 66, 227, 220, 202, 149, 252, 206, 242, 245, 133, 127, 124, 32, 6, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 66, 0, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 133, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 66, 227, 220, 202, 149, 252, 206, 242, 245, 133, 127, 124, 32, 2, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 66, 0, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 133, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 66, 227, 220, 202, 149, 252, 206, 242, 245, 133, 127, 124, 5, 32, 2, 66, 197, 207, 217, 178, 241, 229, 186, 234, 39, 124, 11, 32, 1, 173, 124, 32, 0, 32, 1, 65, 31, 113, 16, 6, 11, 137, 2, 0, 32, 1, 32, 2, 106, 33, 2, 3, 64, 32, 1, 65, 8, 106, 32, 2, 77, 4, 64, 32, 1, 41, 3, 0, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 66, 0, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 32, 0, 133, 66, 27, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 66, 227, 220, 202, 149, 252, 206, 242, 245, 133, 127, 124, 33, 0, 32, 1, 65, 8, 106, 33, 1, 12, 1, 11, 11, 32, 1, 65, 4, 106, 32, 2, 77, 4, 64, 32, 1, 53, 2, 0, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 32, 0, 133, 66, 23, 137, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 66, 249, 243, 221, 241, 153, 246, 153, 171, 22, 124, 33, 0, 32, 1, 65, 4, 106, 33, 1, 11, 3, 64, 32, 1, 32, 2, 73, 4, 64, 32, 1, 49, 0, 0, 66, 197, 207, 217, 178, 241, 229, 186, 234, 39, 126, 32, 0, 133, 66, 11, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 33, 0, 32, 1, 65, 1, 106, 33, 1, 12, 1, 11, 11, 32, 0, 66, 33, 136, 32, 0, 133, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 34, 0, 32, 0, 66, 29, 136, 133, 66, 249, 243, 221, 241, 153, 246, 153, 171, 22, 126, 34, 0, 32, 0, 66, 32, 136, 133, 11, 88, 0, 32, 0, 65, 8, 106, 32, 1, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 124, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 124, 55, 3, 0, 32, 0, 65, 16, 106, 32, 1, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 124, 55, 3, 0, 32, 0, 65, 24, 106, 32, 1, 55, 3, 0, 32, 0, 65, 32, 106, 32, 1, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 125, 55, 3, 0, 11, 132, 5, 2, 3, 127, 4, 126, 32, 1, 32, 2, 106, 33, 5, 32, 0, 65, 40, 106, 33, 4, 32, 0, 65, 200, 0, 106, 40, 2, 0, 33, 3, 32, 0, 32, 0, 41, 3, 0, 32, 2, 173, 124, 55, 3, 0, 32, 2, 32, 3, 106, 65, 32, 73, 4, 64, 32, 3, 32, 4, 106, 32, 1, 32, 2, 252, 10, 0, 0, 32, 0, 65, 200, 0, 106, 32, 2, 32, 3, 106, 54, 2, 0, 15, 11, 32, 3, 4, 64, 32, 3, 32, 4, 106, 32, 1, 65, 32, 32, 3, 107, 34, 2, 252, 10, 0, 0, 32, 0, 65, 8, 106, 34, 3, 41, 3, 0, 32, 4, 41, 3, 0, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 33, 6, 32, 3, 32, 6, 55, 3, 0, 32, 0, 65, 16, 106, 34, 3, 41, 3, 0, 32, 4, 65, 8, 106, 41, 3, 0, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 33, 6, 32, 3, 32, 6, 55, 3, 0, 32, 0, 65, 24, 106, 34, 3, 41, 3, 0, 32, 4, 65, 16, 106, 41, 3, 0, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 33, 6, 32, 3, 32, 6, 55, 3, 0, 32, 0, 65, 32, 106, 34, 3, 41, 3, 0, 32, 4, 65, 24, 106, 41, 3, 0, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 33, 6, 32, 3, 32, 6, 55, 3, 0, 32, 0, 65, 200, 0, 106, 65, 0, 54, 2, 0, 32, 1, 32, 2, 106, 33, 1, 11, 32, 1, 65, 32, 106, 32, 5, 77, 4, 64, 32, 5, 65, 32, 107, 33, 2, 32, 0, 65, 8, 106, 41, 3, 0, 33, 6, 32, 0, 65, 16, 106, 41, 3, 0, 33, 7, 32, 0, 65, 24, 106, 41, 3, 0, 33, 8, 32, 0, 65, 32, 106, 41, 3, 0, 33, 9, 3, 64, 32, 1, 41, 3, 0, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 32, 6, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 33, 6, 32, 1, 65, 8, 106, 34, 1, 41, 3, 0, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 32, 7, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 33, 7, 32, 1, 65, 8, 106, 34, 1, 41, 3, 0, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 32, 8, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 33, 8, 32, 1, 65, 8, 106, 34, 1, 41, 3, 0, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 32, 9, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 33, 9, 32, 1, 65, 8, 106, 34, 1, 32, 2, 77, 13, 0, 11, 32, 0, 65, 8, 106, 32, 6, 55, 3, 0, 32, 0, 65, 16, 106, 32, 7, 55, 3, 0, 32, 0, 65, 24, 106, 32, 8, 55, 3, 0, 32, 0, 65, 32, 106, 32, 9, 55, 3, 0, 11, 32, 1, 32, 5, 73, 4, 64, 32, 4, 32, 1, 32, 5, 32, 1, 107, 34, 1, 252, 10, 0, 0, 32, 0, 65, 200, 0, 106, 32, 1, 54, 2, 0, 11, 11, 200, 2, 1, 5, 126, 32, 0, 65, 24, 106, 41, 3, 0, 33, 1, 32, 0, 41, 3, 0, 34, 2, 66, 32, 90, 4, 126, 32, 0, 65, 8, 106, 41, 3, 0, 34, 3, 66, 1, 137, 32, 0, 65, 16, 106, 41, 3, 0, 34, 4, 66, 7, 137, 124, 32, 1, 66, 12, 137, 32, 0, 65, 32, 106, 41, 3, 0, 34, 5, 66, 18, 137, 124, 124, 32, 3, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 66, 0, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 133, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 66, 227, 220, 202, 149, 252, 206, 242, 245, 133, 127, 124, 32, 4, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 66, 0, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 133, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 66, 227, 220, 202, 149, 252, 206, 242, 245, 133, 127, 124, 32, 1, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 66, 0, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 133, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 66, 227, 220, 202, 149, 252, 206, 242, 245, 133, 127, 124, 32, 5, 66, 207, 214, 211, 190, 210, 199, 171, 217, 66, 126, 66, 0, 124, 66, 31, 137, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 133, 66, 135, 149, 175, 175, 152, 182, 222, 155, 158, 127, 126, 66, 227, 220, 202, 149, 252, 206, 242, 245, 133, 127, 124, 5, 32, 1, 66, 197, 207, 217, 178, 241, 229, 186, 234, 39, 124, 11, 32, 2, 124, 32, 0, 65, 40, 106, 32, 2, 66, 31, 131, 167, 16, 6, 11 ]);
async function e2() {
const {instance: {exports: {mem: _, xxh32: ee, xxh64: ne, init32: ie, update32: re, digest32: se, init64: oe, update64: le, digest64: ue}}} = await WebAssembly.instantiate(t2);
let de = new Uint8Array(_.buffer);
function c2(ee, ne) {
if (_.buffer.byteLength < ee + ne) {
const ie = Math.ceil((ee + ne - _.buffer.byteLength) / 65536);
_.grow(ie), de = new Uint8Array(_.buffer);
}
}
function l2(_, ee, ne, ie, re, se) {
c2(_);
const oe = new Uint8Array(_);
return de.set(oe), ne(0, ee), oe.set(de.slice(0, _)), {
update(ee) {
let ne;
return de.set(oe), "string" == typeof ee ? (c2(3 * ee.length, _), ne = he.encodeInto(ee, de.subarray(_)).written) : (c2(ee.byteLength, _),
de.set(ee, _), ne = ee.byteLength), ie(0, _, ne), oe.set(de.slice(0, _)), this;
},
digest: () => (de.set(oe), se(re(0)))
};
}
function d4(_) {
return _ >>> 0;
}
const fe = BigInt(2) ** BigInt(64) - BigInt(1);
function y2(_) {
return _ & fe;
}
const he = new TextEncoder, pe = BigInt(0);
function p2(_) {
let ne = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0;
return c2(3 * _.length, 0), d4(ee(0, he.encodeInto(_, de).written, ne));
}
function v2(_) {
let ee = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : pe;
return c2(3 * _.length, 0), y2(ne(0, he.encodeInto(_, de).written, ee));
}
return {
h32: p2,
h32ToString(_) {
return p2(_, arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0).toString(16).padStart(8, "0");
},
h32Raw(_) {
let ne = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0;
return c2(_.byteLength, 0), de.set(_), d4(ee(0, _.byteLength, ne));
},
create32() {
return l2(48, arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : 0, ie, re, se, d4);
},
h64: v2,
h64ToString(_) {
return v2(_, arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : pe).toString(16).padStart(16, "0");
},
h64Raw(_) {
let ee = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : pe;
return c2(_.byteLength, 0), de.set(_), y2(ne(0, _.byteLength, ee));
},
create64() {
return l2(88, arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : pe, oe, le, ue, y2);
}
};
}
var hashFunc, crc32kTable = new Uint32Array(256), crc32cTable = new Uint32Array(256);
function generateCRC32KTable() {
for (let _ = 0; _ < 256; _++) {
let ee = _;
for (let _ = 0; _ < 8; _++) if (1 & ee) ee = ee >>> 1 ^ 3988292384; else ee >>>= 1;
crc32kTable[_] = ee;
}
}
function generateCRC32CTable() {
for (let _ = 0; _ < 256; _++) {
let ee = _;
for (let _ = 0; _ < 8; _++) if (1 & ee) ee = ee >>> 1 ^ 517762881; else ee >>>= 1;
crc32cTable[_] = ee;
}
}
generateCRC32CTable();
generateCRC32KTable();
async function initHashFunc() {
try {
const {h32ToString: _} = await e2();
hashFunc = _;
Logger("xxhash for plugin initialised", LOG_LEVEL_VERBOSE);
} catch (_) {
Logger("Could not initialise xxhash. fallback...", LOG_LEVEL_VERBOSE);
Logger(_);
try {
const {h32: _} = await xxhash_wasm_default();
hashFunc = ee => _(ee);
} catch (_) {
Logger("Could not initialise old xxhash for plugin: use sha1", LOG_LEVEL_VERBOSE);
Logger(_);
hashFunc = _ => _;
}
}
return hashFunc;
}
initHashFunc();
async function sha1(_) {
const ee = writeString(_), ne = await webcrypto.subtle.digest({
name: "SHA-1"
}, ee);
return await arrayBufferToBase64Single(ne);
}
function digestHash(_) {
let ee = "";
for (const ne of _) ee = hashFunc(ee + ne);
if ("" == ee) return hashFunc("**"); else return ee;
}
var LiveSyncCommands = class {
get app() {
return this.plugin.app;
}
get settings() {
return this.plugin.settings;
}
get localDatabase() {
return this.plugin.localDatabase;
}
get vaultAccess() {
return this.plugin.vaultAccess;
}
id2path(_, ee, ne) {
return this.plugin.id2path(_, ee, ne);
}
async path2id(_, ee) {
return await this.plugin.path2id(_, ee);
}
getPath(_) {
return this.plugin.getPath(_);
}
constructor(_) {
this.plugin = _;
}
};
function add_css(_) {
append_styles(_, "svelte-guf68w", ".deleted.svelte-guf68w{text-decoration:line-through}.svelte-guf68w{box-sizing:border-box}.scroller.svelte-guf68w{display:flex;flex-direction:column;overflow-y:scroll;max-height:60vh;user-select:text}.json-source.svelte-guf68w{white-space:pre;height:auto;overflow:auto;min-height:var(--font-ui-medium);flex-grow:1}");
}
function get_each_context(_, ee, ne) {
const ie = _.slice();
ie[25] = ee[ne];
return ie;
}
function get_each_context_1(_, ee, ne) {
const ie = _.slice();
ie[28] = ee[ne];
return ie;
}
function create_else_block(_) {
let ee, ne, ie, re, se, oe, le, ue, de, fe, he, pe, ge, me, ye, ve, Se, Ee, Ce, we, Oe, ke, xe, Ae, Le, Re = new Date(_[3].mtime).toLocaleString() + "", Te = _[5].length + "", Pe = new Date(_[4].mtime).toLocaleString() + "", Ie = _[6].length + "", De = ensure_array_like(_[11]), Be = [];
for (let ee = 0; ee < De.length; ee += 1) Be[ee] = create_each_block_1(get_each_context_1(_, De, ee));
function select_block_type_1(_, ee) {
if (false != _[8]) return create_if_block_3; else return create_else_block_1;
}
let Ne = select_block_type_1(_), Me = Ne(_), Fe = _[3]._id == _[4]._id && create_if_block_2(_), je = _[3]._id == _[4]._id && create_if_block_1(_);
return {
c() {
ee = element("div");
for (let _ = 0; _ < Be.length; _ += 1) Be[_].c();
ne = space();
Me.c();
ie = space();
re = element("div");
se = text(_[1]);
oe = space();
if (Fe) Fe.c();
le = text(" ,");
ue = text(Re);
de = space();
fe = text(Te);
he = text(" letters");
pe = space();
ge = element("div");
me = text(_[2]);
ye = space();
if (je) je.c();
ve = text(" ,");
Se = text(Pe);
Ee = space();
Ce = text(Ie);
we = text(" letters");
Oe = space();
ke = element("div");
xe = element("button");
xe.textContent = "Apply";
attr(ee, "class", "options svelte-guf68w");
attr(re, "class", "svelte-guf68w");
attr(ge, "class", "svelte-guf68w");
attr(xe, "class", "svelte-guf68w");
attr(ke, "class", "buttons svelte-guf68w");
},
m(Re, Te) {
insert(Re, ee, Te);
for (let _ = 0; _ < Be.length; _ += 1) if (Be[_]) Be[_].m(ee, null);
insert(Re, ne, Te);
Me.m(Re, Te);
insert(Re, ie, Te);
insert(Re, re, Te);
append(re, se);
append(re, oe);
if (Fe) Fe.m(re, null);
append(re, le);
append(re, ue);
append(re, de);
append(re, fe);
append(re, he);
insert(Re, pe, Te);
insert(Re, ge, Te);
append(ge, me);
append(ge, ye);
if (je) je.m(ge, null);
append(ge, ve);
append(ge, Se);
append(ge, Ee);
append(ge, Ce);
append(ge, we);
insert(Re, Oe, Te);
insert(Re, ke, Te);
append(ke, xe);
if (!Ae) {
Le = listen(xe, "click", _[12]);
Ae = true;
}
},
p(_, ne) {
if (2688 & ne) {
De = ensure_array_like(_[11]);
let ie;
for (ie = 0; ie < De.length; ie += 1) {
const re = get_each_context_1(_, De, ie);
if (Be[ie]) Be[ie].p(re, ne); else {
Be[ie] = create_each_block_1(re);
Be[ie].c();
Be[ie].m(ee, null);
}
}
for (;ie < Be.length; ie += 1) Be[ie].d(1);
Be.length = De.length;
}
if (Ne === (Ne = select_block_type_1(_)) && Me) Me.p(_, ne); else {
Me.d(1);
Me = Ne(_);
if (Me) {
Me.c();
Me.m(ie.parentNode, ie);
}
}
if (2 & ne) set_data(se, _[1]);
if (_[3]._id == _[4]._id) if (Fe) Fe.p(_, ne); else {
Fe = create_if_block_2(_);
Fe.c();
Fe.m(re, le);
} else if (Fe) {
Fe.d(1);
Fe = null;
}
if (8 & ne && Re !== (Re = new Date(_[3].mtime).toLocaleString() + "")) set_data(ue, Re);
if (32 & ne && Te !== (Te = _[5].length + "")) set_data(fe, Te);
if (4 & ne) set_data(me, _[2]);
if (_[3]._id == _[4]._id) if (je) je.p(_, ne); else {
je = create_if_block_1(_);
je.c();
je.m(ge, ve);
} else if (je) {
je.d(1);
je = null;
}
if (16 & ne && Pe !== (Pe = new Date(_[4].mtime).toLocaleString() + "")) set_data(Se, Pe);
if (64 & ne && Ie !== (Ie = _[6].length + "")) set_data(Ce, Ie);
},
d(_) {
if (_) {
detach(ee);
detach(ne);
detach(ie);
detach(re);
detach(pe);
detach(ge);
detach(Oe);
detach(ke);
}
destroy_each(Be, _);
Me.d(_);
if (Fe) Fe.d();
if (je) je.d();
Ae = false;
Le();
}
};
}
function create_if_block(_) {
let ee, ne, ie, re, se, oe;
return {
c() {
ee = element("div");
ee.textContent = "Just for a minute, please!";
ne = space();
ie = element("div");
re = element("button");
re.textContent = "Dismiss";
attr(ee, "class", "message svelte-guf68w");
attr(re, "class", "svelte-guf68w");
attr(ie, "class", "buttons svelte-guf68w");
},
m(le, ue) {
insert(le, ee, ue);
insert(le, ne, ue);
insert(le, ie, ue);
append(ie, re);
if (!se) {
oe = listen(re, "click", _[12]);
se = true;
}
},
p: noop2,
d(_) {
if (_) {
detach(ee);
detach(ne);
detach(ie);
}
se = false;
oe();
}
};
}
function create_if_block_4(_) {
let ee, ne, ie, re, se, oe, le, ue, de, fe, he = false, pe = _[28][1] + "";
ue = init_binding_group(_[21][0]);
return {
c() {
ee = element("label");
ne = element("input");
re = space();
se = element("div");
oe = text(pe);
attr(ne, "type", "radio");
attr(ne, "name", "disp");
ne.__value = ie = _[28][0];
set_input_value(ne, ne.__value);
attr(ne, "class", "sls-setting-tab svelte-guf68w");
attr(se, "class", "sls-setting-menu-btn svelte-guf68w");
attr(ee, "class", le = null_to_empty("sls-setting-label " + (_[28][0] == _[7] ? "selected" : "")) + " svelte-guf68w");
ue.p(ne);
},
m(ie, le) {
insert(ie, ee, le);
append(ee, ne);
ne.checked = ne.__value === _[7];
append(ee, re);
append(ee, se);
append(se, oe);
if (!de) {
fe = listen(ne, "change", _[20]);
de = true;
}
},
p(_, re) {
if (2048 & re && ie !== (ie = _[28][0])) {
ne.__value = ie;
set_input_value(ne, ne.__value);
he = true;
}
if (he || 2176 & re) ne.checked = ne.__value === _[7];
if (2048 & re && pe !== (pe = _[28][1] + "")) set_data(oe, pe);
if (2176 & re && le !== (le = null_to_empty("sls-setting-label " + (_[28][0] == _[7] ? "selected" : "")) + " svelte-guf68w")) attr(ee, "class", le);
},
d(_) {
if (_) detach(ee);
ue.r();
de = false;
fe();
}
};
}
function create_each_block_1(_) {
let ee, ne = ("" == _[28][0] || false != _[9][_[28][0]]) && create_if_block_4(_);
return {
c() {
if (ne) ne.c();
ee = empty();
},
m(_, ie) {
if (ne) ne.m(_, ie);
insert(_, ee, ie);
},
p(_, ie) {
if ("" == _[28][0] || false != _[9][_[28][0]]) if (ne) ne.p(_, ie); else {
ne = create_if_block_4(_);
ne.c();
ne.m(ee.parentNode, ee);
} else if (ne) {
ne.d(1);
ne = null;
}
},
d(_) {
if (_) detach(ee);
if (ne) ne.d(_);
}
};
}
function create_else_block_1(_) {
let ee;
return {
c() {
ee = text("NO PREVIEW");
},
m(_, ne) {
insert(_, ee, ne);
},
p: noop2,
d(_) {
if (_) detach(ee);
}
};
}
function create_if_block_3(_) {
let ee, ne = ensure_array_like(_[10]), ie = [];
for (let ee = 0; ee < ne.length; ee += 1) ie[ee] = create_each_block(get_each_context(_, ne, ee));
return {
c() {
ee = element("div");
for (let _ = 0; _ < ie.length; _ += 1) ie[_].c();
attr(ee, "class", "op-scrollable json-source svelte-guf68w");
},
m(_, ne) {
insert(_, ee, ne);
for (let _ = 0; _ < ie.length; _ += 1) if (ie[_]) ie[_].m(ee, null);
},
p(_, re) {
if (1024 & re) {
ne = ensure_array_like(_[10]);
let se;
for (se = 0; se < ne.length; se += 1) {
const oe = get_each_context(_, ne, se);
if (ie[se]) ie[se].p(oe, re); else {
ie[se] = create_each_block(oe);
ie[se].c();
ie[se].m(ee, null);
}
}
for (;se < ie.length; se += 1) ie[se].d(1);
ie.length = ne.length;
}
},
d(_) {
if (_) detach(ee);
destroy_each(ie, _);
}
};
}
function create_each_block(_) {
let ee, ne, ie, re = _[25][1] + "";
return {
c() {
ee = element("span");
ne = text(re);
attr(ee, "class", ie = null_to_empty(_[25][0] == import_diff_match_patch.DIFF_DELETE ? "deleted" : _[25][0] == import_diff_match_patch.DIFF_INSERT ? "added" : "normal") + " svelte-guf68w");
},
m(_, ie) {
insert(_, ee, ie);
append(ee, ne);
},
p(_, se) {
if (1024 & se && re !== (re = _[25][1] + "")) set_data(ne, re);
if (1024 & se && ie !== (ie = null_to_empty(_[25][0] == import_diff_match_patch.DIFF_DELETE ? "deleted" : _[25][0] == import_diff_match_patch.DIFF_INSERT ? "added" : "normal") + " svelte-guf68w")) attr(ee, "class", ie);
},
d(_) {
if (_) detach(ee);
}
};
}
function create_if_block_2(_) {
let ee, ne, ie = revStringToRevNumber(_[3]._rev) + "";
return {
c() {
ee = text("Rev:");
ne = text(ie);
},
m(_, ie) {
insert(_, ee, ie);
insert(_, ne, ie);
},
p(_, ee) {
if (8 & ee && ie !== (ie = revStringToRevNumber(_[3]._rev) + "")) set_data(ne, ie);
},
d(_) {
if (_) {
detach(ee);
detach(ne);
}
}
};
}
function create_if_block_1(_) {
let ee, ne, ie = revStringToRevNumber(_[4]._rev) + "";
return {
c() {
ee = text("Rev:");
ne = text(ie);
},
m(_, ie) {
insert(_, ee, ie);
insert(_, ne, ie);
},
p(_, ee) {
if (16 & ee && ie !== (ie = revStringToRevNumber(_[4]._rev) + "")) set_data(ne, ie);
},
d(_) {
if (_) {
detach(ee);
detach(ne);
}
}
};
}
function create_fragment(_) {
let ee, ne, ie, re;
function select_block_type(_, ee) {
if (!_[3] || !_[4]) return create_if_block; else return create_else_block;
}
let se = select_block_type(_), oe = se(_);
return {
c() {
ee = element("h2");
ne = text(_[0]);
ie = space();
oe.c();
re = empty();
attr(ee, "class", "svelte-guf68w");
},
m(_, se) {
insert(_, ee, se);
append(ee, ne);
insert(_, ie, se);
oe.m(_, se);
insert(_, re, se);
},
p(_, [ee]) {
if (1 & ee) set_data(ne, _[0]);
if (se === (se = select_block_type(_)) && oe) oe.p(_, ee); else {
oe.d(1);
oe = se(_);
if (oe) {
oe.c();
oe.m(re.parentNode, re);
}
}
},
i: noop2,
o: noop2,
d(_) {
if (_) {
detach(ee);
detach(ie);
detach(re);
}
oe.d(_);
}
};
}
function revStringToRevNumber(_) {
if (!_) return ""; else return _.split("-")[0];
}
function instance(_, ee, ne) {
let ie, re, se, oe, le, ue, {docs: de = []} = ee, {callback: fe = (async (_, ee) => {
Promise.resolve();
})} = ee, {filename: he = ""} = ee, {nameA: pe = "A"} = ee, {nameB: ge = "B"} = ee, {defaultSelect: me = ""} = ee, ye = "", ve = "", Se = {}, Ee = {}, Ce = {}, we = {}, Oe = me;
function docToString(_) {
return "plain" == _.datatype ? getDocData(_.data) : readString(new Uint8Array(decodeBinary(_.data)));
}
_.$$set = _ => {
if ("docs" in _) ne(13, de = _.docs);
if ("callback" in _) ne(14, fe = _.callback);
if ("filename" in _) ne(0, he = _.filename);
if ("nameA" in _) ne(1, pe = _.nameA);
if ("nameB" in _) ne(2, ge = _.nameB);
if ("defaultSelect" in _) ne(15, me = _.defaultSelect);
};
_.$$.update = () => {
if (991352 & _.$$.dirty) if (de && de.length >= 1) {
if (de[0].mtime < de[1].mtime) {
ne(3, oe = de[0]);
ne(4, le = de[1]);
} else {
ne(3, oe = de[1]);
ne(4, le = de[0]);
}
ne(5, ye = docToString(oe));
ne(6, ve = docToString(le));
try {
ne(16, Se = false);
ne(17, Ee = false);
ne(16, Se = JSON.parse(ye));
ne(17, Ee = JSON.parse(ve));
ne(18, Ce = mergeObject(Se, Ee));
ne(19, we = mergeObject(Ee, Se));
if (JSON.stringify(Ce) == JSON.stringify(we)) ne(19, we = false);
} catch (_) {
ne(19, we = false);
ne(18, Ce = false);
}
}
if (983040 & _.$$.dirty) ne(9, ie = {
"": false,
A: Se,
B: Ee,
AB: Ce,
BA: we
});
if (640 & _.$$.dirty) ne(8, re = Oe in ie ? ie[Oe] : {});
if (65792 & _.$$.dirty) ne(10, ue = function getJsonDiff(_, ee) {
return function getDiff(_, ee) {
const ne = new import_diff_match_patch.diff_match_patch, ie = ne.diff_linesToChars_(_, ee), re = ne.diff_main(ie.chars1, ie.chars2, false);
ne.diff_charsToLines_(re, ie.lineArray);
return re;
}(JSON.stringify(_, null, 2), JSON.stringify(ee, null, 2));
}(Se, re));
if (6 & _.$$.dirty) ne(11, se = [ [ "", "Not now" ], [ "A", pe || "A" ], [ "B", ge || "B" ], [ "AB", `${pe || "A"} + ${ge || "B"}` ], [ "BA", `${ge || "B"} + ${pe || "A"}` ] ]);
};
return [ he, pe, ge, oe, le, ye, ve, Oe, re, ie, ue, se, function apply() {
if (oe._id == le._id) {
if ("A" == Oe) return fe(oe._rev, void 0);
if ("B" == Oe) return fe(le._rev, void 0);
} else {
if ("A" == Oe) return fe(void 0, docToString(oe));
if ("B" == Oe) return fe(void 0, docToString(le));
}
if ("BA" == Oe) return fe(void 0, JSON.stringify(we, null, 2));
if ("AB" == Oe) return fe(void 0, JSON.stringify(Ce, null, 2));
fe(void 0, void 0);
}, de, fe, me, Se, Ee, Ce, we, function input_change_handler() {
Oe = this.__value;
ne(7, Oe);
}, [ [] ] ];
}
var context, JsonResolvePane = class extends SvelteComponent {
constructor(_) {
super();
init2(this, _, instance, create_fragment, safe_not_equal, {
docs: 13,
callback: 14,
filename: 0,
nameA: 1,
nameB: 2,
defaultSelect: 15
}, add_css);
}
}, JsonResolvePane_default = JsonResolvePane, JsonResolveModal = class extends import_obsidian.Modal {
constructor(_, ee, ne, ie, re, se, oe) {
super(_);
this.callback = ie;
this.filename = ee;
this.docs = ne;
this.nameA = re || "";
this.nameB = se || "";
this.defaultSelect = oe || "";
waitForSignal(`cancel-internal-conflict:${ee}`).then((() => this.close()));
}
async UICallback(_, ee) {
var ne;
this.close();
await (null == (ne = this.callback) ? void 0 : ne.call(this, _, ee));
this.callback = void 0;
}
onOpen() {
const {contentEl: _} = this;
this.titleEl.setText("Conflicted Setting");
_.empty();
if (null == this.component) this.component = new JsonResolvePane_default({
target: _,
props: {
docs: this.docs,
filename: this.filename,
nameA: this.nameA,
nameB: this.nameB,
defaultSelect: this.defaultSelect,
callback: (_, ee) => this.UICallback(_, ee)
}
});
}
onClose() {
const {contentEl: _} = this;
_.empty();
if (null != this.callback) this.callback(void 0);
if (null != this.component) {
this.component.$destroy();
this.component = void 0;
}
}
};
function reactiveSource(_) {
return _reactive({
initialValue: _
});
}
function reactive(_, ee) {
return _reactive({
expression: _,
initialValue: ee
});
}
function _reactive({expression: _, initialValue: ee}) {
let ne, ie = false;
const re = new Set, se = {
myContext: new Set,
markDirty() {
ie = true;
se.markDependedDirty();
},
rippleChanged() {
re.forEach((_ => _(se)));
se.myContext.forEach((_ => _.rippleChanged()));
},
markClean() {
ie = false;
},
markDependedDirty() {
se.myContext.forEach((_ => _.markDirty()));
},
get isDirty() {
return ie;
},
get value() {
if (context) se.myContext.add(context);
if (!_) return ne;
if (ie) {
const ee = ne, ie = _();
if (isObjectDifferent(ee, ie)) {
ne = ie;
se.markClean();
se.markDependedDirty();
}
}
return ne;
},
set value(_) {
if (isObjectDifferent(ne, _)) {
ne = _;
se.markDirty();
se.rippleChanged();
}
},
onChanged(_) {
re.add(_);
se.markDirty();
},
offChanged(_) {
re.delete(_);
}
};
ne = function initialize() {
const ne = context;
context = se;
const ie = _ ? _(ee) : ee;
context = ne;
return ie;
}();
return se;
}
function computed(_) {
const ee = reactive(_);
return () => ee.value;
}
var lockStats = reactiveSource({
pending: [],
running: [],
count: 0
}), collectingChunks = reactiveSource(0), pluginScanningCount = reactiveSource(0), hiddenFilesProcessingCount = reactiveSource(0), hiddenFilesEventCount = reactiveSource(0), logStore = new QueueProcessor((_ => _), {
batchSize: 1,
suspended: false,
keepResultUntilDownstreamConnected: true
}), logMessages = reactiveSource([]), d = "", d2 = "\n";
function serialize(_) {
var ee, ne, ie, re, se;
let oe = "";
oe += ":";
oe += _.category + d + _.name + d + _.term + d2;
oe += (null != (ee = _.version) ? ee : "") + d2;
oe += _.mtime + d2;
for (const ee of _.files) {
oe += ee.filename + d + (null != (ne = ee.displayName) ? ne : "") + d + (null != (ie = ee.version) ? ie : "") + d2;
const _ = digestHash(null != (re = ee.data) ? re : []);
oe += ee.mtime + d + ee.size + d + _ + d2;
for (const _ of null != (se = ee.data) ? se : []) oe += _ + d;
oe += d2;
}
return oe;
}
function splitWithDelimiters(_) {
const ee = [];
for (const ne of _) {
let _ = 0;
const ie = ne.length;
let re, se, oe = -1;
do {
re = ne.indexOf(d, _);
se = ne.indexOf(d2, _);
if (-1 == re && -1 == se) break;
if (-1 == re) oe = se; else if (-1 == se) oe = re; else oe = re < se ? re : se;
ee.push(ne.slice(_, oe + 1));
_ = oe + 1;
} while (oe < ie);
if (_ < ie) ee.push(ne.slice(_));
}
if ("" == _[_.length - 1]) ee.push("");
return ee;
}
function getTokenizer(_) {
const ee = splitWithDelimiters(_);
ee[0] = ee[0].substring(1);
let ne = 0, ie = false;
return {
next() {
if (ie) return "";
if (ne >= ee.length) return "";
const _ = ee[ne];
if (!_.endsWith(d2)) ne++; else ie = true;
if (_.endsWith(d) || _.endsWith(d2)) return _.substring(0, _.length - 1); else return _ + this.next();
},
nextLine() {
if (ie) ne++; else {
for (;!ee[ne].endsWith(d2); ) {
ne++;
if (ne >= ee.length) break;
}
ne++;
}
ie = false;
}
};
}
function deserialize2(_) {
const ee = getTokenizer(_), ne = ee.next(), ie = ee.next(), re = ee.next();
ee.nextLine();
const se = ee.next();
ee.nextLine();
const oe = Number(ee.next());
ee.nextLine();
const le = Object.assign({}, {
category: ne,
name: ie,
term: re,
version: se,
mtime: oe,
files: []
});
let ue = "";
do {
ue = ee.next();
if (!ue) break;
const _ = ee.next(), ne = ee.next();
ee.nextLine();
const ie = Number(ee.next()), re = Number(ee.next()), se = ee.next();
ee.nextLine();
const oe = [];
let de = "";
do {
de = ee.next();
if ("" == de) break;
oe.push(de);
} while ("" != de);
le.files.push({
filename: ue,
displayName: _,
version: ne,
mtime: ie,
size: re,
data: oe,
hash: se
});
ee.nextLine();
} while (ue);
return le;
}
function deserialize(_, ee) {
try {
if (":" == _[0][0]) return deserialize2(_); else return JSON.parse(_.join(""));
} catch (ne) {
try {
return (0, import_obsidian.parseYaml)(_.join(""));
} catch (_) {
return ee;
}
}
}
var pluginList = writable([]), pluginIsEnumerating = writable(false), ConfigSync = class extends LiveSyncCommands {
constructor(_) {
super(_);
this.pluginDialog = void 0;
this.periodicPluginSweepProcessor = new PeriodicProcessor(this.plugin, (async () => await this.scanAllConfigFiles(false)));
this.pluginList = [];
this.pluginScanProcessor = new QueueProcessor((async _ => {
const ee = _[0], ne = ee.path || this.getPath(ee), ie = this.pluginList.find((_ => _.documentPath == ne));
if (ie && ie.mtime == ee.mtime) return [];
try {
const _ = await this.loadPluginData(ne);
if (_) {
let ee = [ ...this.pluginList ];
ee = ee.filter((ee => ee.documentPath != _.documentPath));
ee.push(_);
this.pluginList = ee;
pluginList.set(ee);
}
return [];
} catch (_) {
Logger(`Something happened at enumerating customization :${ne}`, LOG_LEVEL_NOTICE);
Logger(_, LOG_LEVEL_VERBOSE);
}
return [];
}), {
suspended: false,
batchSize: 1,
concurrentLimit: 10,
delay: 100,
yieldThreshold: 10,
maintainDelay: false,
totalRemainingReactiveSource: pluginScanningCount
}).startPipeline().root.onUpdateProgress((() => {
scheduleTask("checkMissingConfigurations", 250, (async () => {
if (this.pluginScanProcessor.isIdle()) await this.createMissingConfigurationEntry();
}));
}));
this.recentProcessedInternalFiles = [];
pluginScanningCount.onChanged((_ => {
const ee = _.value;
pluginIsEnumerating.set(0 != ee);
}));
}
get kvDB() {
return this.plugin.kvDB;
}
showPluginSyncModal() {
if (this.settings.usePluginSync) if (this.pluginDialog) this.pluginDialog.open(); else {
this.pluginDialog = new PluginDialogModal(this.app, this.plugin);
this.pluginDialog.open();
}
}
hidePluginSyncModal() {
if (null != this.pluginDialog) {
this.pluginDialog.close();
this.pluginDialog = void 0;
}
}
onunload() {
var _;
this.hidePluginSyncModal();
null == (_ = this.periodicPluginSweepProcessor) || _.disable();
}
onload() {
this.plugin.addCommand({
id: "livesync-plugin-dialog-ex",
name: "Show customization sync dialog",
callback: () => {
this.showPluginSyncModal();
}
});
}
getFileCategory(_) {
if (2 == _.split("/").length && _.endsWith(".json")) return "CONFIG";
if (4 == _.split("/").length && _.startsWith(`${this.app.vault.configDir}/themes/`)) return "THEME";
if (_.startsWith(`${this.app.vault.configDir}/snippets/`) && _.endsWith(".css")) return "SNIPPET";
if (_.startsWith(`${this.app.vault.configDir}/plugins/`)) if (_.endsWith("/styles.css") || _.endsWith("/manifest.json") || _.endsWith("/main.js")) return "PLUGIN_MAIN"; else if (_.endsWith("/data.json")) return "PLUGIN_DATA"; else return "";
return "";
}
isTargetPath(_) {
if (!_.startsWith(this.app.vault.configDir)) return false; else return "" != this.getFileCategory(_);
}
async onInitializeDatabase(_) {
if (this.settings.usePluginSync) try {
Logger("Scanning customizations...");
await this.scanAllConfigFiles(_);
Logger("Scanning customizations : done");
} catch (_) {
Logger("Scanning customizations : failed");
Logger(_, LOG_LEVEL_VERBOSE);
}
}
async beforeReplicate(_) {
if (this.settings.autoSweepPlugins && this.settings.usePluginSync) await this.scanAllConfigFiles(_);
}
async onResume() {
if (!this.plugin.suspended) {
if (this.settings.autoSweepPlugins && this.settings.usePluginSync) await this.scanAllConfigFiles(false);
this.periodicPluginSweepProcessor.enable(this.settings.autoSweepPluginsPeriodic && !this.settings.watchInternalFileChanges ? 1e3 * PERIODIC_PLUGIN_SWEEP : 0);
}
}
async reloadPluginList(_) {
this.pluginList = [];
pluginList.set(this.pluginList);
await this.updatePluginList(_);
}
async loadPluginData(_) {
const ee = await this.localDatabase.getDBEntry(_, void 0, false, false);
if (ee) {
const ne = deserialize(getDocDataAsArray(ee.data), {}), ie = [];
let re = false;
for (const _ of ne.files) {
const ee = {
..._,
data: []
};
if (!_.hash) {
const ne = digestHash(getDocDataAsArray(ee.data));
_.hash = ne;
re = true;
}
ee.data = [ _.hash ];
ie.push(ee);
}
if (re) {
Logger(`Digest created for ${_} to improve checking`, LOG_LEVEL_VERBOSE);
ee.data = serialize(ne);
fireAndForget((() => this.localDatabase.putDBEntry(createSavingEntryFromLoadedEntry(ee))));
}
return {
...ne,
documentPath: this.getPath(ee),
files: ie
};
}
return false;
}
async createMissingConfigurationEntry() {
let _ = false;
for (const ee of this.pluginList) {
const ne = `${ee.category}/${ee.name}`;
if (!(ne in this.plugin.settings.pluginSyncExtendedSetting)) this.plugin.settings.pluginSyncExtendedSetting[ne] = {
key: ne,
mode: MODE_SELECTIVE,
files: []
};
if (this.plugin.settings.pluginSyncExtendedSetting[ne].files.sort().join(",").toLowerCase() != ee.files.map((_ => _.filename)).sort().join(",").toLowerCase()) {
this.plugin.settings.pluginSyncExtendedSetting[ne].files = ee.files.map((_ => _.filename)).sort();
_ = true;
}
}
if (_) await this.plugin.saveSettingData();
}
async updatePluginList(_, ee) {
if (this.settings.usePluginSync) {
try {
const _ = ee ? await this.path2id(ee) : "", ne = ee ? this.localDatabase.findEntries(_, _ + "", {
include_docs: true,
key: _,
limit: 1
}) : this.localDatabase.findEntries(ICXHeader + "", `${ICXHeader}`, {
include_docs: true
});
for await (const _ of ne) {
const ne = _.path || this.getPath(_);
if (!ee || ee == ne) this.pluginScanProcessor.enqueue(_);
}
} finally {
pluginIsEnumerating.set(false);
}
pluginIsEnumerating.set(false);
} else {
this.pluginScanProcessor.clearQueue();
this.pluginList = [];
pluginList.set(this.pluginList);
}
}
async compareUsingDisplayData(_, ee) {
const ne = await this.localDatabase.getDBEntry(_.documentPath), ie = await this.localDatabase.getDBEntry(ee.documentPath);
if (ne && ie) {
const re = deserialize(getDocDataAsArray(ne.data), {});
re.documentPath = _.documentPath;
const se = deserialize(getDocDataAsArray(ie.data), {});
se.documentPath = ee.documentPath;
return await this.showJSONMergeDialogAndMerge(ne, ie, re, se);
}
return false;
}
showJSONMergeDialogAndMerge(_, ee, ne, ie) {
const re = {
...ne.files[0],
ctime: ne.files[0].mtime,
_id: `${ne.documentPath}`
}, se = ie.files[0], oe = {
..._,
...re,
datatype: "newnote"
}, le = {
...ee,
...se,
datatype: "newnote"
};
return serialized("config:merge-data", (() => new Promise((_ => {
Logger("Opening data-merging dialog", LOG_LEVEL_VERBOSE);
const ee = stripAllPrefixes(oe.path.split("/").slice(-1).join("/"));
new JsonResolveModal(this.app, ee, [ oe, le ], (async (ee, ie) => {
if (null == ie) return _(false);
try {
_(await this.applyData(ne, ie));
} catch (ee) {
Logger("Could not apply merged file");
Logger(ee, LOG_LEVEL_VERBOSE);
_(false);
}
}), "📡", "🛰️", "B").open();
}))));
}
async applyData(_, ee) {
Logger(`Applying ${_.displayName || _.name}..`);
const ne = this.app.vault.configDir;
try {
if (!_.documentPath) throw "InternalError: Document path not exist";
const ie = await this.localDatabase.getDBEntry(_.documentPath);
if (false == ie) throw "Not found on database";
const re = deserialize(getDocDataAsArray(ie.data), {});
for (const ie of re.files) {
Logger(`Applying ${ie.filename} of ${_.displayName || _.name}..`);
try {
const re = `${ne}/${ie.filename}`;
await this.vaultAccess.ensureDirectory(re);
if (!ee) {
const _ = decodeBinary(ie.data);
await this.vaultAccess.adapterWrite(re, _);
} else await this.vaultAccess.adapterWrite(re, ee);
Logger(`Applying ${ie.filename} of ${_.displayName || _.name}.. Done`);
} catch (ee) {
Logger(`Applying ${ie.filename} of ${_.displayName || _.name}.. Failed`);
Logger(ee, LOG_LEVEL_VERBOSE);
}
}
const se = `${ne}/${re.files[0].filename}`;
await this.storeCustomizationFiles(se);
await this.updatePluginList(true, se);
await delay(100);
Logger(`Config ${_.displayName || _.name} has been applied`, LOG_LEVEL_NOTICE);
if ("PLUGIN_DATA" == _.category || "PLUGIN_MAIN" == _.category) {
const ee = Object.values(this.app.plugins.manifests), ie = this.app.plugins.enabledPlugins, re = ee.find((ee => ie.has(ee.id) && ee.dir == `${ne}/plugins/${_.name}`));
if (re) {
Logger(`Unloading plugin: ${re.name}`, LOG_LEVEL_NOTICE, "plugin-reload-" + re.id);
await this.app.plugins.unloadPlugin(re.id);
await this.app.plugins.loadPlugin(re.id);
Logger(`Plugin reloaded: ${re.name}`, LOG_LEVEL_NOTICE, "plugin-reload-" + re.id);
}
} else if ("CONFIG" == _.category) this.plugin.askReload();
return true;
} catch (ee) {
Logger(`Applying ${_.displayName || _.name}.. Failed`);
Logger(ee, LOG_LEVEL_VERBOSE);
return false;
}
}
async deleteData(_) {
try {
if (_.documentPath) {
await this.deleteConfigOnDatabase(_.documentPath);
await this.updatePluginList(false, _.documentPath);
Logger(`Delete: ${_.documentPath}`, LOG_LEVEL_NOTICE);
}
return true;
} catch (ee) {
Logger(`Failed to delete: ${_.documentPath}`, LOG_LEVEL_NOTICE);
return false;
}
}
async parseReplicationResultItem(_) {
if (_._id.startsWith(ICXHeader)) {
if (this.plugin.settings.usePluginSync) await this.updatePluginList(false, _.path ? _.path : this.getPath(_));
if (this.plugin.settings.usePluginSync && this.plugin.settings.notifyPluginOrSettingUpdated) if (!this.pluginDialog || this.pluginDialog && !this.pluginDialog.isOpened()) {
const _ = createFragment((_ => {
_.createEl("span", void 0, (_ => {
_.appendText("Some configuration has been arrived, Press ");
_.appendChild(_.createEl("a", void 0, (_ => {
_.text = "HERE";
_.addEventListener("click", (() => {
this.showPluginSyncModal();
}));
})));
_.appendText(" to open the config sync dialog , or press elsewhere to dismiss this message.");
}));
})), ee = "popupUpdated-plugins";
scheduleTask(ee, 1e3, (async () => {
var ne;
const ie = await memoIfNotExist(ee, (() => new import_obsidian.Notice(_, 0)));
if (!(null == (ne = null == ie ? void 0 : ie.noticeEl) ? void 0 : ne.isShown())) memoObject(ee, new import_obsidian.Notice(_, 0));
scheduleTask(ee + "-close", 2e4, (() => {
var _;
const ne = retrieveMemoObject(ee);
if (ne) {
if (null == (_ = null == ne ? void 0 : ne.noticeEl) ? void 0 : _.isShown()) ne.hide();
disposeMemoObject(ee);
}
}));
}));
}
return true;
}
return false;
}
async realizeSettingSyncMode() {
var _;
null == (_ = this.periodicPluginSweepProcessor) || _.disable();
if (!this.plugin.suspended) if (this.settings.usePluginSync) {
if (this.settings.autoSweepPlugins) await this.scanAllConfigFiles(false);
this.periodicPluginSweepProcessor.enable(this.settings.autoSweepPluginsPeriodic && !this.settings.watchInternalFileChanges ? 1e3 * PERIODIC_PLUGIN_SWEEP : 0);
}
}
async makeEntryFromFile(_) {
const ee = await this.vaultAccess.adapterStat(_);
let ne, ie;
if (!ee) return false;
const re = await this.vaultAccess.adapterReadBinary(_);
let se;
try {
se = await arrayBufferToBase64(re);
if (_.toLowerCase().endsWith("/manifest.json")) {
const ee = readString(new Uint8Array(re));
try {
const _ = JSON.parse(ee);
if ("version" in _) ne = `${_.version}`;
if ("name" in _) ie = `${_.name}`;
} catch (ee) {
Logger(`Configuration sync data: ${_} looks like manifest, but could not read the version`, LOG_LEVEL_INFO);
}
}
} catch (ee) {
Logger(`The file ${_} could not be encoded`);
Logger(ee, LOG_LEVEL_VERBOSE);
return false;
}
const oe = ee.mtime;
return {
filename: _.substring(this.app.vault.configDir.length + 1),
data: se,
mtime: oe,
size: ee.size,
version: ne,
displayName: ie
};
}
filenameToUnifiedKey(_, ee) {
const ne = ee || this.plugin.deviceAndVaultName, ie = this.getFileCategory(_), re = "CONFIG" == ie || "SNIPPET" == ie ? _.split("/").slice(-1)[0] : "PLUGIN_ETC" == ie ? _.split("/").slice(-2).join("/") : _.split("/").slice(-2)[0];
return `${ICXHeader}${ne}/${ie}/${re}.md`;
}
async storeCustomizationFiles(_, ee) {
const ne = ee || this.plugin.deviceAndVaultName;
if ("" == ne) {
Logger("We have to configure the device name", LOG_LEVEL_NOTICE);
return;
}
const ie = this.filenameToUnifiedKey(_, ne);
return await serialized(`plugin-${ie}`, (async () => {
const ee = this.getFileCategory(_);
let ie = 0, re = [];
const se = "CONFIG" == ee || "SNIPPET" == ee ? _.split("/").reverse()[0] : _.split("/").reverse()[1], oe = _.split("/").slice(0, -1).join("/"), le = this.filenameToUnifiedKey(_, ne), ue = await this.path2id(le), de = {
category: ee,
files: [],
name: se,
mtime: 0,
term: ne
};
if ("CONFIG" == ee || "SNIPPET" == ee || "PLUGIN_ETC" == ee || "PLUGIN_DATA" == ee) {
re = [ _ ];
if ("PLUGIN_ETC" == ee) de.displayName = _.split("/").slice(-1).join("/");
} else if ("PLUGIN_MAIN" == ee) re = [ "manifest.json", "main.js", "styles.css" ].map((_ => `${oe}/${_}`)); else if ("THEME" == ee) re = [ "manifest.json", "theme.css" ].map((_ => `${oe}/${_}`));
for (const _ of re) {
const ee = await this.makeEntryFromFile(_);
if (false != ee) {
if (ee.version) de.version = ee.version;
if (ee.displayName) de.displayName = ee.displayName;
ie = 0 == ie ? ee.mtime : (ee.mtime + ie) / 2;
de.files.push(ee);
} else Logger(`Config: skipped (Possibly is not exist): ${_} `, LOG_LEVEL_VERBOSE);
}
de.mtime = ie;
if (0 == de.files.length) {
Logger(`Nothing left: deleting.. ${_}`);
await this.deleteConfigOnDatabase(le);
await this.updatePluginList(false, le);
return;
}
const fe = createTextBlob(serialize(de));
try {
const _ = await this.localDatabase.getDBEntryMeta(le, void 0, false);
let ee;
if (false === _) ee = {
_id: ue,
path: le,
data: fe,
mtime: ie,
ctime: ie,
datatype: "newnote",
size: fe.size,
children: [],
deleted: false,
type: "newnote",
eden: {}
}; else {
if (_.mtime == ie) return true;
const ne = await this.localDatabase.getDBEntryFromMeta(_, {}, false, false);
if (ne) {
const _ = await deserialize(getDocDataAsArray(ne.data), {});
if (_.files.length == de.files.length) {
const ee = _.files.map((_ => ({
prev: _,
curr: de.files.find((ee => ee.filename == _.filename))
}))).map((async _ => {
var ee, ne;
try {
return await isDocContentSame(null != (ne = null == (ee = _.curr) ? void 0 : ee.data) ? ne : [], _.prev.data);
} catch (_) {
return false;
}
}));
if ((await Promise.all(ee)).every((_ => true == _))) {
Logger(`STORAGE --\x3e DB:${le}: (config) Skipped (Same content)`, LOG_LEVEL_VERBOSE);
return true;
}
}
}
ee = {
..._,
data: fe,
mtime: ie,
size: fe.size,
datatype: "newnote",
children: [],
deleted: false,
type: "newnote"
};
}
const ne = await this.localDatabase.putDBEntry(ee);
await this.updatePluginList(false, ee.path);
Logger(`STORAGE --\x3e DB:${le}: (config) Done`);
return ne;
} catch (_) {
Logger(`STORAGE --\x3e DB:${le}: (config) Failed`);
Logger(_, LOG_LEVEL_VERBOSE);
return false;
}
}));
}
async watchVaultRawEventsAsync(_) {
if (!this.settings.usePluginSync) return false;
if (!this.isTargetPath(_)) return false;
const ee = await this.vaultAccess.adapterStat(_);
if (ee && "file" != ee.type) return false;
const ne = normalizePath(this.app.vault.configDir);
if (Object.values(this.settings.pluginSyncExtendedSetting).filter((_ => _.mode != MODE_SELECTIVE)).map((_ => _.files)).flat().map((_ => `${ne}/${_}`.toLowerCase())).some((ee => ee.startsWith(_.toLowerCase())))) {
Logger(`Customization file skipped: ${_}`, LOG_LEVEL_VERBOSE);
return;
}
const ie = ~~((ee && ee.mtime || 0) / 1e3), re = `${_}-${ie}`;
if (this.recentProcessedInternalFiles.contains(re)) return true;
this.recentProcessedInternalFiles = [ re, ...this.recentProcessedInternalFiles ].slice(0, 100);
scheduleTask(this.filenameToUnifiedKey(_), 100, (async () => {
await this.storeCustomizationFiles(_);
}));
}
async scanAllConfigFiles(_) {
await shareRunningResult("scanAllConfigFiles", (async () => {
var ee;
Logger("Scanning customizing files.", _ ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO, "scan-all-config");
const ne = this.plugin.deviceAndVaultName;
if ("" == ne) {
Logger("We have to configure the device name", LOG_LEVEL_NOTICE);
return;
}
const ie = (await this.scanInternalFiles()).filter((_ => this.isTargetPath(_))).map((_ => ({
key: this.filenameToUnifiedKey(_),
file: _
}))), re = [ ...new Set(ie.map((_ => _.key))) ];
let se = (await this.localDatabase.allDocsRaw({
startkey: ICXHeader + "",
endkey: `${ICXHeader}`,
include_docs: true
})).rows.map((_ => _.doc)).filter((_ => !_.deleted)).map((_ => this.getPath(_))).filter((_ => _.startsWith(`${ICXHeader}${ne}/`)));
for (const _ of re) {
const ne = null == (ee = ie.find((ee => ee.key == _))) ? void 0 : ee.file;
if (ne) {
await this.storeCustomizationFiles(ne);
se = se.filter((ee => ee != _));
} else Logger(`scanAllConfigFiles - File not found: ${_}`, LOG_LEVEL_VERBOSE);
}
for (const _ of se) await this.deleteConfigOnDatabase(_);
this.updatePluginList(false).then();
}));
}
async deleteConfigOnDatabase(_, ee = false) {
const ne = (new Date).getTime();
await serialized("file-x-" + _, (async () => {
try {
const ee = await this.localDatabase.getDBEntryMeta(_, void 0, false);
let ie;
if (false === ee) {
Logger(`STORAGE -x> DB:${_}: (config) already deleted (Not found on database)`);
return;
} else {
if (ee.deleted) {
Logger(`STORAGE -x> DB:${_}: (config) already deleted`);
return;
}
ie = {
...ee,
mtime: ne,
size: 0,
children: [],
deleted: true,
type: "newnote"
};
}
await this.localDatabase.putRaw(ie);
await this.updatePluginList(false, _);
Logger(`STORAGE -x> DB:${_}: (config) Done`);
} catch (ee) {
Logger(`STORAGE -x> DB:${_}: (config) Failed`);
Logger(ee, LOG_LEVEL_VERBOSE);
return false;
}
}));
}
async scanInternalFiles() {
return (await this.getFiles(this.app.vault.configDir, 2)).filter((_ => _.startsWith("."))).filter((_ => !_.startsWith(".trash")));
}
async getFiles(_, ee) {
if (-1 == ee) return [];
let ne;
try {
ne = await this.app.vault.adapter.list(_);
} catch (ee) {
Logger(`Could not traverse(ConfigSync):${_}`, LOG_LEVEL_INFO);
Logger(ee, LOG_LEVEL_VERBOSE);
return [];
}
let ie = [ ...ne.files ];
for (const _ of ne.folders) ie = ie.concat(await this.getFiles(_, ee - 1));
return ie;
}
};
function add_css2(_) {
append_styles(_, "svelte-tsbdtg", ".spacer.svelte-tsbdtg{min-width:1px;flex-grow:1}button.svelte-tsbdtg{margin:2px 4px;min-width:3em;max-width:4em}button.svelte-tsbdtg:disabled{border:none;box-shadow:none;background-color:transparent;visibility:collapse}button.svelte-tsbdtg:disabled:hover{border:none;box-shadow:none;background-color:transparent;visibility:collapse}span.message.svelte-tsbdtg{color:var(--text-muted);font-size:var(--font-ui-smaller);padding:0 1em;line-height:var(--line-height-tight)}span.messages.svelte-tsbdtg{display:flex;flex-direction:column;align-items:center}.is-mobile .spacer.svelte-tsbdtg{margin-left:auto}");
}
function get_each_context2(_, ee, ne) {
const ie = _.slice();
ie[30] = ee[ne];
return ie;
}
function create_else_block_3(_) {
let ee, ne, ie, re, se, oe, le;
return {
c() {
ee = element("span");
ne = space();
ie = element("span");
ie.textContent = "All the same or non-existent";
re = space();
se = element("button");
oe = space();
le = element("button");
attr(ee, "class", "spacer svelte-tsbdtg");
attr(ie, "class", "message even svelte-tsbdtg");
se.disabled = true;
attr(se, "class", "svelte-tsbdtg");
le.disabled = true;
attr(le, "class", "svelte-tsbdtg");
},
m(_, ue) {
insert(_, ee, ue);
insert(_, ne, ue);
insert(_, ie, ue);
insert(_, re, ue);
insert(_, se, ue);
insert(_, oe, ue);
insert(_, le, ue);
},
p: noop2,
d(_) {
if (_) {
detach(ee);
detach(ne);
detach(ie);
detach(re);
detach(se);
detach(oe);
detach(le);
}
}
};
}
function create_if_block2(_) {
let ee, ne, ie, re = !_[0] && create_if_block_12(_);
return {
c() {
ee = element("span");
ne = space();
if (re) re.c();
ie = empty();
attr(ee, "class", "spacer svelte-tsbdtg");
},
m(_, se) {
insert(_, ee, se);
insert(_, ne, se);
if (re) re.m(_, se);
insert(_, ie, se);
},
p(_, ee) {
if (!_[0]) if (re) re.p(_, ee); else {
re = create_if_block_12(_);
re.c();
re.m(ie.parentNode, ie);
} else if (re) {
re.d(1);
re = null;
}
},
d(_) {
if (_) {
detach(ee);
detach(ne);
detach(ie);
}
if (re) re.d(_);
}
};
}
function create_if_block_12(_) {
let ee, ne, ie, re, se, oe, le, ue, de, fe, he, pe, ge, me, ye, ve, Se, Ee, Ce = ensure_array_like(_[8]), we = [];
for (let ee = 0; ee < Ce.length; ee += 1) we[ee] = create_each_block2(get_each_context2(_, Ce, ee));
function select_block_type_1(_, ee) {
if (_[6] || _[1] && "" != _[2]) return create_if_block_42; else return create_else_block_2;
}
let Oe = select_block_type_1(_), ke = Oe(_), xe = _[1] && create_if_block_22(_);
return {
c() {
ee = element("span");
ne = element("span");
ie = text(_[3]);
re = space();
se = element("span");
oe = text(_[4]);
le = space();
ue = element("span");
de = text(_[5]);
fe = space();
he = element("select");
pe = element("option");
pe.textContent = "-";
for (let _ = 0; _ < we.length; _ += 1) we[_].c();
me = space();
ke.c();
ye = space();
if (xe) xe.c();
ve = empty();
attr(ne, "class", "message svelte-tsbdtg");
attr(se, "class", "message svelte-tsbdtg");
attr(ue, "class", "message svelte-tsbdtg");
attr(ee, "class", "messages svelte-tsbdtg");
pe.__value = ge = "";
set_input_value(pe, pe.__value);
if (void 0 === _[2]) add_render_callback((() => _[24].call(he)));
},
m(ge, Ce) {
insert(ge, ee, Ce);
append(ee, ne);
append(ne, ie);
append(ee, re);
append(ee, se);
append(se, oe);
append(ee, le);
append(ee, ue);
append(ue, de);
insert(ge, fe, Ce);
insert(ge, he, Ce);
append(he, pe);
for (let _ = 0; _ < we.length; _ += 1) if (we[_]) we[_].m(he, null);
select_option(he, _[2], true);
insert(ge, me, Ce);
ke.m(ge, Ce);
insert(ge, ye, Ce);
if (xe) xe.m(ge, Ce);
insert(ge, ve, Ce);
if (!Se) {
Ee = listen(he, "change", _[24]);
Se = true;
}
},
p(_, ee) {
if (8 & ee[0]) set_data(ie, _[3]);
if (16 & ee[0]) set_data(oe, _[4]);
if (32 & ee[0]) set_data(de, _[5]);
if (256 & ee[0]) {
Ce = ensure_array_like(_[8]);
let ne;
for (ne = 0; ne < Ce.length; ne += 1) {
const ie = get_each_context2(_, Ce, ne);
if (we[ne]) we[ne].p(ie, ee); else {
we[ne] = create_each_block2(ie);
we[ne].c();
we[ne].m(he, null);
}
}
for (;ne < we.length; ne += 1) we[ne].d(1);
we.length = Ce.length;
}
if (260 & ee[0]) select_option(he, _[2]);
if (Oe === (Oe = select_block_type_1(_)) && ke) ke.p(_, ee); else {
ke.d(1);
ke = Oe(_);
if (ke) {
ke.c();
ke.m(ye.parentNode, ye);
}
}
if (_[1]) if (xe) xe.p(_, ee); else {
xe = create_if_block_22(_);
xe.c();
xe.m(ve.parentNode, ve);
} else if (xe) {
xe.d(1);
xe = null;
}
},
d(_) {
if (_) {
detach(ee);
detach(fe);
detach(he);
detach(me);
detach(ye);
detach(ve);
}
destroy_each(we, _);
ke.d(_);
if (xe) xe.d(_);
Se = false;
Ee();
}
};
}
function create_each_block2(_) {
let ee, ne, ie, re = _[30] + "";
return {
c() {
ee = element("option");
ne = text(re);
ee.__value = ie = _[30];
set_input_value(ee, ee.__value);
},
m(_, ie) {
insert(_, ee, ie);
append(ee, ne);
},
p(_, se) {
if (256 & se[0] && re !== (re = _[30] + "")) set_data(ne, re);
if (256 & se[0] && ie !== (ie = _[30])) {
ee.__value = ie;
set_input_value(ee, ee.__value);
}
},
d(_) {
if (_) detach(ee);
}
};
}
function create_else_block_2(_) {
let ee, ne, ie;
return {
c() {
ee = element("button");
ne = space();
ie = element("button");
ee.disabled = true;
attr(ee, "class", "svelte-tsbdtg");
ie.disabled = true;
attr(ie, "class", "svelte-tsbdtg");
},
m(_, re) {
insert(_, ee, re);
insert(_, ne, re);
insert(_, ie, re);
},
p: noop2,
d(_) {
if (_) {
detach(ee);
detach(ne);
detach(ie);
}
}
};
}
function create_if_block_42(_) {
let ee, ne, ie, re;
function select_block_type_2(_, ee) {
if (_[7]) return create_if_block_5; else return create_else_block_12;
}
let se = select_block_type_2(_), oe = se(_);
return {
c() {
oe.c();
ee = space();
ne = element("button");
ne.textContent = "✓";
attr(ne, "class", "svelte-tsbdtg");
},
m(se, le) {
oe.m(se, le);
insert(se, ee, le);
insert(se, ne, le);
if (!ie) {
re = listen(ne, "click", _[9]);
ie = true;
}
},
p(_, ne) {
if (se === (se = select_block_type_2(_)) && oe) oe.p(_, ne); else {
oe.d(1);
oe = se(_);
if (oe) {
oe.c();
oe.m(ee.parentNode, ee);
}
}
},
d(_) {
if (_) {
detach(ee);
detach(ne);
}
oe.d(_);
ie = false;
re();
}
};
}
function create_else_block_12(_) {
let ee;
return {
c() {
ee = element("button");
ee.disabled = true;
attr(ee, "class", "svelte-tsbdtg");
},
m(_, ne) {
insert(_, ee, ne);
},
p: noop2,
d(_) {
if (_) detach(ee);
}
};
}
function create_if_block_5(_) {
let ee, ne, ie;
return {
c() {
ee = element("button");
ee.textContent = "🔍";
attr(ee, "class", "svelte-tsbdtg");
},
m(re, se) {
insert(re, ee, se);
if (!ne) {
ie = listen(ee, "click", _[10]);
ne = true;
}
},
p: noop2,
d(_) {
if (_) detach(ee);
ne = false;
ie();
}
};
}
function create_if_block_22(_) {
let ee;
function select_block_type_3(_, ee) {
if ("" != _[2]) return create_if_block_32; else return create_else_block2;
}
let ne = select_block_type_3(_), ie = ne(_);
return {
c() {
ie.c();
ee = empty();
},
m(_, ne) {
ie.m(_, ne);
insert(_, ee, ne);
},
p(_, re) {
if (ne === (ne = select_block_type_3(_)) && ie) ie.p(_, re); else {
ie.d(1);
ie = ne(_);
if (ie) {
ie.c();
ie.m(ee.parentNode, ee);
}
}
},
d(_) {
if (_) detach(ee);
ie.d(_);
}
};
}
function create_else_block2(_) {
let ee, ne, ie;
return {
c() {
ee = element("button");
ee.textContent = "📑";
attr(ee, "class", "svelte-tsbdtg");
},
m(re, se) {
insert(re, ee, se);
if (!ne) {
ie = listen(ee, "click", _[12]);
ne = true;
}
},
p: noop2,
d(_) {
if (_) detach(ee);
ne = false;
ie();
}
};
}
function create_if_block_32(_) {
let ee, ne, ie;
return {
c() {
ee = element("button");
ee.textContent = "🗑️";
attr(ee, "class", "svelte-tsbdtg");
},
m(re, se) {
insert(re, ee, se);
if (!ne) {
ie = listen(ee, "click", _[11]);
ne = true;
}
},
p: noop2,
d(_) {
if (_) detach(ee);
ne = false;
ie();
}
};
}
function create_fragment2(_) {
let ee;
function select_block_type(_, ee) {
if (_[8].length > 0) return create_if_block2; else return create_else_block_3;
}
let ne = select_block_type(_), ie = ne(_);
return {
c() {
ie.c();
ee = empty();
},
m(_, ne) {
ie.m(_, ne);
insert(_, ee, ne);
},
p(_, re) {
if (ne === (ne = select_block_type(_)) && ie) ie.p(_, re); else {
ie.d(1);
ie = ne(_);
if (ie) {
ie.c();
ie.m(ee.parentNode, ee);
}
}
},
i: noop2,
o: noop2,
d(_) {
if (_) detach(ee);
ie.d(_);
}
};
}
function instance2(_, ee, ne) {
let {list: ie = []} = ee, {thisTerm: re = ""} = ee, {hideNotApplicable: se = false} = ee, {selectNewest: oe = 0} = ee, {applyAllPluse: le = 0} = ee, {applyData: ue} = ee, {compareData: de} = ee, {deleteData: fe} = ee, {hidden: he} = ee, {plugin: pe} = ee, {isMaintenanceMode: ge = false} = ee;
const me = pe.addOnConfigSync;
let ye = "", ve = "", Se = "", Ee = "", Ce = false, we = false, Oe = 0, ke = 0, xe = [];
async function comparePlugin(_, ee) {
var ne, ie;
let re = "", se = "", oe = false, le = false;
if (!_ && !ee) re = ""; else if (_ && !ee) re = "⚠ Local only"; else if (ee && !_) {
re = "✓ Remote only";
le = true;
} else {
const se = (null !== (ne = null == _ ? void 0 : _.mtime) && void 0 !== ne ? ne : 0) - (null !== (ie = null == ee ? void 0 : ee.mtime) && void 0 !== ie ? ie : 0);
if (se / 1e3 < -10) {
re = "✓ Newer";
le = true;
oe = true;
} else if (se / 1e3 > 10) {
re = "⚠ Older";
le = true;
oe = true;
} else {
re = "⚖️ Same old";
le = false;
oe = true;
}
}
const ue = (null == _ ? void 0 : _.version) || "0.0.0", de = (null == ee ? void 0 : ee.version) || "0.0.0";
if ((null == _ ? void 0 : _.version) || (null == ee ? void 0 : ee.version)) {
const _ = versionNumberString2Number(ue), ee = versionNumberString2Number(de);
if (_ == ee) se = "⚖️ Same ver."; else if (_ > ee) se = `⚠ Lower ${ue} > ${de}`; else if (_ < ee) se = `✓ Higher ${ue} < ${de}`;
}
if (oe) {
const {canApply: ne, equivalency: ie, canCompare: oe} = await async function checkEquivalency(_, ee) {
let ne = "", ie = false, re = false;
const se = [ ...new Set([ ..._.files.map((_ => _.filename)), ...ee.files.map((_ => _.filename)) ]) ].map((ne => {
const ie = _.files.find((_ => _.filename == ne)), re = ee.files.find((_ => _.filename == ne));
if (!ie && !re) return 0; else if (ie && !re) return 2; else if (!ie && re) return 8; else if (getDocData(ie.data) == getDocData(re.data)) return 4; else return 16;
})).reduce(((_, ee) => _ | ee), 0);
if (4 == se) {
ne = "⚖️ Same";
ie = false;
} else if (se <= 4) {
ne = "Same or local only";
ie = false;
} else if (16 == se) {
ie = true;
re = true;
ne = "≠ Different";
} else {
ie = true;
re = true;
ne = "≠ Different";
}
return {
equivalency: ne,
canApply: ie,
canCompare: re
};
}(_, ee);
return {
canApply: ne,
freshness: re,
equivalency: ie,
version: se,
canCompare: oe
};
}
return {
canApply: le,
freshness: re,
equivalency: "",
version: se,
canCompare: false
};
}
async function applySelected() {
const _ = ie.find((_ => _.term == re)), ee = ie.find((_ => _.term == ye));
if (ee && await ue(ee)) me.updatePluginList(true, null == _ ? void 0 : _.documentPath);
}
_.$$set = _ => {
if ("list" in _) ne(13, ie = _.list);
if ("thisTerm" in _) ne(14, re = _.thisTerm);
if ("hideNotApplicable" in _) ne(15, se = _.hideNotApplicable);
if ("selectNewest" in _) ne(16, oe = _.selectNewest);
if ("applyAllPluse" in _) ne(17, le = _.applyAllPluse);
if ("applyData" in _) ne(18, ue = _.applyData);
if ("compareData" in _) ne(19, de = _.compareData);
if ("deleteData" in _) ne(20, fe = _.deleteData);
if ("hidden" in _) ne(0, he = _.hidden);
if ("plugin" in _) ne(21, pe = _.plugin);
if ("isMaintenanceMode" in _) ne(1, ge = _.isMaintenanceMode);
};
_.$$.update = () => {
if (4268034 & _.$$.dirty[0]) {
const _ = oe != Oe;
ne(22, Oe = oe);
(async function updateTerms(_, ee, ie) {
const oe = _.find((_ => _.term == re));
ne(2, ye = "");
if (ie) ne(8, xe = [ ...new Set(_.map((_ => _.term))) ]); else if (se) {
const ee = [], ie = [ ...new Set(_.map((_ => _.term))) ];
for (const ne of ie) {
const ie = _.find((_ => _.term == ne));
if ((await comparePlugin(oe, ie)).canApply) ee.push(ne);
}
ne(8, xe = [ ...ee ]);
} else ne(8, xe = [ ...new Set(_.map((_ => _.term))) ].filter((_ => _ != re)));
let le = oe;
if (ee) {
for (const ee of xe) {
const ne = _.find((_ => _.term == ee));
if (ne && ne.mtime && ((null == le ? void 0 : le.mtime) || 0) < ne.mtime) le = ne;
}
if (le && le.term != re) ne(2, ye = le.term);
}
})(ie, _, ge);
}
if (8519685 & _.$$.dirty[0]) {
const _ = le != ke;
ne(23, ke = le);
if (_ && ye) if (!he) applySelected();
}
if (24580 & _.$$.dirty[0]) {
ne(3, ve = "");
ne(4, Se = "");
ne(5, Ee = "");
ne(6, Ce = false);
if ("" == ye) ; else if (ye == re) {
ne(3, ve = "This device");
ne(6, Ce = false);
} else (async function performCompare(_, ee) {
var ie, re, se;
const oe = await comparePlugin(_, ee);
ne(6, Ce = oe.canApply);
ne(3, ve = oe.freshness);
ne(4, Se = oe.equivalency);
ne(5, Ee = oe.version);
ne(7, we = oe.canCompare);
if (1 != (null == _ ? void 0 : _.files.length) || !(null === (se = null === (re = null === (ie = null == _ ? void 0 : _.files) || void 0 === ie ? void 0 : ie.first()) || void 0 === re ? void 0 : re.filename) || void 0 === se ? void 0 : se.endsWith(".json"))) ne(7, we = false);
})(ie.find((_ => _.term == re)), ie.find((_ => _.term == ye)));
}
};
return [ he, ge, ye, ve, Se, Ee, Ce, we, xe, applySelected, async function compareSelected() {
const _ = ie.find((_ => _.term == re)), ee = ie.find((_ => _.term == ye));
if (_ && ee && await de(_, ee)) me.updatePluginList(true, _.documentPath);
}, async function deleteSelected() {
const _ = ie.find((_ => _.term == ye));
if (_ && await fe(_)) me.reloadPluginList(true);
}, async function duplicateItem() {
const _ = ie.find((_ => _.term == re)), ee = await askString(pe.app, "Duplicate", "device name", "");
if (ee) {
if (ee.contains("/")) {
Logger('We can not use "/" to the device name', LOG_LEVEL_NOTICE);
return;
}
const ne = `${pe.app.vault.configDir}/${_.files[0].filename}`;
await me.storeCustomizationFiles(ne, ee);
await me.updatePluginList(false, me.filenameToUnifiedKey(ne, ee));
}
}, ie, re, se, oe, le, ue, de, fe, pe, Oe, ke, function select_change_handler() {
ye = select_value(this);
ne(2, ye);
ne(8, xe);
} ];
}
var PluginCombo = class extends SvelteComponent {
constructor(_) {
super();
init2(this, _, instance2, create_fragment2, safe_not_equal, {
list: 13,
thisTerm: 14,
hideNotApplicable: 15,
selectNewest: 16,
applyAllPluse: 17,
applyData: 18,
compareData: 19,
deleteData: 20,
hidden: 0,
plugin: 21,
isMaintenanceMode: 1
}, add_css2, [ -1, -1 ]);
}
}, PluginCombo_default = PluginCombo, import_obsidian3 = require("obsidian");
function add_css3(_) {
append_styles(_, "svelte-1mend9p", "h3.svelte-1mend9p.svelte-1mend9p{position:sticky;top:0;background-color:var(--modal-background)}.labelrow.svelte-1mend9p.svelte-1mend9p{margin-left:0.4em;display:flex;justify-content:flex-start;align-items:center;border-top:1px solid var(--background-modifier-border);padding:4px;flex-wrap:wrap}.filerow.svelte-1mend9p.svelte-1mend9p{margin-left:1.25em;display:flex;justify-content:flex-start;align-items:center;padding-right:4px;flex-wrap:wrap}.filerow.hideeven.svelte-1mend9p.svelte-1mend9p:has(.even),.labelrow.hideeven.svelte-1mend9p.svelte-1mend9p:has(.even){display:none}.noterow.svelte-1mend9p.svelte-1mend9p{min-height:2em;display:flex}button.status.svelte-1mend9p.svelte-1mend9p{flex-grow:0;margin:2px 4px;min-width:3em;max-width:4em}.statusnote.svelte-1mend9p.svelte-1mend9p{display:flex;justify-content:flex-end;padding-right:var(--size-4-12);align-items:center;min-width:10em;flex-grow:1}.title.svelte-1mend9p.svelte-1mend9p{color:var(--text-normal);font-size:var(--font-ui-medium);line-height:var(--line-height-tight);margin-right:auto}.filetitle.svelte-1mend9p.svelte-1mend9p{color:var(--text-normal);font-size:var(--font-ui-medium);line-height:var(--line-height-tight);margin-right:auto}.buttons.svelte-1mend9p.svelte-1mend9p{display:flex;flex-direction:row;justify-content:flex-end;margin-top:8px;flex-wrap:wrap}.buttons.svelte-1mend9p>button.svelte-1mend9p{margin-left:4px;width:auto}label.svelte-1mend9p.svelte-1mend9p{display:flex;justify-content:center;align-items:center}label.svelte-1mend9p>span.svelte-1mend9p{margin-right:0.25em}.is-mobile .title.svelte-1mend9p.svelte-1mend9p,.is-mobile .filetitle.svelte-1mend9p.svelte-1mend9p{width:100%}.center.svelte-1mend9p.svelte-1mend9p{display:flex;justify-content:center;align-items:center;min-height:3em}.maintenancerow.svelte-1mend9p.svelte-1mend9p{display:flex;justify-content:flex-end;align-items:center}.maintenancerow.svelte-1mend9p label.svelte-1mend9p{margin-right:0.5em;margin-left:0.5em}");
}
function get_each_context3(_, ee, ne) {
const ie = _.slice();
ie[53] = ee[ne];
return ie;
}
function get_each_context_12(_, ee, ne) {
var ie, re, se;
const oe = _.slice();
oe[56] = ee[ne][0];
oe[57] = ee[ne][1];
const le = `${PREFIX_PLUGIN_ALL}/${oe[56]}`;
oe[58] = le;
const ue = null != (ie = oe[5].get(oe[58])) ? ie : MODE_SELECTIVE;
oe[59] = ue;
const de = `${PREFIX_PLUGIN_MAIN}/${oe[56]}`;
oe[60] = de;
const fe = null != (re = oe[5].get(oe[60])) ? re : MODE_SELECTIVE;
oe[61] = fe;
const he = `${PREFIX_PLUGIN_DATA}/${oe[56]}`;
oe[62] = he;
const pe = null != (se = oe[5].get(oe[62])) ? se : MODE_SELECTIVE;
oe[63] = pe;
return oe;
}
function get_each_context_2(_, ee, ne) {
const ie = _.slice();
ie[66] = ee[ne][0];
ie[67] = ee[ne][1];
return ie;
}
function get_each_context_3(_, ee, ne) {
var ie;
const re = _.slice();
re[56] = ee[ne];
const se = `${re[66]}/${re[56]}`;
re[70] = se;
const oe = null != (ie = re[5].get(re[70])) ? ie : MODE_SELECTIVE;
re[71] = oe;
return re;
}
function create_if_block_8(_) {
let ee, ne, ie;
return {
c() {
ee = element("button");
ee.textContent = "Reload";
attr(ee, "class", "svelte-1mend9p");
},
m(re, se) {
insert(re, ee, se);
if (!ne) {
ie = listen(ee, "click", _[28]);
ne = true;
}
},
p: noop2,
d(_) {
if (_) detach(ee);
ne = false;
ie();
}
};
}
function create_if_block_7(_) {
let ee;
return {
c() {
ee = element("div");
ee.innerHTML = "Updating list...";
},
m(_, ne) {
insert(_, ee, ne);
},
d(_) {
if (_) detach(ee);
}
};
}
function create_else_block3(_) {
let ee, ne, ie, re, se, oe = ensure_array_like(Object.entries(_[11]).filter(_[31])), le = [];
for (let ee = 0; ee < oe.length; ee += 1) le[ee] = create_each_block_2(get_each_context_2(_, oe, ee));
const out = _ => transition_out(le[_], 1, 1, (() => {
le[_] = null;
}));
let ue = ensure_array_like(groupBy(filterList(_[0], [ "PLUGIN_MAIN", "PLUGIN_DATA", "PLUGIN_ETC" ]), "name")), de = [];
for (let ee = 0; ee < ue.length; ee += 1) de[ee] = create_each_block_12(get_each_context_12(_, ue, ee));
const out_1 = _ => transition_out(de[_], 1, 1, (() => {
de[_] = null;
}));
return {
c() {
for (let _ = 0; _ < le.length; _ += 1) le[_].c();
ee = space();
ne = element("div");
ie = element("h3");
ie.textContent = "Plugins";
re = space();
for (let _ = 0; _ < de.length; _ += 1) de[_].c();
attr(ie, "class", "svelte-1mend9p");
},
m(_, oe) {
for (let ee = 0; ee < le.length; ee += 1) if (le[ee]) le[ee].m(_, oe);
insert(_, ee, oe);
insert(_, ne, oe);
append(ne, ie);
append(ne, re);
for (let _ = 0; _ < de.length; _ += 1) if (de[_]) de[_].m(ne, null);
se = true;
},
p(_, ie) {
if (461157 & ie[0]) {
oe = ensure_array_like(Object.entries(_[11]).filter(_[31]));
let ne;
for (ne = 0; ne < oe.length; ne += 1) {
const re = get_each_context_2(_, oe, ne);
if (le[ne]) {
le[ne].p(re, ie);
transition_in(le[ne], 1);
} else {
le[ne] = create_each_block_2(re);
le[ne].c();
transition_in(le[ne], 1);
le[ne].m(ee.parentNode, ee);
}
}
group_outros();
for (ne = oe.length; ne < le.length; ne += 1) out(ne);
check_outros();
}
if (459045 & ie[0]) {
ue = ensure_array_like(groupBy(filterList(_[0], [ "PLUGIN_MAIN", "PLUGIN_DATA", "PLUGIN_ETC" ]), "name"));
let ee;
for (ee = 0; ee < ue.length; ee += 1) {
const re = get_each_context_12(_, ue, ee);
if (de[ee]) {
de[ee].p(re, ie);
transition_in(de[ee], 1);
} else {
de[ee] = create_each_block_12(re);
de[ee].c();
transition_in(de[ee], 1);
de[ee].m(ne, null);
}
}
group_outros();
for (ee = ue.length; ee < de.length; ee += 1) out_1(ee);
check_outros();
}
},
i(_) {
if (!se) {
for (let _ = 0; _ < oe.length; _ += 1) transition_in(le[_]);
for (let _ = 0; _ < ue.length; _ += 1) transition_in(de[_]);
se = true;
}
},
o(_) {
le = le.filter(Boolean);
for (let _ = 0; _ < le.length; _ += 1) transition_out(le[_]);
de = de.filter(Boolean);
for (let _ = 0; _ < de.length; _ += 1) transition_out(de[_]);
se = false;
},
d(_) {
if (_) {
detach(ee);
detach(ne);
}
destroy_each(le, _);
destroy_each(de, _);
}
};
}
function create_if_block_13(_) {
let ee;
return {
c() {
ee = element("div");
ee.textContent = "No Items.";
attr(ee, "class", "center svelte-1mend9p");
},
m(_, ne) {
insert(_, ee, ne);
},
p: noop2,
i: noop2,
o: noop2,
d(_) {
if (_) detach(ee);
}
};
}
function create_else_block_4(_) {
let ee, ne, ie = _[17][_[71]] + "";
return {
c() {
ee = element("div");
ne = text(ie);
attr(ee, "class", "statusnote svelte-1mend9p");
},
m(_, ie) {
insert(_, ee, ie);
append(ee, ne);
},
p(_, ee) {
if (96 & ee[0] && ie !== (ie = _[17][_[71]] + "")) set_data(ne, ie);
},
i: noop2,
o: noop2,
d(_) {
if (_) detach(ee);
}
};
}
function create_if_block_6(_) {
let ee, ne;
function func_12(...ee) {
return _[33](_[66], _[56], ...ee);
}
const ie = [ _[8], {
list: _[0].filter(func_12)
}, {
hidden: false
} ];
let re = {};
for (let _ = 0; _ < ie.length; _ += 1) re = assign(re, ie[_]);
ee = new PluginCombo_default({
props: re
});
return {
c() {
create_component(ee.$$.fragment);
},
m(_, ie) {
mount_component(ee, _, ie);
ne = true;
},
p(ne, re) {
_ = ne;
const se = 2369 & re[0] ? get_spread_update(ie, [ 256 & re[0] && get_spread_object(_[8]), 2113 & re[0] && {
list: _[0].filter(func_12)
}, ie[2] ]) : {};
ee.$set(se);
},
i(_) {
if (!ne) {
transition_in(ee.$$.fragment, _);
ne = true;
}
},
o(_) {
transition_out(ee.$$.fragment, _);
ne = false;
},
d(_) {
destroy_component(ee, _);
}
};
}
function create_each_block_3(_) {
let ee, ne, ie, re, se, oe, le, ue, de, fe, he, pe, ge, me, ye = _[18](_[71]) + "", ve = _[56] + "";
function click_handler_6(...ee) {
return _[32](_[66], _[56], _[70], ...ee);
}
const Se = [ create_if_block_6, create_else_block_4 ], Ee = [];
function select_block_type_1(_, ee) {
if (_[71] == MODE_SELECTIVE) return 0; else return 1;
}
de = select_block_type_1(_);
fe = Ee[de] = Se[de](_);
return {
c() {
ee = element("div");
ne = element("div");
ie = element("button");
re = text(ye);
se = space();
oe = element("span");
le = text(ve);
ue = space();
fe.c();
attr(ie, "class", "status svelte-1mend9p");
attr(oe, "class", "name");
attr(ne, "class", "title svelte-1mend9p");
attr(ee, "class", he = "labelrow " + (_[2] ? "hideeven" : "") + " svelte-1mend9p");
},
m(_, fe) {
insert(_, ee, fe);
append(ee, ne);
append(ne, ie);
append(ie, re);
append(ne, se);
append(ne, oe);
append(oe, le);
append(ee, ue);
Ee[de].m(ee, null);
pe = true;
if (!ge) {
me = listen(ie, "click", click_handler_6);
ge = true;
}
},
p(ne, ie) {
_ = ne;
if ((!pe || 96 & ie[0]) && ye !== (ye = _[18](_[71]) + "")) set_data(re, ye);
if ((!pe || 64 & ie[0]) && ve !== (ve = _[56] + "")) set_data(le, ve);
let se = de;
de = select_block_type_1(_);
if (de === se) Ee[de].p(_, ie); else {
group_outros();
transition_out(Ee[se], 1, 1, (() => {
Ee[se] = null;
}));
check_outros();
fe = Ee[de];
if (!fe) {
fe = Ee[de] = Se[de](_);
fe.c();
} else fe.p(_, ie);
transition_in(fe, 1);
fe.m(ee, null);
}
if (!pe || 4 & ie[0] && he !== (he = "labelrow " + (_[2] ? "hideeven" : "") + " svelte-1mend9p")) attr(ee, "class", he);
},
i(_) {
if (!pe) {
transition_in(fe);
pe = true;
}
},
o(_) {
transition_out(fe);
pe = false;
},
d(_) {
if (_) detach(ee);
Ee[de].d();
ge = false;
me();
}
};
}
function create_each_block_2(_) {
let ee, ne, ie, re, se, oe = _[67] + "", le = ensure_array_like(_[6][_[66]]), ue = [];
for (let ee = 0; ee < le.length; ee += 1) ue[ee] = create_each_block_3(get_each_context_3(_, le, ee));
const out = _ => transition_out(ue[_], 1, 1, (() => {
ue[_] = null;
}));
return {
c() {
ee = element("div");
ne = element("h3");
ie = text(oe);
re = space();
for (let _ = 0; _ < ue.length; _ += 1) ue[_].c();
attr(ne, "class", "svelte-1mend9p");
},
m(_, oe) {
insert(_, ee, oe);
append(ee, ne);
append(ne, ie);
append(ee, re);
for (let _ = 0; _ < ue.length; _ += 1) if (ue[_]) ue[_].m(ee, null);
se = true;
},
p(_, ne) {
if ((!se || 64 & ne[0]) && oe !== (oe = _[67] + "")) set_data(ie, oe);
if (461157 & ne[0]) {
le = ensure_array_like(_[6][_[66]]);
let ie;
for (ie = 0; ie < le.length; ie += 1) {
const re = get_each_context_3(_, le, ie);
if (ue[ie]) {
ue[ie].p(re, ne);
transition_in(ue[ie], 1);
} else {
ue[ie] = create_each_block_3(re);
ue[ie].c();
transition_in(ue[ie], 1);
ue[ie].m(ee, null);
}
}
group_outros();
for (ie = le.length; ie < ue.length; ie += 1) out(ie);
check_outros();
}
},
i(_) {
if (!se) {
for (let _ = 0; _ < le.length; _ += 1) transition_in(ue[_]);
se = true;
}
},
o(_) {
ue = ue.filter(Boolean);
for (let _ = 0; _ < ue.length; _ += 1) transition_out(ue[_]);
se = false;
},
d(_) {
if (_) detach(ee);
destroy_each(ue, _);
}
};
}
function create_if_block_52(_) {
let ee, ne;
const ie = [ _[8], {
list: _[57]
}, {
hidden: true
} ];
let re = {};
for (let _ = 0; _ < ie.length; _ += 1) re = assign(re, ie[_]);
ee = new PluginCombo_default({
props: re
});
return {
c() {
create_component(ee.$$.fragment);
},
m(_, ie) {
mount_component(ee, _, ie);
ne = true;
},
p(_, ne) {
const re = 257 & ne[0] ? get_spread_update(ie, [ 256 & ne[0] && get_spread_object(_[8]), 1 & ne[0] && {
list: _[57]
}, ie[2] ]) : {};
ee.$set(re);
},
i(_) {
if (!ne) {
transition_in(ee.$$.fragment, _);
ne = true;
}
},
o(_) {
transition_out(ee.$$.fragment, _);
ne = false;
},
d(_) {
destroy_component(ee, _);
}
};
}
function create_else_block_32(_) {
let ee, ne, ie, re, se = _[17][_[59]] + "";
return {
c() {
ee = element("div");
ne = element("div");
ie = text(se);
re = space();
attr(ne, "class", "statusnote svelte-1mend9p");
attr(ee, "class", "noterow svelte-1mend9p");
},
m(_, se) {
insert(_, ee, se);
append(ee, ne);
append(ne, ie);
append(ee, re);
},
p(_, ee) {
if (33 & ee[0] && se !== (se = _[17][_[59]] + "")) set_data(ie, se);
},
i: noop2,
o: noop2,
d(_) {
if (_) detach(ee);
}
};
}
function create_if_block_23(_) {
let ee, ne, ie, re, se, oe, le, ue, de, fe, he, pe, ge, me, ye, ve, Se, Ee, Ce, we, Oe, ke, xe, Ae, Le, Re = _[18](_[61]) + "", Te = _[18](_[63]) + "";
function click_handler_8(...ee) {
return _[35](_[56], _[60], ...ee);
}
const Pe = [ create_if_block_43, create_else_block_22 ], Ie = [];
function select_block_type_3(_, ee) {
if (_[61] == MODE_SELECTIVE) return 0; else return 1;
}
ue = select_block_type_3(_);
de = Ie[ue] = Pe[ue](_);
function click_handler_9(...ee) {
return _[36](_[56], _[62], ...ee);
}
const De = [ create_if_block_33, create_else_block_13 ], Be = [];
function select_block_type_4(_, ee) {
if (_[63] == MODE_SELECTIVE) return 0; else return 1;
}
Ce = select_block_type_4(_);
we = Be[Ce] = De[Ce](_);
return {
c() {
ee = element("div");
ne = element("div");
ie = element("button");
re = text(Re);
se = space();
oe = element("span");
oe.textContent = "MAIN";
le = space();
de.c();
he = space();
pe = element("div");
ge = element("div");
me = element("button");
ye = text(Te);
ve = space();
Se = element("span");
Se.textContent = "DATA";
Ee = space();
we.c();
Oe = space();
attr(ie, "class", "status svelte-1mend9p");
attr(oe, "class", "name");
attr(ne, "class", "filetitle svelte-1mend9p");
attr(ee, "class", fe = "filerow " + (_[2] ? "hideeven" : "") + " svelte-1mend9p");
attr(me, "class", "status svelte-1mend9p");
attr(Se, "class", "name");
attr(ge, "class", "filetitle svelte-1mend9p");
attr(pe, "class", ke = "filerow " + (_[2] ? "hideeven" : "") + " svelte-1mend9p");
},
m(_, de) {
insert(_, ee, de);
append(ee, ne);
append(ne, ie);
append(ie, re);
append(ne, se);
append(ne, oe);
append(ee, le);
Ie[ue].m(ee, null);
insert(_, he, de);
insert(_, pe, de);
append(pe, ge);
append(ge, me);
append(me, ye);
append(ge, ve);
append(ge, Se);
append(pe, Ee);
Be[Ce].m(pe, null);
append(pe, Oe);
xe = true;
if (!Ae) {
Le = [ listen(ie, "click", click_handler_8), listen(me, "click", click_handler_9) ];
Ae = true;
}
},
p(ne, ie) {
_ = ne;
if ((!xe || 33 & ie[0]) && Re !== (Re = _[18](_[61]) + "")) set_data(re, Re);
let se = ue;
ue = select_block_type_3(_);
if (ue === se) Ie[ue].p(_, ie); else {
group_outros();
transition_out(Ie[se], 1, 1, (() => {
Ie[se] = null;
}));
check_outros();
de = Ie[ue];
if (!de) {
de = Ie[ue] = Pe[ue](_);
de.c();
} else de.p(_, ie);
transition_in(de, 1);
de.m(ee, null);
}
if (!xe || 4 & ie[0] && fe !== (fe = "filerow " + (_[2] ? "hideeven" : "") + " svelte-1mend9p")) attr(ee, "class", fe);
if ((!xe || 33 & ie[0]) && Te !== (Te = _[18](_[63]) + "")) set_data(ye, Te);
let oe = Ce;
Ce = select_block_type_4(_);
if (Ce === oe) Be[Ce].p(_, ie); else {
group_outros();
transition_out(Be[oe], 1, 1, (() => {
Be[oe] = null;
}));
check_outros();
we = Be[Ce];
if (!we) {
we = Be[Ce] = De[Ce](_);
we.c();
} else we.p(_, ie);
transition_in(we, 1);
we.m(pe, Oe);
}
if (!xe || 4 & ie[0] && ke !== (ke = "filerow " + (_[2] ? "hideeven" : "") + " svelte-1mend9p")) attr(pe, "class", ke);
},
i(_) {
if (!xe) {
transition_in(de);
transition_in(we);
xe = true;
}
},
o(_) {
transition_out(de);
transition_out(we);
xe = false;
},
d(_) {
if (_) {
detach(ee);
detach(he);
detach(pe);
}
Ie[ue].d();
Be[Ce].d();
Ae = false;
run_all(Le);
}
};
}
function create_else_block_22(_) {
let ee, ne, ie = _[17][_[61]] + "";
return {
c() {
ee = element("div");
ne = text(ie);
attr(ee, "class", "statusnote svelte-1mend9p");
},
m(_, ie) {
insert(_, ee, ie);
append(ee, ne);
},
p(_, ee) {
if (33 & ee[0] && ie !== (ie = _[17][_[61]] + "")) set_data(ne, ie);
},
i: noop2,
o: noop2,
d(_) {
if (_) detach(ee);
}
};
}
function create_if_block_43(_) {
let ee, ne;
const ie = [ _[8], {
list: filterList(_[57], [ "PLUGIN_MAIN" ])
}, {
hidden: false
} ];
let re = {};
for (let _ = 0; _ < ie.length; _ += 1) re = assign(re, ie[_]);
ee = new PluginCombo_default({
props: re
});
return {
c() {
create_component(ee.$$.fragment);
},
m(_, ie) {
mount_component(ee, _, ie);
ne = true;
},
p(_, ne) {
const re = 257 & ne[0] ? get_spread_update(ie, [ 256 & ne[0] && get_spread_object(_[8]), 1 & ne[0] && {
list: filterList(_[57], [ "PLUGIN_MAIN" ])
}, ie[2] ]) : {};
ee.$set(re);
},
i(_) {
if (!ne) {
transition_in(ee.$$.fragment, _);
ne = true;
}
},
o(_) {
transition_out(ee.$$.fragment, _);
ne = false;
},
d(_) {
destroy_component(ee, _);
}
};
}
function create_else_block_13(_) {
let ee, ne, ie = _[17][_[63]] + "";
return {
c() {
ee = element("div");
ne = text(ie);
attr(ee, "class", "statusnote svelte-1mend9p");
},
m(_, ie) {
insert(_, ee, ie);
append(ee, ne);
},
p(_, ee) {
if (33 & ee[0] && ie !== (ie = _[17][_[63]] + "")) set_data(ne, ie);
},
i: noop2,
o: noop2,
d(_) {
if (_) detach(ee);
}
};
}
function create_if_block_33(_) {
let ee, ne;
const ie = [ _[8], {
list: filterList(_[57], [ "PLUGIN_DATA" ])
}, {
hidden: false
} ];
let re = {};
for (let _ = 0; _ < ie.length; _ += 1) re = assign(re, ie[_]);
ee = new PluginCombo_default({
props: re
});
return {
c() {
create_component(ee.$$.fragment);
},
m(_, ie) {
mount_component(ee, _, ie);
ne = true;
},
p(_, ne) {
const re = 257 & ne[0] ? get_spread_update(ie, [ 256 & ne[0] && get_spread_object(_[8]), 1 & ne[0] && {
list: filterList(_[57], [ "PLUGIN_DATA" ])
}, ie[2] ]) : {};
ee.$set(re);
},
i(_) {
if (!ne) {
transition_in(ee.$$.fragment, _);
ne = true;
}
},
o(_) {
transition_out(ee.$$.fragment, _);
ne = false;
},
d(_) {
destroy_component(ee, _);
}
};
}
function create_each_block_12(_) {
let ee, ne, ie, re, se, oe, le, ue, de, fe, he, pe, ge, me, ye, ve, Se = _[18](_[59]) + "", Ee = _[56] + "";
function click_handler_7(...ee) {
return _[34](_[56], _[58], ...ee);
}
let Ce = _[59] == MODE_SELECTIVE && create_if_block_52(_);
const we = [ create_if_block_23, create_else_block_32 ], Oe = [];
function select_block_type_2(_, ee) {
if (_[59] == MODE_SELECTIVE) return 0; else return 1;
}
he = select_block_type_2(_);
pe = Oe[he] = we[he](_);
return {
c() {
ee = element("div");
ne = element("div");
ie = element("button");
re = text(Se);
se = space();
oe = element("span");
le = text(Ee);
ue = space();
if (Ce) Ce.c();
fe = space();
pe.c();
ge = empty();
attr(ie, "class", "status svelte-1mend9p");
attr(oe, "class", "name");
attr(ne, "class", "title svelte-1mend9p");
attr(ee, "class", de = "labelrow " + (_[2] ? "hideeven" : "") + " svelte-1mend9p");
},
m(_, de) {
insert(_, ee, de);
append(ee, ne);
append(ne, ie);
append(ie, re);
append(ne, se);
append(ne, oe);
append(oe, le);
append(ee, ue);
if (Ce) Ce.m(ee, null);
insert(_, fe, de);
Oe[he].m(_, de);
insert(_, ge, de);
me = true;
if (!ye) {
ve = listen(ie, "click", click_handler_7);
ye = true;
}
},
p(ne, ie) {
_ = ne;
if ((!me || 33 & ie[0]) && Se !== (Se = _[18](_[59]) + "")) set_data(re, Se);
if ((!me || 1 & ie[0]) && Ee !== (Ee = _[56] + "")) set_data(le, Ee);
if (_[59] == MODE_SELECTIVE) if (Ce) {
Ce.p(_, ie);
if (33 & ie[0]) transition_in(Ce, 1);
} else {
Ce = create_if_block_52(_);
Ce.c();
transition_in(Ce, 1);
Ce.m(ee, null);
} else if (Ce) {
group_outros();
transition_out(Ce, 1, 1, (() => {
Ce = null;
}));
check_outros();
}
if (!me || 4 & ie[0] && de !== (de = "labelrow " + (_[2] ? "hideeven" : "") + " svelte-1mend9p")) attr(ee, "class", de);
let se = he;
he = select_block_type_2(_);
if (he === se) Oe[he].p(_, ie); else {
group_outros();
transition_out(Oe[se], 1, 1, (() => {
Oe[se] = null;
}));
check_outros();
pe = Oe[he];
if (!pe) {
pe = Oe[he] = we[he](_);
pe.c();
} else pe.p(_, ie);
transition_in(pe, 1);
pe.m(ge.parentNode, ge);
}
},
i(_) {
if (!me) {
transition_in(Ce);
transition_in(pe);
me = true;
}
},
o(_) {
transition_out(Ce);
transition_out(pe);
me = false;
},
d(_) {
if (_) {
detach(ee);
detach(fe);
detach(ge);
}
if (Ce) Ce.d();
Oe[he].d(_);
ye = false;
ve();
}
};
}
function create_if_block3(_) {
let ee, ne, ie, re, se, oe, le, ue, de, fe, he, pe, ge = ensure_array_like(_[4]), me = [];
for (let ee = 0; ee < ge.length; ee += 1) me[ee] = create_each_block3(get_each_context3(_, ge, ee));
return {
c() {
ee = element("div");
ne = element("div");
ie = element("h3");
ie.textContent = "Maintenance Commands";
re = space();
se = element("div");
oe = element("label");
oe.textContent = "Delete All of";
le = space();
ue = element("select");
for (let _ = 0; _ < me.length; _ += 1) me[_].c();
de = space();
fe = element("button");
fe.textContent = "🗑️";
attr(ie, "class", "svelte-1mend9p");
attr(oe, "for", "");
attr(oe, "class", "svelte-1mend9p");
if (void 0 === _[7]) add_render_callback((() => _[37].call(ue)));
attr(fe, "class", "status svelte-1mend9p");
attr(se, "class", "maintenancerow svelte-1mend9p");
attr(ee, "class", "list");
},
m(ge, ye) {
insert(ge, ee, ye);
append(ee, ne);
append(ne, ie);
append(ne, re);
append(ne, se);
append(se, oe);
append(se, le);
append(se, ue);
for (let _ = 0; _ < me.length; _ += 1) if (me[_]) me[_].m(ue, null);
select_option(ue, _[7], true);
append(se, de);
append(se, fe);
if (!he) {
pe = [ listen(ue, "change", _[37]), listen(fe, "click", _[38]) ];
he = true;
}
},
p(_, ee) {
if (16 & ee[0]) {
ge = ensure_array_like(_[4]);
let ne;
for (ne = 0; ne < ge.length; ne += 1) {
const ie = get_each_context3(_, ge, ne);
if (me[ne]) me[ne].p(ie, ee); else {
me[ne] = create_each_block3(ie);
me[ne].c();
me[ne].m(ue, null);
}
}
for (;ne < me.length; ne += 1) me[ne].d(1);
me.length = ge.length;
}
if (144 & ee[0]) select_option(ue, _[7]);
},
d(_) {
if (_) detach(ee);
destroy_each(me, _);
he = false;
run_all(pe);
}
};
}
function create_each_block3(_) {
let ee, ne, ie, re = _[53] + "";
return {
c() {
ee = element("option");
ne = text(re);
ee.__value = ie = _[53];
set_input_value(ee, ee.__value);
},
m(_, ie) {
insert(_, ee, ie);
append(ee, ne);
},
p(_, se) {
if (16 & se[0] && re !== (re = _[53] + "")) set_data(ne, re);
if (16 & se[0] && ie !== (ie = _[53])) {
ee.__value = ie;
set_input_value(ee, ee.__value);
}
},
d(_) {
if (_) detach(ee);
}
};
}
function create_fragment3(_) {
let ee, ne, ie, re, se, oe, le, ue, de, fe, he, pe, ge, me, ye, ve, Se, Ee, Ce, we, Oe, ke, xe, Ae, Le, Re, Te, Pe, Ie, De, Be, Ne, Me, Fe = _[1] && create_if_block_8(_), je = _[3] && create_if_block_7(_);
const $e = [ create_if_block_13, create_else_block3 ], Ge = [];
function select_block_type(_, ee) {
if (0 == _[0].length) return 0; else return 1;
}
Ee = select_block_type(_);
Ce = Ge[Ee] = $e[Ee](_);
let Ve = _[1] && create_if_block3(_);
return {
c() {
ee = element("div");
ne = element("div");
ie = element("div");
re = element("button");
re.textContent = "Scan changes";
se = space();
oe = element("button");
oe.textContent = "Sync once";
le = space();
ue = element("button");
ue.textContent = "Refresh";
de = space();
if (Fe) Fe.c();
fe = space();
he = element("button");
he.textContent = "Select All Shiny";
pe = space();
ge = element("div");
me = element("button");
me.textContent = "Apply All";
ye = space();
if (je) je.c();
ve = space();
Se = element("div");
Ce.c();
we = space();
if (Ve) Ve.c();
Oe = space();
ke = element("div");
xe = element("label");
Ae = element("span");
Ae.textContent = "Hide not applicable items";
Le = element("input");
Re = space();
Te = element("div");
Pe = element("label");
Ie = element("span");
Ie.textContent = "Maintenance mode";
De = element("input");
attr(re, "class", "svelte-1mend9p");
attr(oe, "class", "svelte-1mend9p");
attr(ue, "class", "svelte-1mend9p");
attr(he, "class", "svelte-1mend9p");
attr(ie, "class", "buttons svelte-1mend9p");
attr(me, "class", "svelte-1mend9p");
attr(ge, "class", "buttons svelte-1mend9p");
attr(Se, "class", "list");
attr(Ae, "class", "svelte-1mend9p");
attr(Le, "type", "checkbox");
attr(xe, "class", "svelte-1mend9p");
attr(ke, "class", "buttons svelte-1mend9p");
attr(Ie, "class", "svelte-1mend9p");
attr(De, "type", "checkbox");
attr(Pe, "class", "svelte-1mend9p");
attr(Te, "class", "buttons svelte-1mend9p");
},
m(Ce, $e) {
insert(Ce, ee, $e);
append(ee, ne);
append(ne, ie);
append(ie, re);
append(ie, se);
append(ie, oe);
append(ie, le);
append(ie, ue);
append(ie, de);
if (Fe) Fe.m(ie, null);
append(ie, fe);
append(ie, he);
append(ne, pe);
append(ne, ge);
append(ge, me);
append(ee, ye);
if (je) je.m(ee, null);
append(ee, ve);
append(ee, Se);
Ge[Ee].m(Se, null);
append(ee, we);
if (Ve) Ve.m(ee, null);
append(ee, Oe);
append(ee, ke);
append(ke, xe);
append(xe, Ae);
append(xe, Le);
Le.checked = _[2];
append(ee, Re);
append(ee, Te);
append(Te, Pe);
append(Pe, Ie);
append(Pe, De);
De.checked = _[1];
Be = true;
if (!Ne) {
Me = [ listen(re, "click", _[25]), listen(oe, "click", _[26]), listen(ue, "click", _[27]), listen(he, "click", _[29]), listen(me, "click", _[30]), listen(Le, "change", _[39]), listen(De, "change", _[40]) ];
Ne = true;
}
},
p(_, ne) {
if (_[1]) if (Fe) Fe.p(_, ne); else {
Fe = create_if_block_8(_);
Fe.c();
Fe.m(ie, fe);
} else if (Fe) {
Fe.d(1);
Fe = null;
}
if (_[3]) if (je) ; else {
je = create_if_block_7(_);
je.c();
je.m(ee, ve);
} else if (je) {
je.d(1);
je = null;
}
let re = Ee;
Ee = select_block_type(_);
if (Ee === re) Ge[Ee].p(_, ne); else {
group_outros();
transition_out(Ge[re], 1, 1, (() => {
Ge[re] = null;
}));
check_outros();
Ce = Ge[Ee];
if (!Ce) {
Ce = Ge[Ee] = $e[Ee](_);
Ce.c();
} else Ce.p(_, ne);
transition_in(Ce, 1);
Ce.m(Se, null);
}
if (_[1]) if (Ve) Ve.p(_, ne); else {
Ve = create_if_block3(_);
Ve.c();
Ve.m(ee, Oe);
} else if (Ve) {
Ve.d(1);
Ve = null;
}
if (4 & ne[0]) Le.checked = _[2];
if (2 & ne[0]) De.checked = _[1];
},
i(_) {
if (!Be) {
transition_in(Ce);
Be = true;
}
},
o(_) {
transition_out(Ce);
Be = false;
},
d(_) {
if (_) detach(ee);
if (Fe) Fe.d();
if (je) je.d();
Ge[Ee].d();
if (Ve) Ve.d();
Ne = false;
run_all(Me);
}
};
}
var PREFIX_PLUGIN_ALL = "PLUGIN_ALL", PREFIX_PLUGIN_DATA = "PLUGIN_DATA", PREFIX_PLUGIN_MAIN = "PLUGIN_MAIN";
function filterList(_, ee) {
return _.filter((_ => -1 !== ee.indexOf(_.category))).sort(((_, ee) => `${_.category}-${_.name}`.localeCompare(`${ee.category}-${ee.name}`)));
}
function groupBy(_, ee) {
let ne = {};
for (const ie of _) {
const _ = ee in ie ? ie[ee] : "";
ne[_] = ne[_] || [];
ne[_].push(ie);
}
for (const _ in ne) ne[_] = ne[_].sort(((_, ee) => `${_.category}-${_.name}`.localeCompare(`${ee.category}-${ee.name}`)));
return Object.entries(ne).sort((([_], [ee]) => `${_}`.localeCompare(`${ee}`)));
}
function instance3(_, ee, ne) {
let ie, re, se, {plugin: oe} = ee;
const le = oe.addOnConfigSync;
let ue = [], de = 0, fe = false, he = false, pe = 0, ge = false;
async function requestUpdate() {
await le.updatePluginList(true);
}
async function requestReload() {
await le.reloadPluginList(true);
}
let me = [];
pluginList.subscribe((_ => {
ne(0, ue = _);
ne(4, me = unique(ue.map((_ => _.term))));
}));
pluginIsEnumerating.subscribe((_ => {
ne(3, he = _);
}));
onMount((async () => {
requestUpdate();
}));
async function scanAgain() {
await le.scanAllConfigFiles(true);
await requestUpdate();
}
async function replicate2() {
await oe.replicate(true);
}
function selectAllNewest() {
ne(21, de++, de);
}
function applyAll() {
ne(22, pe++, pe);
}
async function applyData(_) {
return await le.applyData(_);
}
async function compareData(_, ee) {
return await le.compareUsingDisplayData(_, ee);
}
async function deleteData(_) {
return await le.deleteData(_);
}
function askMode(_, ee, ne) {
var ie;
const re = new import_obsidian3.Menu;
re.addItem((_ => _.setTitle(ee).setIsLabel(true)));
re.addSeparator();
const se = null !== (ie = Se.get(ne)) && void 0 !== ie ? ie : MODE_SELECTIVE;
for (const ee of [ MODE_SELECTIVE, MODE_AUTOMATIC, MODE_PAUSED ]) re.addItem((ie => {
ie.setTitle(`${getIcon(ee)}:${ve[ee]}`).onClick((ie => {
if (ee === MODE_AUTOMATIC) askOverwriteModeForAutomatic(_, ne); else setMode(ne, ee);
})).setChecked(se == ee).setDisabled(se == ee);
}));
re.showAtMouseEvent(_);
}
function applyAutomaticSync(_, ee) {
var ne, ie;
setMode(_, MODE_AUTOMATIC);
const re = normalizePath(oe.app.vault.configDir), se = (null !== (ie = null === (ne = oe.settings.pluginSyncExtendedSetting[_]) || void 0 === ne ? void 0 : ne.files) && void 0 !== ie ? ie : []).map((_ => `${re}/${_}`));
oe.addOnHiddenFileSync.syncInternalFilesAndDatabase(ee, true, false, se);
}
function askOverwriteModeForAutomatic(_, ee) {
const ne = new import_obsidian3.Menu;
ne.addItem((_ => _.setTitle("Initial Action").setIsLabel(true)));
ne.addSeparator();
ne.addItem((_ => {
_.setTitle("↑: Overwrite Remote").onClick((_ => {
applyAutomaticSync(ee, "pushForce");
}));
})).addItem((_ => {
_.setTitle("↓: Overwrite Local").onClick((_ => {
applyAutomaticSync(ee, "pullForce");
}));
})).addItem((_ => {
_.setTitle("⇅: Use newer").onClick((_ => {
applyAutomaticSync(ee, "safe");
}));
}));
ne.showAtMouseEvent(_);
}
const ye = {
[MODE_SELECTIVE]: "🔀",
[MODE_PAUSED]: "⛔",
[MODE_AUTOMATIC]: "✨"
}, ve = {
[MODE_SELECTIVE]: "Selective",
[MODE_PAUSED]: "Ignore",
[MODE_AUTOMATIC]: "Automatic"
};
function setMode(_, ee) {
if (_.startsWith(PREFIX_PLUGIN_ALL + "/")) {
setMode(PREFIX_PLUGIN_DATA + _.substring(PREFIX_PLUGIN_ALL.length), ee);
setMode(PREFIX_PLUGIN_MAIN + _.substring(PREFIX_PLUGIN_ALL.length), ee);
}
const ie = unique(ue.filter((ee => `${ee.category}/${ee.name}` == _)).map((_ => _.files)).flat().map((_ => _.filename)));
Se.set(_, ee);
ne(5, Ee = Se);
if (!(_ in oe.settings.pluginSyncExtendedSetting)) ne(20, oe.settings.pluginSyncExtendedSetting[_] = {
key: _,
mode: ee,
files: []
}, oe);
ne(20, oe.settings.pluginSyncExtendedSetting[_].files = ie, oe);
ne(20, oe.settings.pluginSyncExtendedSetting[_].mode = ee, oe);
oe.saveSettingData();
}
function getIcon(_) {
if (_ in ye) return ye[_];
}
let Se = new Map, Ee = new Map;
for (const {key: _, mode: ee} of Object.values(oe.settings.pluginSyncExtendedSetting)) Se.set(_, ee);
Ee = Se;
let Ce = {}, we = "";
async function deleteAllItems(_) {
const ee = ue.filter((ee => ee.term == _));
for (const _ of ee) await deleteData(_);
le.reloadPluginList(true);
}
_.$$set = _ => {
if ("plugin" in _) ne(20, oe = _.plugin);
};
_.$$.update = () => {
if (1048576 & _.$$.dirty[0]) ne(24, re = oe.deviceAndVaultName);
if (32505858 & _.$$.dirty[0]) ne(8, se = {
thisTerm: re,
hideNotApplicable: ie,
selectNewest: de,
applyAllPluse: pe,
applyData,
compareData,
deleteData,
plugin: oe,
isMaintenanceMode: ge
});
if (1048577 & _.$$.dirty[0]) {
const _ = Object.keys(oe.settings.pluginSyncExtendedSetting);
ne(6, Ce = [ ...ue, ..._.map((_ => `${_}///`.split("/"))).filter((_ => _[0] && _[1])).map((_ => ({
category: _[0],
name: _[1],
displayName: _[1]
}))) ].sort(((_, ee) => {
var ne, ie;
return (null !== (ne = _.displayName) && void 0 !== ne ? ne : _.name).localeCompare(null !== (ie = ee.displayName) && void 0 !== ie ? ie : ee.name);
})).reduce(((_, ee) => {
var ne, ie;
return {
..._,
[ee.category]: unique(ee.category in _ ? [ ..._[ee.category], null !== (ne = ee.displayName) && void 0 !== ne ? ne : ee.name ] : [ null !== (ie = ee.displayName) && void 0 !== ie ? ie : ee.name ])
};
}), {}));
}
};
ne(23, ie = false);
return [ ue, ge, fe, he, me, Ee, Ce, we, se, requestUpdate, requestReload, {
CONFIG: "Configuration",
THEME: "Themes",
SNIPPET: "Snippets"
}, scanAgain, replicate2, selectAllNewest, applyAll, askMode, ve, getIcon, deleteAllItems, oe, de, pe, ie, re, () => scanAgain(), () => replicate2(), () => requestUpdate(), () => requestReload(), () => selectAllNewest(), () => applyAll(), ([_, ee]) => _ in Ce, (_, ee, ne, ie) => askMode(ie, `${_}/${ee}`, ne), (_, ee, ne) => ne.category == _ && ne.name == ee, (_, ee, ne) => askMode(ne, `${PREFIX_PLUGIN_ALL}/${_}`, ee), (_, ee, ne) => askMode(ne, `${PREFIX_PLUGIN_MAIN}/${_}/MAIN`, ee), (_, ee, ne) => askMode(ne, `${PREFIX_PLUGIN_DATA}/${_}`, ee), function select_change_handler() {
we = select_value(this);
ne(7, we);
ne(4, me);
}, _ => {
deleteAllItems(we);
}, function input0_change_handler() {
fe = this.checked;
ne(2, fe);
}, function input1_change_handler() {
ge = this.checked;
ne(1, ge);
} ];
}
var PluginPane = class extends SvelteComponent {
constructor(_) {
super();
init2(this, _, instance3, create_fragment3, safe_not_equal, {
plugin: 20
}, add_css3, [ -1, -1, -1 ]);
}
}, PluginPane_default = PluginPane, PluginDialogModal = class extends import_obsidian.Modal {
isOpened() {
return null != this.component;
}
constructor(_, ee) {
super(_);
this.plugin = ee;
}
onOpen() {
const {contentEl: _} = this;
this.titleEl.setText("Customization Sync (Beta2)");
if (!this.component) this.component = new PluginPane_default({
target: _,
props: {
plugin: this.plugin
}
});
}
onClose() {
if (this.component) {
this.component.$destroy();
this.component = void 0;
}
}
}, InputStringDialog = class extends import_obsidian.Modal {
constructor(_, ee, ne, ie, re, se) {
super(_);
this.result = false;
this.isManuallyClosed = false;
this.isPassword = false;
this.onSubmit = se;
this.title = ee;
this.placeholder = ie;
this.key = ne;
this.isPassword = re;
}
onOpen() {
const {contentEl: _} = this;
this.titleEl.setText(this.title);
const ee = _.createDiv();
new import_obsidian.Setting(ee).setName(this.key).setClass(this.isPassword ? "password-input" : "normal-input").addText((_ => _.onChange((_ => {
this.result = _;
}))));
new import_obsidian.Setting(ee).addButton((_ => _.setButtonText("Ok").setCta().onClick((() => {
this.isManuallyClosed = true;
this.close();
})))).addButton((_ => _.setButtonText("Cancel").setCta().onClick((() => {
this.close();
}))));
}
onClose() {
const {contentEl: _} = this;
_.empty();
if (this.isManuallyClosed) this.onSubmit(this.result); else this.onSubmit(false);
}
}, PopoverSelectString = class extends import_obsidian.FuzzySuggestModal {
constructor(_, ee, ne, ie, re) {
super(_);
this.callback = () => {};
this.getItemsFun = () => [ "yes", "no" ];
this.app = _;
this.setPlaceholder((null != ne ? ne : "y/n) ") + ee);
if (ie) this.getItemsFun = ie;
this.callback = re;
}
getItems() {
return this.getItemsFun();
}
getItemText(_) {
return _;
}
onChooseItem(_, ee) {
var ne;
null == (ne = this.callback) || ne.call(this, _);
this.callback = void 0;
}
onClose() {
setTimeout((() => {
if (this.callback) {
this.callback("");
this.callback = void 0;
}
}), 100);
}
}, MessageBox = class extends import_obsidian.Modal {
constructor(_, ee, ne, ie, re, se, oe) {
super(_.app);
this.result = false;
this.isManuallyClosed = false;
this.timer = void 0;
this.plugin = _;
this.title = ee;
this.contentMd = ne;
this.buttons = ie;
this.onSubmit = oe;
this.defaultAction = re;
this.timeout = se;
if (this.timeout) this.timer = setInterval((() => {
var _;
if (void 0 !== this.timeout) {
this.timeout--;
if (this.timeout < 0) {
if (this.timer) {
clearInterval(this.timer);
this.timer = void 0;
}
this.result = re;
this.isManuallyClosed = true;
this.close();
} else null == (_ = this.defaultButtonComponent) || _.setButtonText(`( ${this.timeout} ) ${re}`);
}
}), 1e3);
}
onOpen() {
const {contentEl: _} = this;
this.titleEl.setText(this.title);
_.addEventListener("click", (() => {
if (this.timer) {
clearInterval(this.timer);
this.timer = void 0;
}
}));
const ee = _.createDiv();
import_obsidian.MarkdownRenderer.render(this.plugin.app, this.contentMd, ee, "/", this.plugin);
const ne = new import_obsidian.Setting(_);
ne.controlEl.style.flexWrap = "wrap";
for (const _ of this.buttons) ne.addButton((ee => {
ee.setButtonText(_).onClick((() => {
this.isManuallyClosed = true;
this.result = _;
if (this.timer) {
clearInterval(this.timer);
this.timer = void 0;
}
this.close();
}));
if (_ == this.defaultAction) this.defaultButtonComponent = ee;
return ee;
}));
}
onClose() {
const {contentEl: _} = this;
_.empty();
if (this.timer) {
clearInterval(this.timer);
this.timer = void 0;
}
if (this.isManuallyClosed) this.onSubmit(this.result); else this.onSubmit(false);
}
};
function confirmWithMessage(_, ee, ne, ie, re, se) {
return new Promise((oe => {
new MessageBox(_, ee, ne, ie, re, se, (_ => oe(_))).open();
}));
}
var __save, _save_fn, __load, _load_fn, __queueSave, _queueSave_fn, sameChangePairs, YieldOperationNumbers = 100, PersistentMap = class {
constructor(_, ee) {
__privateAdd(this, __save);
__privateAdd(this, __load);
__privateAdd(this, __queueSave);
this._setCount = YieldOperationNumbers;
this._key = _;
this._map = new Map(null != ee ? ee : []);
__privateMethod(this, __load, _load_fn).call(this, ee);
}
flush() {
__privateMethod(this, __save, _save_fn).call(this);
}
delete(_) {
const ee = this._map.delete(_);
__privateMethod(this, __queueSave, _queueSave_fn).call(this);
return ee;
}
has(_) {
return this._map.has(_);
}
set(_, ee) {
this._map.set(_, ee);
__privateMethod(this, __queueSave, _queueSave_fn).call(this);
return this;
}
clear() {
this._map = new Map;
__privateMethod(this, __save, _save_fn).call(this);
}
get(_, ee) {
const ne = this._map.get(_);
if (void 0 === ne) return ee; else return ne;
}
};
__save = new WeakSet;
_save_fn = function() {
localStorage.setItem(this._key, JSON.stringify([ ...this._map.entries() ]));
};
__load = new WeakSet;
_load_fn = function(_ = []) {
var ee;
try {
const ne = null != (ee = localStorage.getItem(this._key)) ? ee : "", ie = "" === ne ? "[]" : ne, re = JSON.parse(ie);
this._map = new Map([ ...re, ..._ ]);
} catch (ee) {
console.log(`Map read error : ${this._key}`);
console.dir(ee);
this._map = new Map([ ..._ ]);
}
return Promise.resolve();
};
__queueSave = new WeakSet;
_queueSave_fn = function() {
this._setCount--;
if (this._setCount < 0) {
this._setCount = YieldOperationNumbers;
scheduleTask(`save-map-${this._key}`, 0, (() => __privateMethod(this, __save, _save_fn).call(this)));
}
scheduleTask(`save-map-${this._key}`, 150, (() => __privateMethod(this, __save, _save_fn).call(this)));
};
function initializeStores(_) {
sameChangePairs = new PersistentMap(`ls-persist-same-changes-${_}`);
}
async function path2id(_, ee) {
const ne = _.split(":"), ie = ne.pop(), re = normalizePath(ie);
ne.push(re);
const se = ne.join(":");
return await path2id_base(se, ee);
}
function id2path(_, ee) {
const ne = id2path_base(_, ee).split(":"), ie = ne.pop(), re = normalizePath(ie);
ne.push(re);
return ne.join(":");
}
function getPath2(_) {
return id2path(_._id, _);
}
function getPathWithoutPrefix(_) {
return stripAllPrefixes(getPath2(_));
}
function getPathFromTFile(_) {
return _.path;
}
var memos = {};
function memoObject(_, ee) {
memos[_] = ee;
return memos[_];
}
async function memoIfNotExist(_, ee) {
if (!(_ in memos)) {
const ne = ee(), ie = ne instanceof Promise ? await ne : ne;
memos[_] = ie;
}
return memos[_];
}
function retrieveMemoObject(_) {
if (_ in memos) return memos[_]; else return false;
}
function disposeMemoObject(_) {
delete memos[_];
}
function isSensibleMargeApplicable(_) {
if (_.endsWith(".md")) return true; else return false;
}
function isObjectMargeApplicable(_) {
if (_.endsWith(".canvas")) return true;
if (_.endsWith(".json")) return true; else return false;
}
function tryParseJSON(_, ee) {
try {
return JSON.parse(_);
} catch (_) {
return ee;
}
}
var MARK_OPERATOR = "", MARK_DELETED = `${MARK_OPERATOR}__DELETED`, MARK_ISARRAY = `${MARK_OPERATOR}__ARRAY`, MARK_SWAPPED = `${MARK_OPERATOR}__SWAP`;
function unorderedArrayToObject(_) {
return _.map((_ => ({
[_.id]: _
}))).reduce(((_, ee) => ({
..._,
...ee
})), {});
}
function objectToUnorderedArray(_) {
const ee = Object.entries(_);
if (ee.some((_ => {
var ee;
return _[0] != (null == (ee = _[1]) ? void 0 : ee.id);
}))) throw new Error("Item looks like not unordered array");
return ee.map((_ => _[1]));
}
function generatePatchUnorderedArray(_, ee) {
if (_.every((_ => "object" == typeof _ && "id" in _)) && ee.every((_ => "object" == typeof _ && "id" in _))) {
const ne = generatePatchObj(unorderedArrayToObject(_), unorderedArrayToObject(ee));
if (Object.keys(ne).length > 0) return {
[MARK_ISARRAY]: ne
}; else return {};
}
return {
[MARK_SWAPPED]: ee
};
}
function generatePatchObj(_, ee) {
const ne = Object.entries(_), ie = new Map(ne), re = {}, se = Object.entries(ee);
for (const [_, ee] of se) if (!ie.has(_)) {
re[_] = ee;
ie.delete(_);
} else {
const ne = ie.get(_);
if (typeof ne != typeof ee || Array.isArray(ne) !== Array.isArray(ee)) re[_] = {
[MARK_SWAPPED]: ee
}; else if ("object" == typeof ne && "object" == typeof ee && !Array.isArray(ne) && !Array.isArray(ee)) {
const ie = generatePatchObj(ne, ee);
if (Object.keys(ie).length > 0) re[_] = ie;
} else if ("object" == typeof ne && "object" == typeof ee && Array.isArray(ne) && Array.isArray(ee)) {
const ie = generatePatchUnorderedArray(ne, ee);
if (Object.keys(ie).length > 0) re[_] = ie;
} else if ("object" != typeof ne && "object" != typeof ee) {
if (JSON.stringify(ie.get(_)) !== JSON.stringify(ee)) re[_] = ee;
} else if (JSON.stringify(ie.get(_)) !== JSON.stringify(ee)) re[_] = {
[MARK_SWAPPED]: ee
};
ie.delete(_);
}
for (const [_] of ie) re[_] = MARK_DELETED;
return re;
}
function applyPatch(_, ee) {
const ne = _, ie = Object.entries(ee);
for (const [_, ee] of ie) if (ee != MARK_DELETED) if ("object" == typeof ee) {
if (MARK_SWAPPED in ee) {
ne[_] = ee[MARK_SWAPPED];
continue;
}
if (MARK_ISARRAY in ee) {
if (!(_ in ne)) ne[_] = [];
if (!Array.isArray(ne[_])) throw new Error("Patch target type is mismatched (array to something)");
const ie = objectToUnorderedArray(applyPatch(unorderedArrayToObject(ne[_]), ee[MARK_ISARRAY]));
ne[_] = [ ...ie ];
} else {
if (!(_ in ne)) {
ne[_] = ee;
continue;
}
ne[_] = applyPatch(ne[_], ee);
}
} else ne[_] = ee; else delete ne[_];
return ne;
}
function mergeObject(_, ee) {
const ne = Object.entries(ee), ie = {
..._
};
if (typeof _ != typeof ee || Array.isArray(_) !== Array.isArray(ee)) return ee;
for (const [_, ee] of ne) if (_ in ie) {
const ne = ie[_];
if (typeof ee != typeof ne || Array.isArray(ee) !== Array.isArray(ne)) ie[_] = ee; else if ("object" == typeof ee && "object" == typeof ne && !Array.isArray(ee) && !Array.isArray(ne)) ie[_] = mergeObject(ee, ne); else if ("object" == typeof ee && "object" == typeof ne && Array.isArray(ee) && Array.isArray(ne)) ie[_] = [ ...new Set([ ...ee, ...ne ]) ]; else ie[_] = ee;
} else ie[_] = ee;
const re = Object.fromEntries(Object.entries(ie).sort(((_, ee) => _[0] < ee[0] ? -1 : _[0] > ee[0] ? 1 : 0)));
if (Array.isArray(_) && Array.isArray(ee)) return Object.values(re); else return re;
}
function flattenObject(_, ee = []) {
if ("object" != typeof _) return [ [ ee.join("."), _ ] ];
if (Array.isArray(_)) return [ [ ee.join("."), JSON.stringify(_) ] ];
const ne = Object.entries(_), ie = [];
for (const [_, re] of ne) {
const ne = flattenObject(re, [ ...ee, _ ]);
ie.push(...ne);
}
return ie;
}
function isValidPath(_) {
if (import_obsidian.Platform.isDesktop) {
if ("darwin" == process.platform) return isValidFilenameInDarwin(_);
if ("linux" == process.platform) return isValidFilenameInLinux(_); else return isValidFilenameInWidows(_);
}
if (import_obsidian.Platform.isAndroidApp) return isValidFilenameInAndroid(_);
if (import_obsidian.Platform.isIosApp) return isValidFilenameInDarwin(_);
Logger("Could not determine platform for checking filename", LOG_LEVEL_VERBOSE);
return isValidFilenameInWidows(_);
}
function isInternalMetadata(_) {
return _.startsWith(ICHeader);
}
function stripInternalMetadataPrefix(_) {
return _.substring(ICHeaderLength);
}
function isChunk(_) {
return _.startsWith(CHeader);
}
function isPluginMetadata(_) {
return _.startsWith(PSCHeader);
}
function isCustomisationSyncMetadata(_) {
return _.startsWith(ICXHeader);
}
var askYesNo = (_, ee) => new Promise((ne => {
new PopoverSelectString(_, ee, void 0, void 0, (_ => ne(_))).open();
})), askSelectString = (_, ee, ne) => {
const getItemsFun = () => ne;
return new Promise((ne => {
new PopoverSelectString(_, ee, "", getItemsFun, (_ => ne(_))).open();
}));
}, askString = (_, ee, ne, ie, re = false) => new Promise((se => {
new InputStringDialog(_, ee, ne, ie, re, (_ => se(_))).open();
})), PeriodicProcessor = class {
constructor(_, ee) {
this._plugin = _;
this._process = ee;
}
async process() {
try {
await this._process();
} catch (_) {
Logger(_);
}
}
enable(_) {
this.disable();
if (0 != _) {
this._timer = window.setInterval((() => fireAndForget((async () => {
await this.process();
if (this._plugin._unloaded) this.disable();
}))), _);
this._plugin.registerInterval(this._timer);
}
}
disable() {
if (void 0 !== this._timer) {
window.clearInterval(this._timer);
this._timer = void 0;
}
}
}, _requestToCouchDB = async (_, ee, ne, ie, re, se, oe) => {
const le = String.fromCharCode.apply(null, [ ...writeString(`${ee}:${ne}`) ]), ue = {
url: `${_}/${re}`,
method: oe || (se ? "PUT" : "GET"),
headers: {
authorization: "Basic " + window.btoa(le),
origin: ie
},
contentType: "application/json",
body: se ? JSON.stringify(se) : void 0
};
return await (0, import_obsidian.requestUrl)(ue);
}, requestToCouchDB = async (_, ee, ne, ie = "", re, se, oe) => {
const le = "_node/_local/_config" + (re ? "/" + re : "");
return await _requestToCouchDB(_, ee, ne, ie, le, se, oe);
};
async function performRebuildDB(_, ee) {
if ("localOnly" == ee) await _.addOnSetup.fetchLocal();
if ("localOnlyWithChunks" == ee) await _.addOnSetup.fetchLocal(true);
if ("remoteOnly" == ee) await _.addOnSetup.rebuildRemote();
if ("rebuildBothByThisDevice" == ee) await _.addOnSetup.rebuildEverything();
}
var BASE_IS_NEW = Symbol("base"), TARGET_IS_NEW = Symbol("target"), EVEN = Symbol("even"), resolution = 2e3;
function compareMTime(_, ee) {
const ne = ~~(_ / resolution) * resolution, ie = ~~(ee / resolution) * resolution;
if (ne == ie) return EVEN;
if (ne > ie) return BASE_IS_NEW;
if (ne < ie) return TARGET_IS_NEW;
throw new Error("Unexpected error");
}
function markChangesAreSame(_, ee, ne) {
var ie;
if (ee === ne) return true;
const re = "string" == typeof _ ? _ : _ instanceof import_obsidian.TFile ? _.path : null != (ie = _.path) ? ie : _._id, se = sameChangePairs.get(re, []) || [];
if (se.some((_ => _ == ee || _ == ne))) sameChangePairs.set(re, [ ...new Set([ ...se, ee, ne ]) ]); else sameChangePairs.set(re, [ ee, ne ]);
}
function isMarkedAsSameChanges(_, ee) {
var ne;
const ie = "string" == typeof _ ? _ : _ instanceof import_obsidian.TFile ? _.path : null != (ne = _.path) ? ne : _._id, re = sameChangePairs.get(ie, []) || [];
if (ee.every((_ => -1 !== re.indexOf(_)))) return EVEN;
}
function compareFileFreshness(_, ee) {
var ne, ie, re, se, oe, le;
if (void 0 === _ && null == ee) return EVEN;
if (null == _) return TARGET_IS_NEW;
if (null == ee) return BASE_IS_NEW;
const ue = _ instanceof import_obsidian.TFile ? null != (ie = null == (ne = null == _ ? void 0 : _.stat) ? void 0 : ne.mtime) ? ie : 0 : null != (re = null == _ ? void 0 : _.mtime) ? re : 0, de = ee instanceof import_obsidian.TFile ? null != (oe = null == (se = null == ee ? void 0 : ee.stat) ? void 0 : se.mtime) ? oe : 0 : null != (le = null == ee ? void 0 : ee.mtime) ? le : 0;
if (ue && de && isMarkedAsSameChanges(_, [ ue, de ])) return EVEN; else return compareMTime(ue, de);
}
var import_obsidian5 = require("obsidian");
function add_css4(_) {
append_styles(_, "svelte-zh5x8", "label.svelte-zh5x8.svelte-zh5x8{min-width:4em;width:4em;display:inline-flex;flex-direction:row;justify-content:flex-end}ul.svelte-zh5x8.svelte-zh5x8{flex-grow:1;display:inline-flex;flex-direction:column;list-style-type:none;margin-block-start:0;margin-block-end:0;margin-inline-start:0px;margin-inline-end:0px;padding-inline-start:0}li.svelte-zh5x8.svelte-zh5x8{padding:var(--size-2-1) var(--size-4-1);display:inline-flex;flex-grow:1;align-items:center;justify-content:flex-end;gap:var(--size-4-2)}li.svelte-zh5x8 input.svelte-zh5x8{min-width:10em}button.iconbutton.svelte-zh5x8.svelte-zh5x8{max-width:4em}");
}
function get_each_context4(_, ee, ne) {
const ie = _.slice();
ie[15] = ee[ne];
ie[16] = ee;
ie[17] = ne;
return ie;
}
function create_each_block4(_) {
let ee, ne, ie, re, se, oe, le, ue, de, fe = _[2][_[17]] + "", he = _[3][_[17]] + "";
function input_input_handler() {
_[8].call(se, _[16], _[17]);
}
function click_handler() {
return _[9](_[17]);
}
return {
c() {
ee = element("li");
ne = element("label");
ie = text(fe);
re = text(he);
se = element("input");
le = element("button");
le.textContent = "🗑";
attr(ne, "class", "svelte-zh5x8");
attr(se, "type", "text");
attr(se, "class", oe = null_to_empty(_[2][_[17]]) + " svelte-zh5x8");
attr(le, "class", "iconbutton svelte-zh5x8");
attr(ee, "class", "svelte-zh5x8");
},
m(oe, fe) {
insert(oe, ee, fe);
append(ee, ne);
append(ne, ie);
append(ne, re);
append(ee, se);
set_input_value(se, _[15]);
append(ee, le);
if (!ue) {
de = [ listen(se, "input", input_input_handler), listen(le, "click", click_handler) ];
ue = true;
}
},
p(ee, ne) {
_ = ee;
if (4 & ne && fe !== (fe = _[2][_[17]] + "")) set_data(ie, fe);
if (8 & ne && he !== (he = _[3][_[17]] + "")) set_data(re, he);
if (4 & ne && oe !== (oe = null_to_empty(_[2][_[17]]) + " svelte-zh5x8")) attr(se, "class", oe);
if (1 & ne && se.value !== _[15]) set_input_value(se, _[15]);
},
d(_) {
if (_) detach(ee);
ue = false;
run_all(de);
}
};
}
function create_fragment4(_) {
let ee, ne, ie, re, se, oe, le, ue, de, fe, he, pe, ge, me, ye, ve, Se = ensure_array_like(_[0]), Ee = [];
for (let ee = 0; ee < Se.length; ee += 1) Ee[ee] = create_each_block4(get_each_context4(_, Se, ee));
return {
c() {
ee = element("ul");
for (let _ = 0; _ < Ee.length; _ += 1) Ee[_].c();
ne = space();
ie = element("li");
re = element("label");
se = element("button");
se.textContent = "Add";
oe = space();
le = element("li");
ue = element("button");
de = text("Apply");
he = space();
pe = element("button");
ge = text("Revert");
attr(re, "class", "svelte-zh5x8");
attr(ie, "class", "svelte-zh5x8");
ue.disabled = fe = _[3].some(_[11]) || _[2].every(func_1);
pe.disabled = me = _[3].some(_[13]) || _[2].every(func_3);
attr(le, "class", "buttons svelte-zh5x8");
attr(ee, "class", "svelte-zh5x8");
},
m(fe, me) {
insert(fe, ee, me);
for (let _ = 0; _ < Ee.length; _ += 1) if (Ee[_]) Ee[_].m(ee, null);
append(ee, ne);
append(ee, ie);
append(ie, re);
append(re, se);
append(ee, oe);
append(ee, le);
append(le, ue);
append(ue, de);
append(le, he);
append(le, pe);
append(pe, ge);
if (!ye) {
ve = [ listen(se, "click", _[10]), listen(ue, "click", _[12]), listen(pe, "click", _[14]) ];
ye = true;
}
},
p(_, [ie]) {
if (45 & ie) {
Se = ensure_array_like(_[0]);
let re;
for (re = 0; re < Se.length; re += 1) {
const se = get_each_context4(_, Se, re);
if (Ee[re]) Ee[re].p(se, ie); else {
Ee[re] = create_each_block4(se);
Ee[re].c();
Ee[re].m(ee, ne);
}
}
for (;re < Ee.length; re += 1) Ee[re].d(1);
Ee.length = Se.length;
}
if (12 & ie && fe !== (fe = _[3].some(_[11]) || _[2].every(func_1))) ue.disabled = fe;
if (12 & ie && me !== (me = _[3].some(_[13]) || _[2].every(func_3))) pe.disabled = me;
},
i: noop2,
o: noop2,
d(_) {
if (_) detach(ee);
destroy_each(Ee, _);
ye = false;
run_all(ve);
}
};
}
var CHECK_OK = "✔", CHECK_NG = "⚠", MARK_MODIFIED = "✏ ";
function checkRegExp(_) {
if ("" == _.trim()) return "";
try {
new RegExp(_);
return CHECK_OK;
} catch (_) {
return CHECK_NG;
}
}
var func_1 = _ => "" == _, func_3 = _ => "" == _;
function instance4(_, ee, ne) {
let ie, re, {patterns: se = []} = ee, {originals: oe = []} = ee, {apply: le = (_ => Promise.resolve())} = ee;
function revert() {
ne(0, se = [ ...oe ]);
}
function remove(_) {
ne(0, se[_] = "", se);
}
function add() {
ne(0, se = [ ...se, "" ]);
}
_.$$set = _ => {
if ("patterns" in _) ne(0, se = _.patterns);
if ("originals" in _) ne(7, oe = _.originals);
if ("apply" in _) ne(1, le = _.apply);
};
_.$$.update = () => {
if (1 & _.$$.dirty) ne(3, ie = se.map((_ => checkRegExp(_))));
if (129 & _.$$.dirty) ne(2, re = se.map(((_, ee) => {
var ne;
return (null !== (ne = _ != (null == oe ? void 0 : oe[ee])) && void 0 !== ne ? ne : "") ? MARK_MODIFIED : "";
})));
};
return [ se, le, re, ie, revert, remove, add, oe, function input_input_handler(_, ee) {
_[ee] = this.value;
ne(0, se);
}, _ => remove(_), () => add(), _ => _ == CHECK_NG, () => le(se), _ => _ == CHECK_NG, () => revert() ];
}
var MultipleRegExpControl = class extends SvelteComponent {
constructor(_) {
super();
init2(this, _, instance4, create_fragment4, safe_not_equal, {
patterns: 0,
originals: 7,
apply: 1
}, add_css4);
}
}, MultipleRegExpControl_default = MultipleRegExpControl;
function inlineWorker(_) {
let ee = new Blob([ _ ], {
type: "text/javascript"
}), ne = URL.createObjectURL(ee), ie = new Worker(ne);
URL.revokeObjectURL(ne);
return ie;
}
function Worker2() {
return inlineWorker('var M=Object.defineProperty,B=Object.defineProperties;var k=Object.getOwnPropertyDescriptors;var T=Object.getOwnPropertySymbols;var U=Object.prototype.hasOwnProperty,G=Object.prototype.propertyIsEnumerable;var x=(e,n)=>(n=Symbol[e])?n:Symbol.for("Symbol."+e);var A=(e,n,t)=>n in e?M(e,n,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[n]=t,O=(e,n)=>{for(var t in n||(n={}))U.call(n,t)&&A(e,t,n[t]);if(T)for(var t of T(n))G.call(n,t)&&A(e,t,n[t]);return e},L=(e,n)=>B(e,k(n));var m=function(e,n){this[0]=e,this[1]=n},_=(e,n,t)=>{var r=(l,s,c,a)=>{try{var y=t[l](s),f=(s=y.value)instanceof m,E=y.done;Promise.resolve(f?s[0]:s).then(u=>f?r(l==="return"?l:"next",s[1]?{done:u.done,value:u.value}:u,c,a):c({value:u,done:E})).catch(u=>r("throw",u,c,a))}catch(u){a(u)}},o=l=>i[l]=s=>new Promise((c,a)=>r(l,s,c,a)),i={};return t=t.apply(e,n),i[x("asyncIterator")]=()=>i,o("next"),o("throw"),o("return"),i},S=e=>{var n=e[x("asyncIterator")],t=!1,r,o={};return n==null?(n=e[x("iterator")](),r=i=>o[i]=l=>n[i](l)):(n=n.call(e),r=i=>o[i]=l=>{if(t){if(t=!1,i==="throw")throw l;return l}return t=!0,{done:!1,value:new m(new Promise(s=>{var c=n[i](l);if(!(c instanceof Object))throw TypeError("Object expected");s(c)}),1)}}),o[x("iterator")]=()=>o,r("next"),"throw"in n?r("throw"):o.throw=i=>{throw i},"return"in n&&r("return"),o},C=(e,n,t)=>(n=e[x("asyncIterator")])?n.call(e):(e=e[x("iterator")](),n={},t=(r,o)=>(o=e[r])&&(n[r]=i=>new Promise((l,s,c)=>(i=o.call(e,i),c=i.done,Promise.resolve(i.value).then(a=>l({value:a,done:c}),s)))),t("next"),t("return"),n);var re=Symbol("cancelled"),oe=Symbol("auto_merged"),ie=Symbol("not_conflicted"),se=Symbol("missing_or_error"),ae=Symbol("leave_to_subsequent_proc"),le=Symbol("infinity"),ce=Symbol("timed out"),ue=Symbol("NotFound");var D={syncMaxSizeInMB:50,customChunkSize:0,concurrencyOfReadChunksOnline:100,minimumIntervalOfReadChunksOnline:333},ye=L(O({},D),{customChunkSize:50,concurrencyOfReadChunksOnline:30,minimumIntervalOfReadChunksOnline:25}),fe=L(O({},D),{customChunkSize:10,concurrencyOfReadChunksOnline:30,minimumIntervalOfReadChunksOnline:25}),v={minimumChunkSize:20,longLineThreshold:250,encrypt:!1,usePathObfuscation:!1,enableCompression:!1,useEden:!1,customChunkSize:0,useDynamicIterationCount:!1,hashAlg:"xxhash64",enableChunkSplitterV2:!0},V={maxChunksInEden:10,maxTotalLengthInEden:1024,maxAgeInEden:10,useIgnoreFiles:!1,useCustomRequestHandler:!1,batch_size:25,batches_limit:25,useIndexedDBAdapter:!0,useTimeouts:!1,readChunksOnline:!0,hashCacheMaxCount:300,hashCacheMaxAmount:50,concurrencyOfReadChunksOnline:40,minimumIntervalOfReadChunksOnline:50,ignoreFiles:".gitignore",syncMaxSizeInMB:50,enableChunkSplitterV2:!0};var pe=O(O({},V),v);var z={},H={};for(let e=0;e<256;e++)z[`00${e.toString(16)}`.slice(-2)]=e,H[e]=`00${e.toString(16)}`.slice(-2);function*K(e,n){for(let t=e;t<=n;t++)yield t}var $={},X={};[...K(192,447)].forEach((e,n)=>{$[n]=e,X[e]=n});var Ie=1024*1024*30;var Y=32768;var Te=3*5e7;function q(e){return new Promise((n,t)=>{let r=new Blob([e],{type:"application/octet-binary"}),o=new FileReader;o.onload=function(i){var c,a;let l=((a=(c=i.target)==null?void 0:c.result)==null?void 0:a.toString())||"";if(e.byteLength!=0&&(l==""||l=="data:"))return t(new TypeError("Could not parse the encoded string"));let s=l.substring(l.indexOf(",")+1);n(s)},o.readAsDataURL(r)})}async function I(e){let n=e instanceof Uint8Array?e:new Uint8Array(e);return n.byteLength0&&!(e[0].startsWith("```")||e[0].startsWith(" ```")||e[0].startsWith(" ```")||e[0].startsWith(" ```")));let o=t.endsWith("="),i=t.length>2048,l=e.shift();if(typeof l!="undefined"&&(t+=l,t+=e.length!=0?`\n`:""),!o&&!i){let s=/(.*?[;,:<])/g,c=t.split(s).filter(a=>a!="");for(let a of c)yield a}else yield t;t=""}else t+=r+(e.length!=0?`\n`:""),(t.length>=n||e.length==0||e[0]=="#"||t[0]=="#")&&(yield t,t="")}while(e.length>0)}var R=10;function J(e,n,t,r){let o=typeof e=="string"?[e]:e;return function*(){for(let l of o)if(t){let s=l.split(`\n`),c=j(s,r);for(let a of c){let y=a;do{let f=n;y.charCodeAt(f-1)!=y.codePointAt(f-1)&&f++,yield y.substring(0,f),y=y.substring(f)}while(y!="")}}else{let s=l;do{let c=n,a=s.substring(0,c);s=s.substring(c),yield a}while(s!="")}}}function*Q(e,n,t=25,r){let o="",i=!1,l=n.length;for(let s of e){let c=s.length;if(r&&c>r){yield o+s,i=!1,o="";continue}let a=-1,y=0;e:do{if(a=s.indexOf(n,y),a==-1)break e;o+=s.slice(y,a)+n,o.length>t?(yield o,o="",i=!1):i=!0,y=a+l}while(an){let r=0;do{let o=r+n;if(o>t){yield e.substring(r);break}for(;e.charCodeAt(o-1)!=e.codePointAt(o-1);)o++;yield e.substring(r,o),r=o}while(rne;)u+=r;let p=ee([f]),h=Q(p,`\n`,u),d=Z(h,n);return function*(){yield*S(d)}}let i=0;o&&o.endsWith(".pdf")&&(i=47);let c=Math.max(1e5,Math.min(1e8,e.size)),a=1,y=c;for(;y>10;)y/=12.5,a++;return r=Math.floor(10**(a-1)),function(){return _(this,null,function*(){let E=e.size,u=0,p=new Uint8Array(yield new m(e.arrayBuffer()));do{let h=u+r,d=u+n,g,b=p.indexOf(i,h);b==-1&&(b=p.indexOf(R,h)),b==-1?g=d:g=b10;)y/=12.5,a++;return r=Math.floor(10**(a-1)),function(){return _(this,null,function*(){let E=e.size,u=0;do{let p=n,h=new Uint8Array(yield new m(e.slice(u,u+n).arrayBuffer())),d=h.indexOf(i,r);p=d==-1?n:Math.min(n,d),d==-1&&(d=h.indexOf(R,r));let g=h.slice(0,p);u+=g.length,yield yield new m(I(g))}while(u{let n=e.data.data,t=n.key,r=n.dataSrc,o=n.pieceSize,i=n.plainSplit,l=n.minimumChunkSize,s=n.filename,a=await(n.useV2?P:N)(r,o,i,l,s);try{for(var y=C(a()),f,E,u;f=!(E=await y.next()).done;f=!1){let p=E.value;self.postMessage([t,p])}}catch(E){u=[E]}finally{try{f&&(E=y.return)&&await E.call(y)}finally{if(u)throw u[0]}}self.postMessage([t,void 0])};\n');
}
var key = 0, buffers = new Map, notify = new Notifier, worker = Worker2(), isTerminated = false;
worker.onmessage = ({data: _}) => {
const [ee, ne] = _;
if (!buffers.has(ee)) buffers.set(ee, []);
buffers.set(ee, buffers.get(ee).concat(ne));
notify.notify();
};
worker.onerror = () => {
worker.terminate();
isTerminated = true;
};
function terminateWorker() {
worker.terminate();
isTerminated = true;
}
function splitPieces2Worker(_, ee, ne, ie, re) {
return _splitPieces2Worker(_, ee, ne, ie, re, false);
}
function splitPieces2WorkerV2(_, ee, ne, ie, re) {
return _splitPieces2Worker(_, ee, ne, ie, re, true);
}
function _splitPieces2Worker(_, ee, ne, ie, re, se) {
key++;
worker.postMessage({
data: {
key,
dataSrc: _,
pieceSize: ee,
plainSplit: ne,
minimumChunkSize: ie,
filename: re,
useV2: se
}
});
buffers.set(key, []);
return async function* pieces() {
const _ = key;
do {
const ee = buffers.get(_);
if (ee.length > 0) {
const ne = ee.shift();
buffers.set(_, ee);
if (void 0 === ne) {
buffers.delete(_);
return;
}
yield ne;
} else await notify.nextNotify;
} while (!isTerminated);
};
}
function isTextBlob2(_) {
return "text/plain" === _.type;
}
function* pickPiece(_, ee) {
let ne = "";
e: do {
const ie = _.shift();
if ("undefined" == typeof ie) {
yield ne;
break e;
}
if (ie.startsWith("```") || ie.startsWith(" ```") || ie.startsWith(" ```") || ie.startsWith(" ```")) {
yield ne;
ne = ie + (0 != _.length ? "\n" : "");
t: do {
const ee = _.shift();
if ("undefined" == typeof ee) break t;
ne += ee + (0 != _.length ? "\n" : "");
} while (_.length > 0 && !(_[0].startsWith("```") || _[0].startsWith(" ```") || _[0].startsWith(" ```") || _[0].startsWith(" ```")));
const ee = ne.endsWith("="), re = ne.length > 2048, se = _.shift();
if ("undefined" != typeof se) {
ne += se;
ne += 0 != _.length ? "\n" : "";
}
if (!ee && !re) {
const _ = /(.*?[;,:<])/g, ee = ne.split(_).filter((_ => "" != _));
for (const _ of ee) yield _;
} else yield ne;
ne = "";
} else {
ne += ie + (0 != _.length ? "\n" : "");
if (ne.length >= ee || 0 == _.length || "#" == _[0] || "#" == ne[0]) {
yield ne;
ne = "";
}
}
} while (_.length > 0);
}
var charNewLine = "\n".charCodeAt(0);
function splitPiecesText(_, ee, ne, ie) {
const re = "string" == typeof _ ? [ _ ] : _;
return function* pieces() {
for (const _ of re) if (ne) {
const ne = pickPiece(_.split("\n"), ie);
for (const _ of ne) {
let ne = _;
do {
let _ = ee;
if (ne.charCodeAt(_ - 1) != ne.codePointAt(_ - 1)) _++;
yield ne.substring(0, _);
ne = ne.substring(_);
} while ("" != ne);
}
} else {
let ne = _;
do {
const _ = ee, ie = ne.substring(0, _);
ne = ne.substring(_);
yield ie;
} while ("" != ne);
}
};
}
function* splitByDelimiterWithMinLength(_, ee, ne = 25, ie) {
let re = "", se = false;
const oe = ee.length;
for (const le of _) {
const _ = le.length;
if (ie && _ > ie) {
yield re + le;
se = false;
re = "";
continue;
}
let ue = -1, de = 0;
e: do {
ue = le.indexOf(ee, de);
if (-1 == ue) break e;
re += le.slice(de, ue) + ee;
if (re.length > ne) {
yield re;
re = "";
se = false;
} else se = true;
de = ue + oe;
} while (ue < _);
if (de != ue || -1 == de && -1 == ue) {
re += le.slice(de);
se = true;
}
}
if (se) yield re;
}
function* chunkStringGenerator(_, ee) {
const ne = _.length;
if (ne > ee) {
let ie = 0;
do {
let re = ie + ee;
if (re > ne) {
yield _.substring(ie);
break;
}
for (;_.charCodeAt(re - 1) != _.codePointAt(re - 1); ) re++;
yield _.substring(ie, re);
ie = re;
} while (ie < ne);
} else yield _;
}
function* chunkStringGeneratorFromGenerator(_, ee) {
for (const ne of _) yield* chunkStringGenerator(ne, ee);
}
function* stringGenerator(_) {
for (const ee of _) yield ee;
}
var MAX_ITEMS = 100;
async function splitPieces2V2(_, ee, ne, ie, re) {
if (0 == _.size) return function* noItems() {};
if (isTextBlob2(_)) {
const re = await _.text();
if (!ne) {
const _ = chunkStringGenerator(re, ee);
return function* pieces() {
yield* _;
};
}
const se = re.length;
let oe = ie;
for (;se / oe > MAX_ITEMS; ) oe += ie;
const le = chunkStringGeneratorFromGenerator(splitByDelimiterWithMinLength(stringGenerator([ re ]), "\n", oe), ee);
return function* pieces() {
yield* le;
};
}
let se = 0;
if (re && re.endsWith(".pdf")) se = "/".charCodeAt(0);
let oe = 1, le = Math.max(1e5, Math.min(1e8, _.size));
for (;le > 10; ) {
le /= 12.5;
oe++;
}
ie = Math.floor(10 ** (oe - 1));
return async function* piecesBlob() {
const ne = _.size;
let re = 0;
const oe = new Uint8Array(await _.arrayBuffer());
do {
const _ = re + ie, ne = re + ee;
let le, ue = oe.indexOf(se, _);
if (-1 == ue) ue = oe.indexOf(charNewLine, _);
if (-1 == ue) le = ne; else le = ue < ne ? ue : ne;
yield await arrayBufferToBase64Single(oe.slice(re, le));
re = le;
} while (re < ne);
};
}
async function splitPieces2(_, ee, ne, ie, re) {
if (isTextBlob2(_)) return splitPiecesText(await _.text(), ee, ne, ie);
let se = 0;
if (re && re.endsWith(".pdf")) se = "/".charCodeAt(0);
let oe = 1, le = Math.max(1e5, Math.min(1e8, _.size));
for (;le > 10; ) {
le /= 12.5;
oe++;
}
ie = Math.floor(10 ** (oe - 1));
return async function* piecesBlob() {
const ne = _.size;
let re = 0;
do {
let ne = ee;
const oe = new Uint8Array(await _.slice(re, re + ee).arrayBuffer());
let le = oe.indexOf(se, ie);
ne = -1 == le ? ee : Math.min(ee, le);
if (-1 == le) le = oe.indexOf(charNewLine, ie);
const ue = oe.slice(0, ne);
re += ue.length;
yield await arrayBufferToBase64Single(ue);
} while (re < ne);
};
}
async function getChunk(_, ee, ne) {
const ie = _.hashCaches.revGet(ee);
if (void 0 !== ie) return {
isNew: false,
id: ie,
piece: ee
};
const re = PREFIX_CHUNK + await generateHashedChunk(_, ee);
if (re in ne.eden) return {
isNew: false,
id: re,
piece: ee
};
const se = _.hashCaches.get(re);
if (se && se != ee) {
Logger(`Hash collided! If possible, please report the following string:${re}=>\nA:--${se}--\nB:--${ee}--`, LOG_LEVEL_NOTICE);
return false;
}
_.hashCaches.set(re, ee);
return {
isNew: true,
id: re,
piece: ee
};
}
async function generateHashedChunk(_, ee) {
const ne = _.settings.passphrase;
if ("sha1" == _.settings.hashAlg) if (_.settings.encrypt) return "+" + await sha1(`${ee}-${ne}-${ee.length}`); else return await sha1(`${ee}-${ee.length}`); else if ("" === _.settings.hashAlg) if (_.settings.encrypt) {
const ie = _.h32Raw((new TextEncoder).encode(ne));
return "+" + (_.h32Raw((new TextEncoder).encode(ee)) ^ ie ^ ee.length).toString(36);
} else return (_.h32Raw((new TextEncoder).encode(ee)) ^ ee.length).toString(36); else if ("xxhash64" == _.settings.hashAlg && _.xxhash64) if (_.settings.encrypt) return "+" + _.xxhash64(`${ee}-${ne}-${ee.length}`).toString(36); else return _.xxhash64(`${ee}-${ee.length}`).toString(36); else if (_.settings.encrypt) return "+" + _.xxhash32(`${ee}-${ne}-${ee.length}`).toString(36); else return _.xxhash32(`${ee}-${ee.length}`).toString(36);
}
function getNoFromRev(_) {
if (!_) return 0; else return parseInt(_.split("-")[0]);
}
async function putDBEntry(_, ee) {
var ne;
const ie = _.id2path(ee._id, ee), re = stripAllPrefixes(ie);
if (!ee.eden) ee.eden = {};
if (!_.isTargetFile(ie)) {
Logger(`File skipped:${re}`, LOG_LEVEL_VERBOSE);
return false;
}
let se = 0;
const oe = Math.floor(MAX_DOC_SIZE_BIN * (1 * (_.settings.customChunkSize || 0) + 1));
let le = false;
const ue = _.settings.minimumChunkSize;
if (Date.now() - ee.mtime > 2592e6) le = false; else if (shouldSplitAsPlainText(ie)) le = true;
const de = ee.data instanceof Blob ? ee.data : createTextBlob(ee.data);
ee.type = isTextBlob(de) ? "plain" : "newnote";
ee.datatype = ee.type;
const fe = _.settings.enableChunkSplitterV2 ? splitPieces2V2 : splitPieces2, he = _.settings.enableChunkSplitterV2 ? splitPieces2WorkerV2 : splitPieces2Worker, pe = _.settings.disableWorkerForGeneratingChunks ? fe : _.settings.processSmallFilesInUIThread && ee.data.size < 1024 ? fe : he, ge = await pe(de, oe, le, ue, ie), me = [];
for await (const ne of ge()) {
se++;
me.push(getChunk(_, ne, ee));
}
const ye = await Promise.all(me);
if (ye.some((_ => false === _))) {
Logger(`This document could not be saved:${re}`, LOG_LEVEL_NOTICE);
return false;
}
let ve = {}, Se = 0;
if ("eden" in ee) ve = ee.eden;
let Ee = [];
if (_.settings.useEden) {
try {
const ne = await _.localDatabase.get(ee._id);
Se = getNoFromRev(ne._rev);
ve = {
..."eden" in ne ? ne.eden : {},
...ve
};
} catch (_) {
if (isErrorOfMissingDoc(_)) ; else throw _;
}
const ne = Object.keys(ve).length;
let ie = 0;
const se = Object.keys(ve).filter((_ => ye.every((ee => ee.id !== _))));
for (const _ of se) {
ie++;
delete ve[_];
}
let oe = 0, le = 0;
for (const _ of ye) if (_.id in ve) le++; else {
oe++;
ve[_.id] = {
epoch: Se + 1,
data: _.piece
};
}
const ue = Object.entries(ve).sort(((_, ee) => ee[1].epoch - _[1].epoch));
let de = 0, fe = 0;
const he = Object.keys(ve);
let pe = 0, ge = 0;
const me = (await _.localDatabase.allDocs({
keys: he
})).rows.reduce(((_, ee) => ({
..._,
[ee.key]: ee
})), {});
for (const [ee, ne] of ue) {
fe++;
let ie = false;
if (!(ee in me) || me[ee].error) {
if (ne.data.length > 1024) ie = true; else if (ne.epoch + _.settings.maxAgeInEden < Se) ie = true;
if (de > _.settings.maxTotalLengthInEden) ie = true;
if (fe > _.settings.maxChunksInEden) ie = true;
if (ie) {
fe--;
ge++;
Ee.push({
_id: ee,
data: ne.data,
type: "leaf"
});
delete ve[ee];
} else de += ne.data.length;
} else {
fe--;
delete ve[ee];
pe++;
}
}
Logger(`Progress on Eden: doc: ${re} : ${ne}->${Object.keys(ve).length} (removed: ${ie}, new: ${oe}, exist: ${le}, alreadyIndependent:${pe}, independent:${ge})`, LOG_LEVEL_VERBOSE);
} else Ee = ye.filter((_ => _.isNew)).map((_ => ({
_id: _.id,
data: _.piece,
type: "leaf"
})));
const Ce = se - Ee.length;
if (Ee.length) {
const ee = (await _.localDatabase.bulkDocs(Ee)).reduce(((_, ee) => {
if ("ok" in ee) {
_.ok.push(ee);
return _;
}
if ("error" in ee) if (409 == ee.status) {
_.skip.push(ee);
return _;
}
_.failed.push(ee);
return _;
}), {
ok: [],
skip: [],
failed: []
});
if (ee.failed.length) {
Logger(`Save failed.: ${re} :${ee.failed.map((_ => {
var ee;
return null != (ee = null == _ ? void 0 : _.id) ? ee : _.toString();
})).join(",")}`, LOG_LEVEL_VERBOSE);
Logger(`This document could not be saved:${re}`, LOG_LEVEL_NOTICE);
return false;
}
Logger(`Chunks saved: doc: ${re} ,chunks: ${se} (new:${ee.ok.length}, recycled:${ee.skip.length}, cached:${Ce})`);
}
const we = {
children: ye.map((_ => _.id)),
_id: ee._id,
path: ee.path,
ctime: ee.ctime,
mtime: ee.mtime,
size: ee.size,
type: ee.datatype,
eden: ve
};
return null != (ne = await serialized("file:" + ie, (async () => {
try {
const ee = await _.localDatabase.get(we._id);
we._rev = ee._rev;
} catch (_) {
if (isErrorOfMissingDoc(_)) ; else throw _;
}
const ee = await _.localDatabase.put(we, {
force: true
});
if (ee.ok) return ee; else return false;
}))) ? ne : false;
}
async function getDBEntryMeta(_, ee, ne, ie = false) {
var re, se;
if (!_.isTargetFile(ee)) return false;
const oe = await _.path2id(ee);
try {
let le = null;
if (ne) le = await _.localDatabase.get(oe, ne); else le = await _.localDatabase.get(oe);
const ue = null != (se = null != (re = null == le ? void 0 : le.deleted) ? re : le._deleted) ? se : void 0;
if (!ie && ue) return false;
if (le.type && "leaf" == le.type) return false;
if (!le.type || le.type && "notes" == le.type || "newnote" == le.type || "plain" == le.type) {
const _ = le;
let ne = [], ie = "plain";
if ("newnote" == le.type || "plain" == le.type) {
ne = le.children;
ie = le.type;
}
return {
data: "",
_id: _._id,
path: ee,
ctime: _.ctime,
mtime: _.mtime,
size: _.size,
_rev: le._rev,
_conflicts: le._conflicts,
children: ne,
datatype: ie,
deleted: ue,
type: ie,
eden: "eden" in le ? le.eden : {}
};
}
} catch (_) {
if (isErrorOfMissingDoc(_)) return false;
throw _;
}
return false;
}
async function getDBEntryFromMeta(_, ee, ne, ie = false, re = true, se = false) {
var oe, le, ue;
const de = _.id2path(ee._id, ee);
if (!_.isTargetFile(de)) return false;
const fe = stripAllPrefixes(de), he = null != (le = null != (oe = ee.deleted) ? oe : ee._deleted) ? le : void 0;
if (!ee.type || ee.type && "notes" == ee.type) {
const _ = ee, ne = {
data: _.data,
path: _.path,
_id: _._id,
ctime: _.ctime,
mtime: _.mtime,
size: _.size,
_rev: ee._rev,
_conflicts: ee._conflicts,
children: [],
datatype: "newnote",
deleted: he,
type: "newnote",
eden: "eden" in ee ? ee.eden : {}
};
if (ie) {
Logger("--Old fashioned document--");
Logger(ne);
}
return ne;
}
if ("newnote" == ee.type || "plain" == ee.type) {
if (ie) {
const ne = await _.localDatabase.get(ee._id, {
conflicts: true,
revs_info: true
});
Logger("-- Conflicts --");
Logger(null != (ue = ne._conflicts) ? ue : "No conflicts");
Logger("-- Revs info -- ");
Logger(ne._revs_info);
}
try {
if (ie) {
Logger("--Bare document--");
Logger(ee);
}
const ne = [ ...ee.children ], se = new Map;
if (ee.eden) Object.entries(ee.eden).forEach((([_, ee]) => se.set(_, ee.data)));
const oe = unique(ne).filter((_ => !se.has(_)));
if (0 != oe.length) if (_.isOnDemandChunkEnabled) {
const ne = await _.collectChunks(oe, false, re);
if (false === ne || ne.some((_ => "leaf" != _.type))) {
Logger(`Chunks of ${fe} (${ee._id.substring(0, 8)}) are not valid.`, LOG_LEVEL_NOTICE);
if (ne) Logger(`Missing chunks: ${ne.map((_ => _._id)).join(",")}`, LOG_LEVEL_VERBOSE);
return false;
}
ne.forEach((_ => se.set(_._id, _.data)));
} else try {
if (re) (await Promise.all(oe.map((ee => _.getDBLeaf(ee, re))))).forEach(((_, ee) => se.set(oe[ee], _))); else {
const ne = await _.localDatabase.allDocs({
keys: oe,
include_docs: true
});
if (ne.rows.some((_ => "error" in _))) {
const _ = ne.rows.filter((_ => "error" in _)).map((_ => _.key)).join(", ");
Logger(`Chunks of ${fe} (${ee._id.substring(0, 8)}) are not valid.`, LOG_LEVEL_NOTICE);
Logger(`Missing chunks: ${_}`, LOG_LEVEL_VERBOSE);
return false;
}
if (ne.rows.some((_ => _.doc && "leaf" != _.doc.type))) {
const _ = ne.rows.filter((_ => _.doc && "leaf" != _.doc.type)).map((_ => _.id)).join(", ");
Logger(`Chunks of ${fe} (${ee._id.substring(0, 8)}) are not valid.`, LOG_LEVEL_NOTICE);
Logger(`Corrupted chunks: ${_}`, LOG_LEVEL_VERBOSE);
return false;
}
ne.rows.forEach(((_, ee) => "doc" in _ && se.set(_.doc._id, _.doc.data)));
}
} catch (_) {
Logger(`Something went wrong on reading chunks of ${fe}(${ee._id.substring(0, 8)}) from database, see verbose info for detail.`, LOG_LEVEL_NOTICE);
Logger(_, LOG_LEVEL_VERBOSE);
return false;
}
const le = ne.map((_ => se.get(_)));
if (le.some((_ => void 0 === _))) throw new Error("Load failed");
const ue = {
data: le,
path: ee.path,
_id: ee._id,
ctime: ee.ctime,
mtime: ee.mtime,
size: ee.size,
_rev: ee._rev,
children: ee.children,
datatype: ee.type,
_conflicts: ee._conflicts,
eden: ee.eden,
deleted: he,
type: ee.type
};
if (ie) {
Logger("--Loaded Document--");
Logger(ue);
}
return ue;
} catch (_) {
if (isErrorOfMissingDoc(_)) {
Logger(`Missing document content!, could not read ${fe}(${ee._id.substring(0, 8)}) from database.`, LOG_LEVEL_NOTICE);
return false;
}
Logger(`Something went wrong on reading ${fe}(${ee._id.substring(0, 8)}) from database:`, LOG_LEVEL_NOTICE);
Logger(_);
}
}
return false;
}
async function getDBEntry(_, ee, ne, ie = false, re = true, se = false) {
const oe = await getDBEntryMeta(_, ee, ne, se);
if (oe) return await getDBEntryFromMeta(_, oe, ne, ie, re, se); else return false;
}
async function deleteDBEntry(_, ee, ne) {
var ie;
if (!_.isTargetFile(ee)) return false;
const re = await _.path2id(ee);
try {
return null != (ie = await serialized("file:" + ee, (async () => {
let ie = null;
if (ne) ie = await _.localDatabase.get(re, ne); else ie = await _.localDatabase.get(re);
const se = ne && "" != ("rev" in ne ? ne.rev : "");
if (ie.type && "leaf" == ie.type) return false;
if (!ie.type || ie.type && "notes" == ie.type) {
ie._deleted = true;
const ne = await _.localDatabase.put(ie, {
force: !se
});
Logger(`Entry removed:${ee} (${ie._id.substring(0, 8)}-${ne.rev})`);
return true;
}
if ("newnote" == ie.type || "plain" == ie.type) {
if (se) ie._deleted = true; else {
ie.deleted = true;
ie.mtime = Date.now();
if (_.settings.deleteMetadataOfDeletedFiles) ie._deleted = true;
}
const ne = await _.localDatabase.put(ie, {
force: !se
});
Logger(`Entry removed:${ee} (${ie._id.substring(0, 8)}-${ne.rev})`);
return true;
} else return false;
}))) ? ie : false;
} catch (_) {
if (isErrorOfMissingDoc(_)) return false;
throw _;
}
}
async function deleteDBEntryPrefix(_, ee) {
let ne = 0, ie = 0;
const re = [];
do {
const se = await _.localDatabase.allDocs({
include_docs: false,
skip: ne,
limit: 100,
conflicts: true
});
ie = se.rows.length;
if (ie > 0) for (const ne of se.rows) {
const ie = _.id2path(ne.id, ne.doc);
if (ie.startsWith(ee)) {
if (_.isTargetFile(ie)) re.push(ne.id);
} else if (!ne.id.startsWith("h:")) ;
}
ne += ie;
} while (0 != ie);
let se = 0, oe = 0;
for (const ee of re) try {
await serialized("file:" + ee, (async () => {
const ne = await _.localDatabase.get(ee);
if ("newnote" == ne.type || "plain" == ne.type) {
ne.deleted = true;
if (_.settings.deleteMetadataOfDeletedFiles) ne._deleted = true;
ne.mtime = Date.now();
} else ne._deleted = true;
await _.localDatabase.put(ne, {
force: true
});
}));
se++;
} catch (_) {
if (isErrorOfMissingDoc(_)) oe++; else throw _;
}
Logger(`deleteDBEntryPrefix:deleted ${se} items, skipped ${oe}`);
return true;
}
async function ensureRemoteIsCompatible(_, ee, ne, ie, re) {
var se, oe;
const le = {
_id: MILSTONE_DOCID,
type: "milestoneinfo",
created: new Date / 1,
locked: false,
accepted_nodes: [ ne ],
node_chunk_info: {
[ne]: ie
},
tweak_values: {}
};
let ue = _;
if (!ue) ue = le;
const de = extractObject(TweakValuesTemplate, ee);
ue.node_chunk_info = {
...le.node_chunk_info,
...ue.node_chunk_info
};
if (ue.node_chunk_info[ne].min != ie.min || ue.node_chunk_info[ne].max != ie.max || isObjectDifferent(null == (se = ue.tweak_values) ? void 0 : se[ne], de) || "undefined" == typeof ue._rev) {
ue.node_chunk_info[ne].min = ie.min;
ue.node_chunk_info[ne].max = ie.max;
ue.tweak_values = {
...null != (oe = ue.tweak_values) ? oe : {},
[ne]: de
};
await re(ue);
}
let fe = ie.min, he = ie.max;
for (const _ of ue.accepted_nodes) if (_ != ne) if (_ in ue.node_chunk_info) {
const ee = ue.node_chunk_info[_];
fe = Math.max(ee.min, fe);
he = Math.min(ee.max, he);
} else {
fe = 0;
he = 0;
}
if (he < fe) if (!ee.ignoreVersionCheck) return "INCOMPATIBLE";
if (!ee.disableCheckingConfigMismatch) {
const _ = Object.entries(ue.tweak_values).filter((([_, ee]) => isObjectDifferent(de, ee))).map((([_, ee]) => ({
key: _,
all: ee,
recommended: extractObject(TweakValuesRecommendedTemplate, ee),
shouldBeMatched: extractObject(TweakValuesShouldMatchedTemplate, ee)
}))), ee = _.map((_ => _.all)), ne = extractObject(TweakValuesShouldMatchedTemplate, de);
for (const ie of _) if (isObjectDifferent(ie.shouldBeMatched, ne, true)) return [ "MISMATCHED", ee ];
}
if (ue.locked) {
if (-1 == ue.accepted_nodes.indexOf(ne)) if (ue.cleaned) return "NODE_CLEANED"; else return "NODE_LOCKED";
return "LOCKED";
}
return "OK";
}
async function ensureDatabaseIsCompatible(_, ee, ne, ie) {
const re = await resolveWithIgnoreKnownError(_.get(MILSTONE_DOCID), false);
return await ensureRemoteIsCompatible(re, ee, ne, ie, (async ee => {
await _.put(ee);
}));
}
var LiveSyncAbstractReplicator = class {
constructor(_) {
this.syncStatus = "NOT_CONNECTED";
this.docArrived = 0;
this.docSent = 0;
this.lastSyncPullSeq = 0;
this.maxPullSeq = 0;
this.lastSyncPushSeq = 0;
this.maxPushSeq = 0;
this.nodeid = "";
this.remoteLocked = false;
this.remoteCleaned = false;
this.remoteLockedAndDeviceNotAccepted = false;
this.tweakSettingsMismatched = false;
this.mismatchedTweakValues = [];
this.updateInfo = () => {
this.env.replicationStat.value = {
sent: this.docSent,
arrived: this.docArrived,
maxPullSeq: this.maxPullSeq,
maxPushSeq: this.maxPushSeq,
lastSyncPullSeq: this.lastSyncPullSeq,
lastSyncPushSeq: this.lastSyncPushSeq,
syncStatus: this.syncStatus
};
};
this.env = _;
}
async initializeDatabaseForReplication() {
const _ = this.env.getDatabase();
try {
const ee = await resolveWithIgnoreKnownError(_.get(NODEINFO_DOCID), {
_id: NODEINFO_DOCID,
type: "nodeinfo",
nodeid: "",
v20220607: true
});
if ("" == ee.nodeid) {
ee.nodeid = Math.random().toString(36).slice(-10);
await _.put(ee);
}
this.nodeid = ee.nodeid;
return true;
} catch (_) {
Logger(_);
}
return false;
}
}, currentVersionRange = {
min: 0,
max: 2,
current: 2
}, selectorOnDemandPull = {
selector: {
type: {
$ne: "leaf"
}
}
}, selectorOnDemandPush = {};
async function* genReplication(_, ee) {
const ne = [];
let locker = () => Promise.resolve(), unlock = () => {
locker = () => new Promise((_ => unlock = _));
};
unlock();
const push = function(_) {
ne.push(_);
unlock();
};
_.on("complete", (_ => push([ "complete", _ ])));
_.on("change", (_ => push([ "change", _ ])));
_.on("active", (() => push([ "active" ])));
_.on("denied", (_ => push([ "denied", _ ])));
_.on("error", (_ => push([ "error", _ ])));
_.on("paused", (_ => push([ "paused", _ ])));
_.then((() => push([ "finally" ]))).catch((() => push([ "finally" ])));
try {
e: for (;;) {
const _ = ne.shift();
if (!_) {
const dx = async () => {
await locker();
return true;
};
for (;;) {
const timeout = async () => {
await delay(100);
return false;
};
if (await Promise.race([ dx(), timeout() ])) continue e;
if (ee.aborted) break e;
}
} else {
yield _;
if ("finally" == _[0]) break;
}
}
} finally {
_.cancel();
}
}
var LiveSyncCouchDBReplicator = class extends LiveSyncAbstractReplicator {
constructor(_) {
super(_);
this.syncStatus = "NOT_CONNECTED";
this.docArrived = 0;
this.docSent = 0;
this.lastSyncPullSeq = 0;
this.maxPullSeq = 0;
this.lastSyncPushSeq = 0;
this.maxPushSeq = 0;
this.nodeid = "";
this.remoteLocked = false;
this.remoteCleaned = false;
this.remoteLockedAndDeviceNotAccepted = false;
this.updateInfo = () => {
this.env.replicationStat.value = {
sent: this.docSent,
arrived: this.docArrived,
maxPullSeq: this.maxPullSeq,
maxPushSeq: this.maxPushSeq,
lastSyncPullSeq: this.lastSyncPullSeq,
lastSyncPushSeq: this.lastSyncPushSeq,
syncStatus: this.syncStatus
};
};
this.env = _;
this.initializeDatabaseForReplication();
this.env.getDatabase().on("close", (() => {
this.closeReplication();
}));
}
async migrate(_, ee) {
Logger(`Database updated from ${_} to ${ee}`, LOG_LEVEL_NOTICE);
return true;
}
terminateSync() {
if (this.controller) {
this.controller.abort();
this.controller = void 0;
}
}
async openReplication(_, ee, ne, ie) {
await this.initializeDatabaseForReplication();
if (ee) this.openContinuousReplication(_, ne, false); else return this.openOneShotReplication(_, ne, false, "sync", ie);
}
replicationActivated(_) {
this.syncStatus = "CONNECTED";
this.updateInfo();
Logger("Replication activated", _ ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO, "sync");
}
async replicationChangeDetected(_, ee, ne, ie) {
try {
if ("pull" == _.direction) {
await this.env.processReplication(_.change.docs);
this.docArrived += _.change.docs.length;
} else this.docSent += _.change.docs.length;
if (ee) {
const _ = this.maxPullSeq, ee = this.maxPushSeq, re = this.lastSyncPullSeq, se = this.lastSyncPushSeq, oe = 0 == se ? "" : se >= ee ? " (LIVE)" : ` (${ee - se})`, le = 0 == re ? "" : re >= _ ? " (LIVE)" : ` (${_ - re})`;
Logger(`↑${this.docSent - ne}${oe} ↓${this.docArrived - ie}${le}`, LOG_LEVEL_NOTICE, "sync");
}
this.updateInfo();
} catch (_) {
Logger("Replication callback error", LOG_LEVEL_NOTICE, "sync");
Logger(_, LOG_LEVEL_VERBOSE);
}
}
replicationCompleted(_) {
this.syncStatus = "COMPLETED";
this.updateInfo();
Logger("Replication completed", _ ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO, _ ? "sync" : "");
this.terminateSync();
}
replicationDenied(_) {
this.syncStatus = "ERRORED";
this.updateInfo();
this.terminateSync();
Logger("Replication denied", LOG_LEVEL_NOTICE, "sync");
Logger(_, LOG_LEVEL_VERBOSE);
}
replicationErrored(_) {
this.syncStatus = "ERRORED";
this.terminateSync();
this.updateInfo();
Logger("Replication error", LOG_LEVEL_NOTICE, "sync");
Logger(_, LOG_LEVEL_VERBOSE);
}
replicationPaused() {
this.syncStatus = "PAUSED";
this.updateInfo();
Logger("Replication paused", LOG_LEVEL_VERBOSE, "sync");
}
async processSync(_, ee, ne, ie, re, se, oe = true) {
const le = new AbortController;
if (this.controller) this.controller.abort();
this.controller = le;
const ue = genReplication(_, le.signal);
try {
for await (const [_, oe] of ue) {
const le = await globalConcurrencyController.tryAcquire(1, REPLICATION_BUSY_TIMEOUT);
if (false === le) {
Logger("Replication stopped for busy.", ee ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO, "sync");
return "FAILED";
}
le();
switch (_) {
case "change":
if ("direction" in oe) {
if ("pull" == oe.direction) this.lastSyncPullSeq = Number(`${oe.change.last_seq}`.split("-")[0]); else this.lastSyncPushSeq = Number(`${oe.change.last_seq}`.split("-")[0]);
await this.replicationChangeDetected(oe, ee, ne, ie);
} else if ("pullOnly" == re) {
this.lastSyncPullSeq = Number(`${oe.last_seq}`.split("-")[0]);
await this.replicationChangeDetected({
direction: "pull",
change: oe
}, ee, ne, ie);
} else if ("pushOnly" == re) {
this.lastSyncPushSeq = Number(`${oe.last_seq}`.split("-")[0]);
this.updateInfo();
await this.replicationChangeDetected({
direction: "push",
change: oe
}, ee, ne, ie);
}
if (se) if (this.docSent - ne + (this.docArrived - ie) > 2 * this.originalSetting.batch_size) return "NEED_RESURRECT";
break;
case "complete":
this.replicationCompleted(ee);
return "DONE";
case "active":
this.replicationActivated(ee);
break;
case "denied":
this.replicationDenied(oe);
return "FAILED";
case "error":
this.replicationErrored(oe);
Logger("Replication stopped.", ee ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO, "sync");
if (this.env.getLastPostFailedBySize()) {
if (oe && 413 == (null == oe ? void 0 : oe.status)) {
Logger("Something went wrong during synchronisation. Please check the log!", LOG_LEVEL_NOTICE);
return "FAILED";
}
return "NEED_RETRY";
} else {
Logger("Replication error", LOG_LEVEL_NOTICE, "sync");
Logger(oe);
}
return "FAILED";
case "paused":
this.replicationPaused();
break;
case "finally":
break;
default:
Logger(`Unexpected synchronization status:${JSON.stringify(oe)}`);
}
}
if (oe) return "DONE"; else return "CANCELLED";
} catch (_) {
Logger("Unexpected synchronization exception");
Logger(_, LOG_LEVEL_VERBOSE);
return "FAILED";
} finally {
this.terminateSync();
this.controller = void 0;
}
}
async openOneShotReplication(_, ee, ne, ie, re = false) {
const se = await shareRunningResult("oneShotReplication", (async () => {
if (this.controller) {
Logger("Replication is already in progress.", ee ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO, "sync");
return false;
}
const se = this.env.getDatabase();
Logger(`OneShot Sync begin... (${ie})`);
const oe = await this.checkReplicationConnectivity(_, false, ne, ee, re);
if (false === oe) {
Logger("Could not connect to server.", ee ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO, "sync");
return false;
}
this.maxPullSeq = Number(`${oe.info.update_seq}`.split("-")[0]);
this.maxPushSeq = Number(`${(await se.info()).update_seq}`.split("-")[0]);
if (ee) Logger("Looking for the point last synchronized point.", LOG_LEVEL_NOTICE, "sync");
const {db: le, syncOptionBase: ue} = oe;
this.syncStatus = "STARTED";
this.updateInfo();
const de = this.docArrived, fe = this.docSent;
if (!ne) this.originalSetting = _;
this.terminateSync();
const he = "sync" == ie ? se.sync(le, {
...ue
}) : "pullOnly" == ie ? se.replicate.from(le, {
...ue,
..._.readChunksOnline ? selectorOnDemandPull : {}
}) : "pushOnly" == ie ? se.replicate.to(le, {
...ue,
..._.readChunksOnline ? selectorOnDemandPush : {}
}) : void 0, pe = await this.processSync(he, ee, fe, de, ie, ne, false);
if ("DONE" == pe) return true;
if ("CANCELLED" == pe) return false;
if ("FAILED" == pe) return false;
if ("NEED_RESURRECT" == pe) {
this.terminateSync();
return async () => await this.openOneShotReplication(this.originalSetting, ee, false, ie, re);
}
if ("NEED_RETRY" == pe) {
const ne = JSON.parse(JSON.stringify(_));
ne.batch_size = Math.ceil(ne.batch_size / 2) + 2;
ne.batches_limit = Math.ceil(ne.batches_limit / 2) + 2;
if (ne.batch_size <= 5 && ne.batches_limit <= 5) {
Logger("We can't replicate more lower value.", ee ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO);
return false;
} else {
Logger(`Retry with lower batch size:${ne.batch_size}/${ne.batches_limit}`, ee ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO);
return async () => await this.openOneShotReplication(ne, ee, true, ie, re);
}
}
return false;
}));
if ("boolean" == typeof se) return se; else return await se();
}
replicateAllToServer(_, ee) {
return this.openOneShotReplication(_, null != ee ? ee : false, false, "pushOnly");
}
replicateAllFromServer(_, ee) {
return this.openOneShotReplication(_, null != ee ? ee : false, false, "pullOnly");
}
async checkReplicationConnectivity(_, ee, ne, ie, re = false) {
if ("" != _.versionUpFlash) {
Logger("Open settings and check message, please.", LOG_LEVEL_NOTICE);
return false;
}
const se = _.couchDB_URI + ("" == _.couchDB_DBNAME ? "" : "/" + _.couchDB_DBNAME);
if (this.controller) {
Logger("Another replication running.");
return false;
}
const oe = await this.connectRemoteCouchDBWithSetting(_, this.env.getIsMobile(), true);
if ("string" == typeof oe) {
Logger(`Could not connect to ${se}: ${oe}`, ie ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO);
return false;
}
if (!ne) {
if (!await checkRemoteVersion(oe.db, this.migrate.bind(this), VER)) {
Logger("Remote database is newer or corrupted, make sure to latest version of self-hosted-livesync installed", LOG_LEVEL_NOTICE);
return false;
}
this.remoteCleaned = false;
this.remoteLocked = false;
this.remoteLockedAndDeviceNotAccepted = false;
this.tweakSettingsMismatched = false;
this.mismatchedTweakValues = [];
const ee = await ensureDatabaseIsCompatible(oe.db, _, this.nodeid, currentVersionRange);
if ("INCOMPATIBLE" == ee) {
Logger("The remote database has no compatibility with the running version. Please upgrade the plugin.", LOG_LEVEL_NOTICE);
return false;
} else if ("NODE_LOCKED" == ee) {
Logger("The remote database has been rebuilt or corrupted since we have synchronized last time. Fetch rebuilt DB, explicit unlocking or chunk clean-up is required.", LOG_LEVEL_NOTICE);
this.remoteLockedAndDeviceNotAccepted = true;
this.remoteLocked = true;
return false;
} else if ("LOCKED" == ee) this.remoteLocked = true; else if ("NODE_CLEANED" == ee) if (re) this.remoteLocked = true; else {
Logger("The remote database has been cleaned up. Fetch rebuilt DB, explicit unlocking or chunk clean-up is required.", LOG_LEVEL_NOTICE);
this.remoteLockedAndDeviceNotAccepted = true;
this.remoteLocked = true;
this.remoteCleaned = true;
return false;
} else if ("MISMATCHED" == ee[0]) {
Logger("Configuration mismatching between the clients has been detected. This can be harmful or extra capacity consumption. We have to make these value unified.", LOG_LEVEL_NOTICE);
this.tweakSettingsMismatched = true;
this.mismatchedTweakValues = ee[1];
return false;
}
}
const le = {
batches_limit: _.batches_limit,
batch_size: _.batch_size
};
if (_.readChunksOnline) {
le.push = {
...selectorOnDemandPush
};
le.pull = {
...selectorOnDemandPull
};
}
const ue = ee ? {
live: true,
retry: true,
heartbeat: _.useTimeouts ? false : 3e4,
...le
} : {
...le
};
return {
db: oe.db,
info: oe.info,
syncOptionBase: le,
syncOption: ue
};
}
async openContinuousReplication(_, ee, ne) {
const ie = await shareRunningResult("continuousReplication", (async () => {
if (this.controller) {
Logger("Replication is already in progress.", ee ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO);
return false;
}
const ie = this.env.getDatabase();
Logger("Before LiveSync, start OneShot once...");
if (await this.openOneShotReplication(_, ee, false, "pullOnly")) {
Logger("LiveSync begin...");
const re = await this.checkReplicationConnectivity(_, true, true, ee);
if (false === re) {
Logger("Could not connect to server.", ee ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO);
return false;
}
if (ee) Logger("Looking for the point last synchronized point.", LOG_LEVEL_NOTICE, "sync");
const {db: se, syncOption: oe} = re;
this.syncStatus = "STARTED";
this.maxPullSeq = Number(`${re.info.update_seq}`.split("-")[0]);
this.maxPushSeq = Number(`${(await ie.info()).update_seq}`.split("-")[0]);
this.updateInfo();
const le = this.docArrived, ue = this.docSent;
if (!ne) this.originalSetting = _;
this.terminateSync();
const de = ie.sync(se, {
...oe
}), fe = "sync", he = await this.processSync(de, ee, ue, le, fe, ne);
if ("DONE" == he) return true;
if ("FAILED" == he) return false;
if ("NEED_RESURRECT" == he) {
this.terminateSync();
return async () => await this.openContinuousReplication(this.originalSetting, ee, false);
}
if ("NEED_RETRY" == he) {
const ne = JSON.parse(JSON.stringify(_));
ne.batch_size = Math.ceil(ne.batch_size / 2) + 2;
ne.batches_limit = Math.ceil(ne.batches_limit / 2) + 2;
if (ne.batch_size <= 5 && ne.batches_limit <= 5) {
Logger("We can't replicate more lower value.", ee ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO);
return false;
} else {
Logger(`Retry with lower batch size:${ne.batch_size}/${ne.batches_limit}`, ee ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO);
return async () => await this.openContinuousReplication(ne, ee, true);
}
}
}
return false;
}));
if ("boolean" == typeof ie) return ie; else return await ie();
}
closeReplication() {
if (this.controller) {
this.controller.abort();
this.controller = void 0;
this.syncStatus = "CLOSED";
Logger("Replication closed");
this.updateInfo();
}
}
async tryResetRemoteDatabase(_) {
this.closeReplication();
const ee = await this.connectRemoteCouchDBWithSetting(_, this.env.getIsMobile(), true);
if ("string" != typeof ee) try {
await ee.db.destroy();
Logger("Remote Database Destroyed", LOG_LEVEL_NOTICE);
await this.tryCreateRemoteDatabase(_);
} catch (_) {
Logger("Something happened on Remote Database Destroy:", LOG_LEVEL_NOTICE);
Logger(_, LOG_LEVEL_NOTICE);
}
}
async tryCreateRemoteDatabase(_) {
this.closeReplication();
if ("string" != typeof await this.connectRemoteCouchDBWithSetting(_, this.env.getIsMobile(), true)) Logger("Remote Database Created or Connected", LOG_LEVEL_NOTICE);
}
async markRemoteLocked(_, ee, ne) {
const ie = _.couchDB_URI + ("" == _.couchDB_DBNAME ? "" : "/" + _.couchDB_DBNAME), re = await this.connectRemoteCouchDBWithSetting(_, this.env.getIsMobile(), true);
if ("string" == typeof re) {
Logger(`could not connect to ${ie}:${re}`, LOG_LEVEL_NOTICE);
return;
}
if (!await checkRemoteVersion(re.db, this.migrate.bind(this), VER)) {
Logger("Remote database is newer or corrupted, make sure to latest version of self-hosted-livesync installed", LOG_LEVEL_NOTICE);
return;
}
const se = {
_id: MILSTONE_DOCID,
type: "milestoneinfo",
created: new Date / 1,
locked: ee,
cleaned: ne,
accepted_nodes: [ this.nodeid ],
node_chunk_info: {
[this.nodeid]: currentVersionRange
},
tweak_values: {}
}, oe = {
...se,
...await resolveWithIgnoreKnownError(re.db.get(MILSTONE_DOCID), se)
};
oe.node_chunk_info = {
...se.node_chunk_info,
...oe.node_chunk_info
};
oe.accepted_nodes = [ this.nodeid ];
oe.locked = ee;
oe.cleaned = oe.cleaned || ne;
if (ee) Logger("Lock remote database to prevent data corruption", LOG_LEVEL_NOTICE); else Logger("Unlock remote database to prevent data corruption", LOG_LEVEL_NOTICE);
await re.db.put(oe);
}
async markRemoteResolved(_) {
const ee = _.couchDB_URI + ("" == _.couchDB_DBNAME ? "" : "/" + _.couchDB_DBNAME), ne = await this.connectRemoteCouchDBWithSetting(_, this.env.getIsMobile(), true);
if ("string" == typeof ne) {
Logger(`could not connect to ${ee}:${ne}`, LOG_LEVEL_NOTICE);
return;
}
if (!await checkRemoteVersion(ne.db, this.migrate.bind(this), VER)) {
Logger("Remote database is newer or corrupted, make sure to latest version of self-hosted-livesync installed", LOG_LEVEL_NOTICE);
return;
}
const ie = {
_id: MILSTONE_DOCID,
type: "milestoneinfo",
created: new Date / 1,
locked: false,
accepted_nodes: [ this.nodeid ],
node_chunk_info: {
[this.nodeid]: currentVersionRange
},
tweak_values: {}
}, re = {
...ie,
...await resolveWithIgnoreKnownError(ne.db.get(MILSTONE_DOCID), ie)
};
re.node_chunk_info = {
...ie.node_chunk_info,
...re.node_chunk_info
};
re.accepted_nodes = Array.from(new Set([ ...re.accepted_nodes, this.nodeid ]));
Logger("Mark this device as 'resolved'.", LOG_LEVEL_NOTICE);
await ne.db.put(re);
}
connectRemoteCouchDBWithSetting(_, ee, ne = false, ie = false) {
if (_.encrypt && "" == _.passphrase && !_.permitEmptyPassphrase) return "Empty passphrases cannot be used without explicit permission"; else return this.env.connectRemoteCouchDB(_.couchDB_URI + ("" == _.couchDB_DBNAME ? "" : "/" + _.couchDB_DBNAME), {
username: _.couchDB_USER,
password: _.couchDB_PASSWORD
}, _.disableRequestURI || ee, _.encrypt ? _.passphrase : _.encrypt, _.useDynamicIterationCount, ne, ie, _.enableCompression);
}
async fetchRemoteChunks(_, ee) {
const ne = await this.connectRemoteCouchDBWithSetting(this.env.getSettings(), this.env.getIsMobile(), false, true);
if ("string" == typeof ne) {
Logger(`Could not connect to server.${ne} `, ee ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO, "fetch");
return false;
}
const ie = await ne.db.allDocs({
keys: _,
include_docs: true
});
if (ie.rows.some((_ => "error" in _))) {
Logger("Some chunks are not exists both on remote and local database.", ee ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO, "fetch");
return false;
}
return ie.rows.map((_ => _.doc));
}
async tryConnectRemote(_, ee = true) {
const ne = await this.connectRemoteCouchDBWithSetting(_, this.env.getIsMobile(), true);
if ("string" == typeof ne) {
Logger(`ERROR!: could not connect to ${_.couchDB_URI} : ${_.couchDB_DBNAME} \n(${ne})`, LOG_LEVEL_NOTICE);
return false;
}
Logger(`Connected to ${ne.info.db_name} successfully`, LOG_LEVEL_NOTICE);
return true;
}
async resetRemoteTweakSettings(_) {
const ee = _.couchDB_URI + ("" == _.couchDB_DBNAME ? "" : "/" + _.couchDB_DBNAME), ne = await this.connectRemoteCouchDBWithSetting(_, this.env.getIsMobile(), true);
if ("string" != typeof ne) if (await checkRemoteVersion(ne.db, this.migrate.bind(this), VER)) try {
const _ = await ne.db.get(MILSTONE_DOCID);
_.tweak_values = {};
await ne.db.put(_);
Logger("tweak values on the remote database have been cleared", LOG_LEVEL_VERBOSE);
} catch (_) {
Logger("Could not retrieve remote milestone", LOG_LEVEL_NOTICE);
throw _;
} else Logger("Remote database is newer or corrupted, make sure to latest version of self-hosted-livesync installed", LOG_LEVEL_NOTICE); else Logger(`could not connect to ${ee}:${ne}`, LOG_LEVEL_NOTICE);
}
async compactRemote(_) {
const ee = _.couchDB_URI + ("" == _.couchDB_DBNAME ? "" : "/" + _.couchDB_DBNAME), ne = await this.connectRemoteCouchDBWithSetting(_, this.env.getIsMobile(), true);
if ("string" == typeof ne) {
Logger(`could not connect to ${ee}:${ne}`, LOG_LEVEL_NOTICE);
return false;
}
return (await ne.db.compact({
interval: 1e3
})).ok;
}
}, LANG_DE = "de", LANG_JA = "ja", LANG_RU = "ru", LANG_ZH = "zh", LANG_ZH_TW = "zh-tw", SUPPORTED_I18N_LANGS = [ LANG_DE, LANG_JA, LANG_RU, LANG_ZH, LANG_ZH_TW ], allMessages = {
"Self-hosted LiveSync has undergone a major upgrade. Please open the setting dialog, and check the information pane.": {
ja: "Self-hosted LiveSyncにメジャーバージョンアップがありました。設定を開き、Information paneを確認してください",
zh: "Self-hosted LiveSync 已经进行了重大升级。请打开设置对话框,检查信息面板。"
},
"lang-de": {
def: "Deutsche"
},
"lang-ja": {
def: "日本語"
},
"lang-ru": {
def: "Русский"
},
"lang-zh": {
def: "简体中文"
},
"lang-zh-tw": {
def: "繁體中文"
},
"Self-hosted LiveSync": {
zh: "自托管 LiveSync"
},
"Remote Type": {
zh: "远程类型"
},
"Remote server type": {
zh: "远程服务器类型"
},
"Endpoint URL": {
zh: "终端节点网址"
},
"Access Key": {
zh: "访问密钥ID"
},
"Secret Key": {
zh: "访问密钥密码"
},
Region: {
zh: "地域"
},
"Bucket Name": {
zh: "存储桶名称"
},
"Use Custom HTTP Handler": {
zh: "使用自定义HTTP处理程序"
},
"If your Object Storage could not configured accepting CORS, enable this.": {
zh: "如果您的对象存储无法配置接受CORS,请启用此功能。"
},
URI: {
zh: "URI"
},
Username: {
zh: "用户名"
},
username: {
zh: "用户名"
},
Password: {
zh: "密码"
},
password: {
zh: "密码"
},
"Database name": {
zh: "数据库名称"
},
"Incubate Chunks in Document": {
zh: "在文档中孵化块"
},
"If enabled, newly created chunks are temporarily kept within the document, and graduated to become independent chunks once stabilised.": {
zh: "如果启用,新创建的数据块将暂时保留在文档中,并在稳定后成为独立数据块。"
},
"Maximum Incubating Chunks": {
zh: "最大孵化块数"
},
"The maximum number of chunks that can be incubated within the document. Chunks exceeding this number will immediately graduate to independent chunks.": {
zh: "文档中可以孵化的数据块的最大数量。超过此数量的数据块将立即成为独立数据块。"
},
"Maximum Incubating Chunk Size": {
zh: "最大孵化块大小"
},
"The maximum total size of chunks that can be incubated within the document. Chunks exceeding this size will immediately graduate to independent chunks.": {
zh: "文档中可以孵化的数据块的最大尺寸。超过此大小的数据块将立即成为独立数据块。"
},
"Maximum Incubation Period": {
zh: "最大孵化期限"
},
"The maximum duration for which chunks can be incubated within the document. Chunks exceeding this period will graduate to independent chunks.": {
zh: "文档中可以孵化的数据块的最大持续时间。超过此时间的数据块将成为独立数据块。"
},
"Data Compression": {
zh: "数据压缩"
},
"End-to-End Encryption": {
zh: "端到端加密"
},
"Encrypt contents on the remote database. If you use the plugin's synchronization feature, enabling this is recommend.": {
zh: "加密远程数据库中的内容。如果您使用插件的同步功能,则建议启用此功能。"
},
Passphrase: {
zh: "口令"
},
"Encrypting passphrase. If you change the passphrase of an existing database, overwriting the remote database is strongly recommended.": {
zh: "加密口令。如果更改现有数据库的口令,则强烈建议覆盖远程数据库。"
},
"Path Obfuscation": {
zh: "路径混淆"
},
"Use dynamic iteration count": {
zh: "使用动态迭代次数"
},
"Display Language": {
zh: "显示语言"
},
'Not all messages have been translated. And, please revert to "Default" when reporting errors.': {
ja: 'すべてのメッセージが翻訳されているわけではありません。また、Issue報告の際にはいったん"Default"に戻してください',
zh: '并非所有消息都已翻译。请在报告错误时恢复为"Default"'
},
"Show status inside the editor": {
zh: "在编辑器内显示状态"
},
"Reflected after reboot": {
zh: "重启后生效"
},
"Show status as icons only": {
zh: "仅以图标显示状态"
},
"Show status on the status bar": {
zh: "在状态栏上显示状态"
},
"Reflected after reboot.": {
zh: "重启后生效"
},
"Show only notifications": {
zh: "仅显示通知"
},
"Prevent logging and show only notification": {
zh: "阻止记录日志并仅显示通知"
},
"Verbose Log": {
zh: "详细日志"
},
"Show verbose log": {
zh: "显示详细日志"
},
"Memory cache size (by total items)": {
zh: "内存缓存大小(按总项目数)"
},
"Memory cache size (by total characters)": {
zh: "内存缓存大小(按总字符数)"
},
"(Mega chars)": {
zh: "(百万字符)"
},
Filename: {
zh: "文件名"
},
"If you set this, all settings are saved in a markdown file. You will be notified when new settings arrive. You can set different files by the platform.": {
zh: "如果设置了此项,所有设置都将保存在一个Markdown文件中。当新设置到达时,您将收到通知。您可以根据平台设置不同的文件。"
},
"Write credentials in the file": {
zh: "将凭据写入文件"
},
"(Not recommended) If set, credentials will be stored in the file.": {
zh: "(不建议)如果设置,凭据将存储在文件中。"
},
"Notify all setting files": {
zh: "通知所有设置文件"
},
"Encrypting sensitive configuration items": {
zh: "加密敏感配置项"
},
"Passphrase of sensitive configuration items": {
zh: "敏感配置项的口令"
},
"This passphrase will not be copied to another device. It will be set to `Default` until you configure it again.": {
zh: "此口令不会复制到另一台设备。在您再次配置之前,它将设置为`Default`。"
},
Presets: {
zh: "预设"
},
"Apply preset configuration": {
zh: "应用预设配置"
},
"Sync Mode": {
zh: "同步模式"
},
"Periodic Sync interval": {
zh: "定期同步间隔"
},
"Interval (sec)": {
zh: "间隔(秒)"
},
"Sync on Save": {
zh: "保存时同步"
},
"When you save a file, sync automatically": {
zh: "保存文件时,自动同步"
},
"Sync on Editor Save": {
zh: "编辑器保存时同步"
},
"When you save a file in the editor, sync automatically": {
zh: "在编辑器中保存文件时,自动同步"
},
"Sync on File Open": {
zh: "打开文件时同步"
},
"When you open a file, sync automatically": {
zh: "打开文件时,自动同步"
},
"Sync on Start": {
zh: "启动时同步"
},
"Start synchronization after launching Obsidian.": {
zh: "启动Obsidian后开始同步"
},
"Sync after merging file": {
zh: "合并文件后同步"
},
"Sync automatically after merging files": {
zh: "合并文件后自动同步"
},
"Use the trash bin": {
zh: "使用回收站"
},
"Do not delete files that are deleted in remote, just move to trash.": {
zh: "不删除被远程删除的文件,只是移动到回收站"
},
"Keep empty folder": {
zh: "保留空文件夹"
},
"Normally, a folder is deleted when it becomes empty after a synchronization. Enabling this will prevent it from getting deleted": {
zh: "通常,同步后,文件夹变为空时会被删除。启用此功能将阻止其被删除"
},
"Always overwrite with a newer file (beta)": {
zh: "始终使用更新的文件覆盖(测试版)"
},
"(Def off) Resolve conflicts by newer files automatically.": {
zh: "(默认关闭)自动使用更新的文件解决冲突"
},
"Postpone resolution of inactive files": {
zh: "推迟解决不活动文件"
},
"Postpone manual resolution of inactive files": {
zh: "推迟手动解决不活动文件"
},
"Always resolve conflicts manually": {
zh: "始终手动解决冲突"
},
"If this switch is turned on, a merge dialog will be displayed, even if the sensible-merge is possible automatically. (Turn on to previous behavior)": {
zh: "如果打开此开关,即使可以自动进行合并,也会显示合并对话框。(打开可恢复到以前的行为)"
},
"Always reflect synchronized changes even if the note has a conflict": {
zh: "即使笔记存在冲突,也始终反映同步的更改"
},
"Turn on to previous behavior": {
zh: "打开可恢复到以前的行为"
},
"Scan for hidden files before replication": {
zh: "复制前扫描隐藏文件"
},
"Scan hidden files periodically": {
zh: "定期扫描隐藏文件"
},
"Seconds, 0 to disable": {
zh: "秒,0为禁用"
},
"Batch database update": {
zh: "批量数据库更新"
},
"Reducing the frequency with which on-disk changes are reflected into the DB": {
zh: "降低将磁盘上的更改反映到数据库中的频率"
},
"Enhance chunk size": {
zh: "增强块大小"
},
"Fetch chunks on demand": {
zh: "按需获取块"
},
"(ex. Read chunks online) If this option is enabled, LiveSync reads chunks online directly instead of replicating them locally. Increasing Custom chunk size is recommended.": {
zh: "(例如,在线读取块)如果启用此选项,LiveSync将直接在线读取块,而不是在本地复制块。建议增加自定义块大小"
},
"Maximum file size": {
zh: "最大文件大小"
},
"(MB) If this is set, changes to local and remote files that are larger than this will be skipped. If the file becomes smaller again, a newer one will be used.": {
zh: "(MB)如果设置了此项,大于此大小的本地和远程文件的更改将被跳过。如果文件再次变小,将使用更新的文件"
},
"(Beta) Use ignore files": {
zh: "(测试版)使用忽略文件"
},
"If this is set, changes to local files which are matched by the ignore files will be skipped. Remote changes are determined using local ignore files.": {
zh: "如果设置了此项,与忽略文件匹配的本地文件的更改将被跳过。远程更改使用本地忽略文件确定"
},
"Ignore files": {
zh: "忽略文件"
},
"We can use multiple ignore files, e.g.) `.gitignore, .dockerignore`": {
zh: "我们可以使用多个忽略文件,例如`.gitignore, .dockerignore`"
},
"Batch size": {
zh: "批量大小"
},
"Number of change feed items to process at a time. Defaults to 50. Minimum is 2.": {
zh: "一次处理的更改源项目数。默认为50。最小为2"
},
"Batch limit": {
zh: "批量限制"
},
"Number of batches to process at a time. Defaults to 40. Minimum is 2. This along with batch size controls how many docs are kept in memory at a time.": {
zh: "一次处理的批量数。默认为40。最小为2。这与批量大小一起控制一次在内存中保留多少文档"
},
"Use timeouts instead of heartbeats": {
zh: "使用超时而不是心跳"
},
"If this option is enabled, PouchDB will hold the connection open for 60 seconds, and if no change arrives in that time, close and reopen the socket, instead of holding it open indefinitely. Useful when a proxy limits request duration but can increase resource usage.": {
zh: "如果启用此选项,PouchDB将保持连接打开60秒,如果在此时间内没有更改到达,则关闭并重新打开套接字,而不是无限期保持打开。当代理限制请求持续时间时有用,但可能会增加资源使用"
},
"Batch size of on-demand fetching": {
zh: "按需获取的批量大小"
},
"The delay for consecutive on-demand fetches": {
zh: "连续按需获取的延迟"
},
"Suspend file watching": {
zh: "暂停文件监视"
},
"Stop watching for file change.": {
zh: "停止监视文件更改"
},
"Suspend database reflecting": {
zh: "暂停数据库反映"
},
"Stop reflecting database changes to storage files.": {
zh: "停止将数据库更改反映到存储文件"
},
"Write logs into the file": {
zh: "将日志写入文件"
},
"Warning! This will have a serious impact on performance. And the logs will not be synchronised under the default name. Please be careful with logs; they often contain your confidential information.": {
zh: "警告!这将严重影响性能。并且日志不会以默认名称同步。请小心处理日志;它们通常包含您的敏感信息"
},
"Do not keep metadata of deleted files.": {
zh: "不保留已删除文件的元数据"
},
"Delete old metadata of deleted files on start-up": {
zh: "启动时删除已删除文件的旧元数据"
},
"(Days passed, 0 to disable automatic-deletion)": {
zh: "(天数,0为禁用自动删除)"
},
"Use an old adapter for compatibility": {
zh: "为了兼容性使用旧适配器"
},
"Before v0.17.16, we used an old adapter for the local database. Now the new adapter is preferred. However, it needs local database rebuilding. Please disable this toggle when you have enough time. If leave it enabled, also while fetching from the remote database, you will be asked to disable this.": {
zh: "在v0.17.16之前,我们使用了旧适配器作为本地数据库。现在更倾向于使用新适配器。但是,它需要重建本地数据库。请在有足够时间时禁用此切换。如果保留启用状态,且在从远程数据库获取时,将要求您禁用此切换"
},
"Scan changes on customization sync": {
zh: "在自定义同步时扫描更改"
},
"Do not use internal API": {
zh: "不使用内部API"
},
"Database suffix": {
zh: "数据库后缀"
},
"LiveSync could not handle multiple vaults which have same name without different prefix, This should be automatically configured.": {
zh: "LiveSync无法处理具有相同名称但没有不同前缀的多个仓库。这应该自动配置"
},
"The Hash algorithm for chunk IDs": {
zh: "块ID的哈希算法"
},
"Fetch database with previous behaviour": {
zh: "用以前的行为获取数据库"
},
"Do not check configuration mismatch before replication": {
zh: "在复制前不检查配置不匹配"
},
"Device name": {
zh: "设备名称"
},
"Unique name between all synchronized devices. To edit this setting, please disable customization sync once.": {
zh: "所有同步设备之间的唯一名称。要编辑此设置,请首先禁用自定义同步"
},
"Enable customization sync": {
zh: "启用自定义同步"
},
"Scan customization automatically": {
zh: "自动扫描自定义设置"
},
"Scan customization before replicating.": {
zh: "在复制前扫描自定义设置"
},
"Scan customization periodically": {
zh: "定期扫描自定义设置"
},
"Scan customization every 1 minute.": {
zh: "每1分钟扫描自定义设置"
},
"Notify customized": {
zh: "通知自定义设置"
},
"Notify when other device has newly customized.": {
zh: "当其他设备有新的自定义设置时通知"
},
"Waiting for ready...": {
zh: "等待就绪..."
}
}, currentLang = "", missingTranslations = [], __onMissingTranslations = _ => console.warn(_);
function __onMissingTranslation(_) {
__onMissingTranslations = _;
}
var msgCache = new Map;
function setLang(_) {
if (_ != currentLang) {
currentLang = _;
msgCache.clear();
}
}
function _getMessage(_, ee) {
var ne, ie, re;
if ("" == _.trim()) return _;
const se = null != (ne = allMessages[_]) ? ne : void 0;
if ("" == ee) ee = "def";
let oe = null != (ie = null == se ? void 0 : se[ee]) ? ie : void 0;
if (!oe) oe = null != (re = null == se ? void 0 : se.def) ? re : void 0;
if (!oe) {
if (!missingTranslations.contains(_)) {
__onMissingTranslations(_);
missingTranslations.push(_);
}
return _;
}
return oe;
}
function getMessage(_) {
if (msgCache.has(_)) return msgCache.get(_);
const ee = _getMessage(_, currentLang);
msgCache.set(_, ee);
return ee;
}
function $t(_, ee) {
if (void 0 !== ee) return _getMessage(_, ee); else return getMessage(_);
}
function $f(_, ...ee) {
let ne = "";
for (let ie = 0; ie < ee.length; ie++) ne += getMessage(_[ie]) + ee[ie];
ne += getMessage(_[_.length - 1]);
return ne;
}
var _a3, OnDialogSettingsDefault = {
configPassphrase: "",
preset: "",
syncMode: "ONEVENTS",
dummy: 0,
deviceAndVaultName: ""
}, AllSettingDefault = {
...DEFAULT_SETTINGS,
...OnDialogSettingsDefault
}, SettingInformation = {
liveSync: {
name: "Sync Mode"
},
couchDB_URI: {
name: "URI",
placeHolder: "https://........"
},
couchDB_USER: {
name: "Username",
desc: "username"
},
couchDB_PASSWORD: {
name: "Password",
desc: "password"
},
couchDB_DBNAME: {
name: "Database name"
},
passphrase: {
name: "Passphrase",
desc: "Encrypting passphrase. If you change the passphrase of an existing database, overwriting the remote database is strongly recommended."
},
showStatusOnEditor: {
name: "Show status inside the editor",
desc: "Reflected after reboot"
},
showOnlyIconsOnEditor: {
name: "Show status as icons only"
},
showStatusOnStatusbar: {
name: "Show status on the status bar",
desc: "Reflected after reboot."
},
lessInformationInLog: {
name: "Show only notifications",
desc: "Prevent logging and show only notification. Please disable when you report the logs"
},
showVerboseLog: {
name: "Verbose Log",
desc: "Show verbose log. Please enable when you report the logs"
},
hashCacheMaxCount: {
name: "Memory cache size (by total items)"
},
hashCacheMaxAmount: {
name: "Memory cache size (by total characters)",
desc: "(Mega chars)"
},
writeCredentialsForSettingSync: {
name: "Write credentials in the file",
desc: "(Not recommended) If set, credentials will be stored in the file."
},
notifyAllSettingSyncFile: {
name: "Notify all setting files"
},
configPassphrase: {
name: "Passphrase of sensitive configuration items",
desc: "This passphrase will not be copied to another device. It will be set to `Default` until you configure it again."
},
configPassphraseStore: {
name: "Encrypting sensitive configuration items"
},
syncOnSave: {
name: "Sync on Save",
desc: "When you save a file, sync automatically"
},
syncOnEditorSave: {
name: "Sync on Editor Save",
desc: "When you save a file in the editor, sync automatically"
},
syncOnFileOpen: {
name: "Sync on File Open",
desc: "When you open a file, sync automatically"
},
syncOnStart: {
name: "Sync on Start",
desc: "Start synchronization after launching Obsidian."
},
syncAfterMerge: {
name: "Sync after merging file",
desc: "Sync automatically after merging files"
},
trashInsteadDelete: {
name: "Use the trash bin",
desc: "Do not delete files that are deleted in remote, just move to trash."
},
doNotDeleteFolder: {
name: "Keep empty folder",
desc: "Normally, a folder is deleted when it becomes empty after a synchronization. Enabling this will prevent it from getting deleted"
},
resolveConflictsByNewerFile: {
name: "Always overwrite with a newer file (beta)",
desc: "(Def off) Resolve conflicts by newer files automatically."
},
checkConflictOnlyOnOpen: {
name: "Postpone resolution of inactive files"
},
showMergeDialogOnlyOnActive: {
name: "Postpone manual resolution of inactive files"
},
disableMarkdownAutoMerge: {
name: "Always resolve conflicts manually",
desc: "If this switch is turned on, a merge dialog will be displayed, even if the sensible-merge is possible automatically. (Turn on to previous behavior)"
},
writeDocumentsIfConflicted: {
name: "Always reflect synchronized changes even if the note has a conflict",
desc: "Turn on to previous behavior"
},
syncInternalFilesInterval: {
name: "Scan hidden files periodically",
desc: "Seconds, 0 to disable"
},
batchSave: {
name: "Batch database update",
desc: "Reducing the frequency with which on-disk changes are reflected into the DB"
},
readChunksOnline: {
name: "Fetch chunks on demand",
desc: "(ex. Read chunks online) If this option is enabled, LiveSync reads chunks online directly instead of replicating them locally. Increasing Custom chunk size is recommended."
},
syncMaxSizeInMB: {
name: "Maximum file size",
desc: "(MB) If this is set, changes to local and remote files that are larger than this will be skipped. If the file becomes smaller again, a newer one will be used."
},
useIgnoreFiles: {
name: "(Beta) Use ignore files",
desc: "If this is set, changes to local files which are matched by the ignore files will be skipped. Remote changes are determined using local ignore files."
},
ignoreFiles: {
name: "Ignore files",
desc: "We can use multiple ignore files, e.g.) `.gitignore, .dockerignore`"
},
batch_size: {
name: "Batch size",
desc: "Number of change feed items to process at a time. Defaults to 50. Minimum is 2."
},
batches_limit: {
name: "Batch limit",
desc: "Number of batches to process at a time. Defaults to 40. Minimum is 2. This along with batch size controls how many docs are kept in memory at a time."
},
useTimeouts: {
name: "Use timeouts instead of heartbeats",
desc: "If this option is enabled, PouchDB will hold the connection open for 60 seconds, and if no change arrives in that time, close and reopen the socket, instead of holding it open indefinitely. Useful when a proxy limits request duration but can increase resource usage."
},
concurrencyOfReadChunksOnline: {
name: "Batch size of on-demand fetching"
},
minimumIntervalOfReadChunksOnline: {
name: "The delay for consecutive on-demand fetches"
},
suspendFileWatching: {
name: "Suspend file watching",
desc: "Stop watching for file change."
},
suspendParseReplicationResult: {
name: "Suspend database reflecting",
desc: "Stop reflecting database changes to storage files."
},
writeLogToTheFile: {
name: "Write logs into the file",
desc: "Warning! This will have a serious impact on performance. And the logs will not be synchronised under the default name. Please be careful with logs; they often contain your confidential information."
},
deleteMetadataOfDeletedFiles: {
name: "Do not keep metadata of deleted files."
},
useIndexedDBAdapter: {
name: "Use an old adapter for compatibility",
desc: "Before v0.17.16, we used an old adapter for the local database. Now the new adapter is preferred. However, it needs local database rebuilding. Please disable this toggle when you have enough time. If leave it enabled, also while fetching from the remote database, you will be asked to disable this."
},
watchInternalFileChanges: {
name: "Scan changes on customization sync",
desc: "Do not use internal API"
},
doNotSuspendOnFetching: {
name: "Fetch database with previous behaviour"
},
disableCheckingConfigMismatch: {
name: "Do not check configuration mismatch before replication"
},
usePluginSync: {
name: "Enable customization sync"
},
autoSweepPlugins: {
name: "Scan customization automatically",
desc: "Scan customization before replicating."
},
autoSweepPluginsPeriodic: {
name: "Scan customization periodically",
desc: "Scan customization every 1 minute."
},
notifyPluginOrSettingUpdated: {
name: "Notify customized",
desc: "Notify when other device has newly customized."
},
remoteType: {
name: "Remote Type",
desc: "Remote server type"
},
endpoint: {
name: "Endpoint URL",
placeHolder: "https://........"
},
accessKey: {
name: "Access Key"
},
secretKey: {
name: "Secret Key"
},
region: {
name: "Region",
placeHolder: "auto"
},
bucket: {
name: "Bucket Name"
},
useCustomRequestHandler: {
name: "Use Custom HTTP Handler",
desc: "If your Object Storage could not configured accepting CORS, enable this."
},
maxChunksInEden: {
name: "Maximum Incubating Chunks",
desc: "The maximum number of chunks that can be incubated within the document. Chunks exceeding this number will immediately graduate to independent chunks."
},
maxTotalLengthInEden: {
name: "Maximum Incubating Chunk Size",
desc: "The maximum total size of chunks that can be incubated within the document. Chunks exceeding this size will immediately graduate to independent chunks."
},
maxAgeInEden: {
name: "Maximum Incubation Period",
desc: "The maximum duration for which chunks can be incubated within the document. Chunks exceeding this period will graduate to independent chunks."
},
settingSyncFile: {
name: "Filename",
desc: "If you set this, all settings are saved in a markdown file. You will be notified when new settings arrive. You can set different files by the platform."
},
preset: {
name: "Presets",
desc: "Apply preset configuration"
},
syncMode: {
name: "Sync Mode"
},
periodicReplicationInterval: {
name: "Periodic Sync interval",
desc: "Interval (sec)"
},
syncInternalFilesBeforeReplication: {
name: "Scan for hidden files before replication"
},
automaticallyDeleteMetadataOfDeletedFiles: {
name: "Delete old metadata of deleted files on start-up",
desc: "(Days passed, 0 to disable automatic-deletion)"
},
additionalSuffixOfDatabaseName: {
name: "Database suffix",
desc: "LiveSync could not handle multiple vaults which have same name without different prefix, This should be automatically configured."
},
hashAlg: {
name: (null == (_a3 = configurationNames["hashAlg"]) ? void 0 : _a3.name) || "",
desc: "xxhash64 is the current default."
},
deviceAndVaultName: {
name: "Device name",
desc: "Unique name between all synchronized devices. To edit this setting, please disable customization sync once."
},
displayLanguage: {
name: "Display Language",
desc: 'Not all messages have been translated. And, please revert to "Default" when reporting errors.'
},
enableChunkSplitterV2: {
name: "Use splitting-limit-capped chunk splitter",
desc: "If enabled, chunks will be split into no more than 100 items. However, dedupe is slightly weaker."
},
disableWorkerForGeneratingChunks: {
name: "Do not split chunks in the background",
desc: "If disabled(toggled), chunks will be split on the UI thread (Previous behaviour)."
},
processSmallFilesInUIThread: {
name: "Process small files in the foreground",
desc: "If enabled, the file under 1kb will be processed in the UI thread."
},
batchSaveMinimumDelay: {
name: "Minimum delay for batch database updating",
desc: "Seconds. Saving to the local database will be delayed until this value after we stop typing or saving."
},
batchSaveMaximumDelay: {
name: "Maximum delay for batch database updating",
desc: "Saving will be performed forcefully after this number of seconds."
}
};
function translateInfo(_) {
if (!_) return false;
const ee = {
..._
};
ee.name = $t(ee.name);
if (ee.desc) ee.desc = $t(ee.desc);
return ee;
}
function _getConfig(_) {
if (_ in configurationNames) return configurationNames[_];
if (_ in SettingInformation) return SettingInformation[_]; else return false;
}
function getConfig(_) {
return translateInfo(_getConfig(_));
}
function getConfName(_) {
const ee = getConfig(_);
if (!ee) return `${_} (No info)`; else return ee.name;
}
function visibleOnly(_) {
return () => ({
visibility: _()
});
}
function enableOnly(_) {
return () => ({
disabled: !_()
});
}
function wrapMemo(_) {
let ee;
return ne => {
if (ee !== ne) {
_(ne);
ee = ne;
}
};
}
var Setting2 = class _Setting extends import_obsidian.Setting {
constructor(_) {
super(_);
this.watchDirtyKeys = [];
this.holdValue = false;
this.descBuf = "";
this.nameBuf = "";
this.placeHolderBuf = "";
this.hasPassword = false;
this.updateHandlers = new Set;
this.prevStatus = {};
_Setting.env.settingComponents.push(this);
}
setDesc(_) {
this.descBuf = _;
super.setDesc(_);
return this;
}
setName(_) {
this.nameBuf = _;
super.setName(_);
return this;
}
setAuto(_, ee) {
this.autoWireSetting(_, ee);
return this;
}
autoWireSetting(_, ee) {
const ne = getConfig(_);
if (!ne) return;
const ie = `${ne.name}${statusDisplay(ne.status)}`;
this.setName(ie);
if (ne.desc) this.setDesc(ne.desc);
this.holdValue = (null == ee ? void 0 : ee.holdValue) || this.holdValue;
this.selfKey = _;
if (null == ee ? void 0 : ee.onUpdate) this.addOnUpdate(ee.onUpdate);
const re = this._getComputedStatus();
if (false === re.visibility) this.settingEl.toggleClass("sls-setting-hidden", !re.visibility);
return ne;
}
autoWireComponent(_, ee, ne) {
this.placeHolderBuf = (null == ee ? void 0 : ee.placeHolder) || (null == ne ? void 0 : ne.placeHolder) || "";
if (this.placeHolderBuf && _ instanceof import_obsidian5.TextComponent) _.setPlaceholder(this.placeHolderBuf);
if (null == ne ? void 0 : ne.onUpdate) this.addOnUpdate(ne.onUpdate);
}
async commitValue(_) {
const ee = this.selfKey;
if (void 0 !== ee) if (_ != _Setting.env.editingSettings[ee]) {
_Setting.env.editingSettings[ee] = _;
if (!this.holdValue) await _Setting.env.saveSettings([ ee ]);
}
_Setting.env.requestUpdate();
}
autoWireText(_, ee) {
const ne = this.autoWireSetting(_, ee);
this.addText((ie => {
this.autoWiredComponent = ie;
const re = wrapMemo((_ => ie.setValue(_)));
this.invalidateValue = () => re(`${_Setting.env.editingSettings[_]}`);
this.invalidateValue();
ie.onChange((async _ => {
await this.commitValue(_);
}));
if (null == ee ? void 0 : ee.isPassword) {
ie.inputEl.setAttribute("type", "password");
this.hasPassword = true;
}
this.autoWireComponent(this.autoWiredComponent, ne, ee);
}));
return this;
}
autoWireTextArea(_, ee) {
const ne = this.autoWireSetting(_, ee);
this.addTextArea((ie => {
this.autoWiredComponent = ie;
const re = wrapMemo((_ => ie.setValue(_)));
this.invalidateValue = () => re(`${_Setting.env.editingSettings[_]}`);
this.invalidateValue();
ie.onChange((async _ => {
await this.commitValue(_);
}));
if (null == ee ? void 0 : ee.isPassword) {
ie.inputEl.setAttribute("type", "password");
this.hasPassword = true;
}
this.autoWireComponent(this.autoWiredComponent, ne, ee);
}));
return this;
}
autoWireNumeric(_, ee) {
const ne = this.autoWireSetting(_, ee);
this.addText((ie => {
this.autoWiredComponent = ie;
if (ee.clampMin) ie.inputEl.setAttribute("min", `${ee.clampMin}`);
if (ee.clampMax) ie.inputEl.setAttribute("max", `${ee.clampMax}`);
let re = false;
const se = wrapMemo((_ => ie.setValue(_)));
this.invalidateValue = () => {
if (!re) se(`${_Setting.env.editingSettings[_]}`);
};
this.invalidateValue();
ie.onChange((async _ => {
const ne = Number(_);
let se = false;
if (isNaN(ne)) se = true;
if (ee.clampMax && ee.clampMax < ne) se = true;
if (ee.clampMin && ee.clampMin > ne) if (ee.acceptZero && 0 == ne) ; else se = true;
if (!se) {
re = false;
this.setTooltip("");
ie.inputEl.toggleClass("sls-item-invalid-value", false);
await this.commitValue(ne);
} else {
this.setTooltip(`The value should ${ee.clampMin || "~"} < value < ${ee.clampMax || "~"}`);
ie.inputEl.toggleClass("sls-item-invalid-value", true);
re = true;
return false;
}
}));
ie.inputEl.setAttr("type", "number");
this.autoWireComponent(this.autoWiredComponent, ne, ee);
}));
return this;
}
autoWireToggle(_, ee) {
const ne = this.autoWireSetting(_, ee);
this.addToggle((ie => {
this.autoWiredComponent = ie;
const re = wrapMemo((_ => ie.setValue((null == ee ? void 0 : ee.invert) ? !_ : _)));
this.invalidateValue = () => {
var ee;
return re(null != (ee = _Setting.env.editingSettings[_]) ? ee : false);
};
this.invalidateValue();
ie.onChange((async _ => {
await this.commitValue((null == ee ? void 0 : ee.invert) ? !_ : _);
}));
this.autoWireComponent(this.autoWiredComponent, ne, ee);
}));
return this;
}
autoWireDropDown(_, ee) {
const ne = this.autoWireSetting(_, ee);
this.addDropdown((ie => {
this.autoWiredComponent = ie;
const re = wrapMemo((_ => {
ie.setValue(_);
}));
ie.addOptions(ee.options);
this.invalidateValue = () => re(_Setting.env.editingSettings[_] || "");
this.invalidateValue();
ie.onChange((async _ => {
await this.commitValue(_);
}));
this.autoWireComponent(this.autoWiredComponent, ne, ee);
}));
return this;
}
addApplyButton(_) {
this.addButton((ee => {
this.applyButtonComponent = ee;
this.watchDirtyKeys = unique([ ..._, ...this.watchDirtyKeys ]);
ee.setButtonText("Apply");
ee.onClick((async () => {
await _Setting.env.saveSettings(_);
_Setting.env.reloadAllSettings();
}));
_Setting.env.requestUpdate();
}));
return this;
}
addOnUpdate(_) {
this.updateHandlers.add(_);
return this;
}
_getComputedStatus() {
let _ = {};
for (const ee of this.updateHandlers) _ = {
..._,
...ee()
};
return _;
}
_applyOnUpdateHandlers() {
if (this.updateHandlers.size > 0) {
const _ = this._getComputedStatus(), ee = Object.keys(_);
for (const ne of ee) if (!(ne in this.prevStatus) || this.prevStatus[ne] != _[ne]) switch (ne) {
case "visibility":
this.settingEl.toggleClass("sls-setting-hidden", !(_[ne] || false));
this.prevStatus[ne] = _[ne];
break;
case "classes":
break;
case "disabled":
this.setDisabled(_[ne] || false);
this.settingEl.toggleClass("sls-setting-disabled", _[ne] || false);
this.prevStatus[ne] = _[ne];
break;
case "isCta":
{
const ee = this.autoWiredComponent;
if (ee instanceof import_obsidian5.ButtonComponent) if (_[ne]) ee.setCta(); else ee.removeCta();
this.prevStatus[ne] = _[ne];
}
break;
case "isWarning":
{
const ee = this.autoWiredComponent;
if (ee instanceof import_obsidian5.ButtonComponent) if (_[ne]) ee.setWarning();
this.prevStatus[ne] = _[ne];
}
break;
}
}
}
_onUpdate() {
if (this.applyButtonComponent) {
const _ = _Setting.env.isSomeDirty(this.watchDirtyKeys);
this.applyButtonComponent.setDisabled(!_);
if (_) this.applyButtonComponent.setCta(); else this.applyButtonComponent.removeCta();
}
if (this.selfKey && !_Setting.env.isDirty(this.selfKey) && this.invalidateValue) this.invalidateValue();
if (this.holdValue && this.selfKey) {
const _ = _Setting.env.isDirty(this.selfKey), ee = _ ? `Original: ${_Setting.env.initialSettings[this.selfKey]}` : "";
this.controlEl.toggleClass("sls-item-dirty", _);
if (!this.hasPassword) {
this.nameEl.toggleClass("sls-item-dirty-help", _);
this.setTooltip(ee, {
delay: 10,
placement: "right"
});
}
}
this._applyOnUpdateHandlers();
}
}, ObsidianLiveSyncSettingTab = class extends import_obsidian.PluginSettingTab {
constructor(_, ee) {
super(_, ee);
this.selectedScreen = "";
this.settingComponents = [];
this.controlledElementFunc = [];
this.onSavedHandlers = [];
this.isShown = false;
this.plugin = ee;
Setting2.env = this;
}
get editingSettings() {
if (!this._editingSettings) this.reloadAllSettings();
return this._editingSettings;
}
set editingSettings(_) {
if (!this._editingSettings) this.reloadAllSettings();
this._editingSettings = _;
}
applySetting(_) {
for (const ee of _) if (this.isDirty(ee)) if (!(ee in OnDialogSettingsDefault)) {
this.plugin.settings[ee] = this.editingSettings[ee];
this.initialSettings[ee] = this.plugin.settings[ee];
}
_.forEach((_ => this.refreshSetting(_)));
}
applyAllSettings() {
var _;
const ee = Object.keys(null != (_ = this.editingSettings) ? _ : {}).filter((_ => this.isDirty(_)));
this.applySetting(ee);
this.reloadAllSettings();
}
async saveLocalSetting(_) {
var ee, ne, ie;
if ("configPassphrase" == _) {
localStorage.setItem("ls-setting-passphrase", null != (ne = null == (ee = this.editingSettings) ? void 0 : ee[_]) ? ne : "");
return await Promise.resolve();
}
if ("deviceAndVaultName" == _) {
this.plugin.deviceAndVaultName = null == (ie = this.editingSettings) ? void 0 : ie[_];
this.plugin.saveDeviceAndVaultName();
return await Promise.resolve();
}
}
async saveSettings(_) {
let ee = false;
const ne = [];
for (const ie of _) if (this.isDirty(ie)) {
ne.push(ie);
if (!(ie in OnDialogSettingsDefault)) {
this.plugin.settings[ie] = this.editingSettings[ie];
this.initialSettings[ie] = this.plugin.settings[ie];
ee = true;
} else {
await this.saveLocalSetting(ie);
this.initialSettings[ie] = this.editingSettings[ie];
}
}
if (ee) await this.plugin.saveSettings();
const ie = this.onSavedHandlers.filter((_ => -1 !== ne.indexOf(_.key))).map((_ => _.handler(this.editingSettings[_.key])));
await Promise.all(ie);
_.forEach((_ => this.refreshSetting(_)));
}
async saveAllDirtySettings() {
var _;
const ee = Object.keys(null != (_ = this.editingSettings) ? _ : {}).filter((_ => this.isDirty(_)));
await this.saveSettings(ee);
this.reloadAllSettings();
}
requestUpdate() {
scheduleTask("update-setting", 10, (() => {
for (const _ of this.settingComponents) _._onUpdate();
for (const _ of this.controlledElementFunc) _();
}));
}
reloadAllLocalSettings() {
const _ = {
...OnDialogSettingsDefault
};
_.configPassphrase = localStorage.getItem("ls-setting-passphrase") || "";
_.preset = "";
_.deviceAndVaultName = this.plugin.deviceAndVaultName;
return _;
}
computeAllLocalSettings() {
var _, ee;
return {
syncMode: (null == (_ = this.editingSettings) ? void 0 : _.liveSync) ? "LIVESYNC" : (null == (ee = this.editingSettings) ? void 0 : ee.periodicReplication) ? "PERIODIC" : "ONEVENTS"
};
}
reloadAllSettings(_ = false) {
const ee = this.reloadAllLocalSettings();
this._editingSettings = {
...this.plugin.settings,
...ee
};
this._editingSettings = {
...this.editingSettings,
...this.computeAllLocalSettings()
};
this.initialSettings = {
...this.editingSettings
};
if (!_) this.requestUpdate();
}
refreshSetting(_) {
const ee = this.reloadAllLocalSettings();
if (_ in this.plugin.settings) if (_ in ee) {
this.initialSettings[_] = ee[_];
this.editingSettings[_] = ee[_];
} else {
this.initialSettings[_] = this.plugin.settings[_];
this.editingSettings[_] = this.initialSettings[_];
}
this.editingSettings = {
...this.editingSettings,
...this.computeAllLocalSettings()
};
this.requestUpdate();
}
isDirty(_) {
var ee;
return isObjectDifferent(this.editingSettings[_], null == (ee = this.initialSettings) ? void 0 : ee[_]);
}
isSomeDirty(_) {
return _.some((_ => this.isDirty(_)));
}
isConfiguredAs(_, ee) {
if (!this.editingSettings) return false; else return this.editingSettings[_] == ee;
}
async testConnection(_ = {}) {
const ee = {
...this.editingSettings,
..._
}, ne = this.plugin.getNewReplicator(ee);
await ne.tryConnectRemote(ee);
}
closeSetting() {
this.plugin.app.setting.close();
}
handleElement(_, ee) {
const ne = ((_, ee) => {
const ne = {};
return () => {
const ie = ee(), re = Object.keys(ie);
for (const ee of re) if (ne[ee] !== ie[ee]) {
if ("visibility" == ee) _.toggleClass("sls-setting-hidden", !(ie[ee] || false));
ne[ee] = ie[ee];
}
};
})(_, ee);
this.controlledElementFunc.push(ne);
ne();
}
createEl(_, ee, ne, ie, re) {
const se = _.createEl(ee, ne, ie);
if (re) this.handleElement(se, re);
return se;
}
addOnSaved(_, ee) {
this.onSavedHandlers.push({
key: _,
handler: ee
});
}
resetEditingSettings() {
this._editingSettings = void 0;
this.initialSettings = void 0;
}
hide() {
this.isShown = false;
}
requestReload() {
var _;
if (this.isShown) {
const ee = this.plugin.settings, ne = Object.keys(ee);
let ie = false;
for (const re of ne) if ("deviceAndVaultName" !== re) if (isObjectDifferent(ee[re], null == (_ = this.initialSettings) ? void 0 : _[re])) if (this.isDirty(re)) this.plugin.askInPopup(`config-reloaded-${re}`, `The setting "${getConfName(re)}" being in editing has been changed from somewhere. We can discard modification and reload by clicking {HERE}. Click elsewhere to ignore changes`, (_ => {
_.text = "HERE";
_.addEventListener("click", (() => {
this.refreshSetting(re);
this.display();
}));
})); else {
this.refreshSetting(re);
ie = true;
}
if (ie) this.display(); else this.requestUpdate();
} else this.reloadAllSettings(true);
}
display() {
var _, ee, ne, ie, re, se;
const {containerEl: oe} = this;
this.settingComponents.length = 0;
this.controlledElementFunc.length = 0;
this.onSavedHandlers.length = 0;
if (null == this._editingSettings || null == this.initialSettings) this.reloadAllSettings();
if (void 0 === this.editingSettings || null == this.initialSettings) return;
this.isShown = true;
oe.empty();
this.createEl(oe, "h2", {
text: "Settings for Self-hosted LiveSync."
});
oe.addClass("sls-setting");
oe.removeClass("isWizard");
const le = oe.createDiv(""), ue = {}, addScreenElement = (_, ee) => {
if (!(_ in ue)) ue[_] = [];
ue[_].push(ee);
};
le.addClass("sls-setting-menu");
le.innerHTML = "\n\n\n\n\n\n\n\n\n ";
const de = le.querySelectorAll(".sls-setting-label"), changeDisplay = _ => {
for (const ee in ue) if (ee == _) ue[ee].forEach((_ => _.removeClass("setting-collapsed"))); else ue[ee].forEach((_ => _.addClass("setting-collapsed")));
le.querySelectorAll(".sls-setting-label").forEach((_ => {
_.removeClass("selected");
_.querySelector("input[type=radio]").checked = false;
}));
le.querySelectorAll(`.sls-setting-label.c-${_}`).forEach((_ => {
_.addClass("selected");
_.querySelector("input[type=radio]").checked = true;
}));
this.selectedScreen = _;
};
de.forEach((_ => {
const ee = _.querySelector(".sls-setting-tab");
if (ee) ee.addEventListener("change", (ee => {
de.forEach((_ => _.removeClass("selected")));
changeDisplay(ee.currentTarget.value);
_.addClass("selected");
}));
}));
const fe = oe.createDiv(), he = this.createEl(fe, "h3", {
text: "Updates"
}), pe = this.createEl(fe, "div", {
text: ""
}), ge = "0.23.14", me = ~~(versionNumberString2Number(ge) / 1e3), ye = createSpan();
ye.addClass("sls-header-button");
ye.innerHTML = "";
if (me > ((null == (_ = this.editingSettings) ? void 0 : _.lastReadUpdates) || 0)) {
const _ = he.appendChild(ye);
null == (ee = _.querySelector("button")) || ee.addEventListener("click", (async () => {
this.editingSettings.lastReadUpdates = me;
await this.saveAllDirtySettings();
_.remove();
}));
}
import_obsidian.MarkdownRenderer.render(this.plugin.app, "### 0.23.0\nIncredibly new features!\n\nNow, we can use object storage (MinIO, S3, R2 or anything you like) for synchronising! Moreover, despite that, we can use all the features as if we were using CouchDB.\nNote: As this is a pretty experimental feature, hence we have some limitations.\n- This is built on the append-only architecture. It will not shrink used storage if we do not perform a rebuild.\n- A bit fragile. However, our version x.yy.0 is always so.\n- When the first synchronisation, the entire history to date is transferred. For this reason, it is preferable to do this under the WiFi network.\n- Do not worry, from the second synchronisation, we always transfer only differences.\n\nI hope this feature empowers users to maintain independence and self-host their data, offering an alternative for those who prefer to manage their own storage solutions and avoid being stuck on the right side of a sudden change in business model.\n\nOf course, I use Self-hosted MinIO for testing and recommend this. It is for the same reason as using CouchDB. -- open, controllable, auditable and indeed already audited by numerous eyes.\n\nLet me write one more acknowledgement.\n\nI have a lot of respect for that plugin, even though it is sometimes treated as if it is a competitor, remotely-save. I think it is a great architecture that embodies a different approach to my approach of recreating history. This time, with all due respect, I have used some of its code as a reference.\nHooray for open source, and generous licences, and the sharing of knowledge by experts.\n\n#### Version history\n- 0.23.14:\n - Fixed:\n - No longer batch-saving ignores editor inputs.\n - The file-watching and serialisation processes have been changed to the one which is similar to previous implementations.\n - We can configure the settings (Especially about text-boxes) even if we have configured the device name.\n - Improved:\n - We can configure the delay of batch-saving.\n - Default: 5 seconds, the same as the previous hard-coded value. (Note: also, the previous behaviour was not correct).\n - Also, we can configure the limit of delaying batch-saving.\n - The performance of showing status indicators has been improved.\n- 0.23.13:\n - Fixed:\n - No longer files have been trimmed even delimiters have been continuous.\n - Fixed the toggle title to `Do not split chunks in the background` from `Do not split chunks in the foreground`.\n - Non-configured item mismatches are no longer detected.\n- 0.23.12:\n - Improved:\n - Now notes will be split into chunks in the background thread to improve smoothness.\n - Default enabled, to disable, toggle `Do not split chunks in the foreground` on `Hatch` -> `Compatibility`.\n - If you want to process very small notes in the foreground, please enable `Process small files in the foreground` on `Hatch` -> `Compatibility`.\n - We can use a `splitting-limit-capped chunk splitter`; which performs more simple and make less amount of chunks.\n - Default disabled, to enable, toggle `Use splitting-limit-capped chunk splitter` on `Sync settings` -> `Performance tweaks`\n - Tidied\n - Some files have been separated into multiple files to make them more explicit in what they are responsible for.\n- 0.23.11:\n - Fixed:\n - Now we *surely* can set the device name and enable customised synchronisation.\n - Unnecessary dialogue update processes have been eliminated.\n - Customisation sync no longer stores half-collected files.\n - No longer hangs up when removing or renaming files with the `Sync on Save` toggle enabled.\n - Improved:\n - Customisation sync now performs data deserialization more smoothly.\n - New translations have been merged.\n- 0.23.10\n - Fixed:\n - No longer configurations have been locked in the minimal setup.\n- 0.23.9\n - Fixed:\n - No longer unexpected parallel replication is performed.\n - Now we can set the device name and enable customised synchronisation again.\n\n\nOlder notes is in [updates_old.md](https://github.com/vrtmrz/obsidian-livesync/blob/main/updates_old.md).", pe, "/", this.plugin);
addScreenElement("100", fe);
const isAnySyncEnabled = () => {
var _, ee, ne, ie;
if (this.isConfiguredAs("isConfigured", false)) return false;
if (this.isConfiguredAs("liveSync", true)) return true;
if (this.isConfiguredAs("periodicReplication", true)) return true;
if (this.isConfiguredAs("syncOnFileOpen", true)) return true;
if (this.isConfiguredAs("syncOnSave", true)) return true;
if (this.isConfiguredAs("syncOnEditorSave", true)) return true;
if (this.isConfiguredAs("syncOnStart", true)) return true;
if (this.isConfiguredAs("syncAfterMerge", true)) return true;
if (this.isConfiguredAs("syncOnFileOpen", true)) return true;
if ("CONNECTED" == (null == (ee = null == (_ = this.plugin) ? void 0 : _.replicator) ? void 0 : ee.syncStatus)) return true;
if ("PAUSED" == (null == (ie = null == (ne = this.plugin) ? void 0 : ne.replicator) ? void 0 : ie.syncStatus)) return true; else return false;
}, ve = enableOnly((() => !isAnySyncEnabled()));
let Se = false;
if (oe.hasClass("inWizard")) Se = true;
const Ee = oe.createDiv();
this.createEl(Ee, "h3", {
text: "Setup wizard"
});
new Setting2(Ee).setName("Use the copied setup URI").setDesc("To setup Self-hosted LiveSync, this method is the most preferred one.").addButton((_ => {
_.setButtonText("Use").onClick((async () => {
this.closeSetting();
await this.plugin.addOnSetup.command_openSetupURI();
}));
}));
if (this.editingSettings.isConfigured) new Setting2(Ee).setName("Copy current settings as a new setup URI").addButton((_ => {
_.setButtonText("Copy").onClick((async () => {
await this.plugin.addOnSetup.command_copySetupURI();
}));
}));
new Setting2(Ee).setName("Minimal setup").addButton((_ => {
_.setButtonText("Start").onClick((async () => {
this.editingSettings.liveSync = false;
this.editingSettings.periodicReplication = false;
this.editingSettings.syncOnSave = false;
this.editingSettings.syncOnEditorSave = false;
this.editingSettings.syncOnStart = false;
this.editingSettings.syncOnFileOpen = false;
this.editingSettings.syncAfterMerge = false;
this.plugin.replicator.closeReplication();
await this.saveAllDirtySettings();
oe.addClass("isWizard");
Se = true;
changeDisplay("0");
}));
}));
new Setting2(Ee).setName("Enable LiveSync on this device as the setup was completed manually").addButton((_ => {
_.setButtonText("Enable").onClick((async () => {
this.editingSettings.isConfigured = true;
await this.saveAllDirtySettings();
this.plugin.askReload();
}));
})).addOnUpdate(visibleOnly((() => !this.isConfiguredAs("isConfigured", true))));
new Setting2(Ee).setName("Discard existing settings and databases").addButton((_ => {
_.setButtonText("Discard").onClick((async () => {
if ("yes" == await askYesNo(this.plugin.app, "Do you really want to discard existing settings and databases?")) {
this.editingSettings = {
...this.editingSettings,
...DEFAULT_SETTINGS
};
await this.plugin.saveSettingData();
await this.plugin.resetLocalDatabase();
this.plugin.askReload();
}
})).setWarning();
})).addOnUpdate(visibleOnly((() => this.isConfiguredAs("isConfigured", true))));
this.createEl(Ee, "h3", {
text: "Online Tips"
});
const Ce = "vrtmrz/obsidian-livesync", we = "/docs/troubleshooting.md", Oe = `https://raw.githubusercontent.com/${Ce}/main`;
this.createEl(Ee, "div", "", (_ => _.innerHTML = `Open in browser`));
const ke = this.createEl(Ee, "div", {
text: "",
cls: "sls-troubleshoot-preview"
}), loadMarkdownPage = async (_, ee = "") => {
var ne, ie;
ke.style.minHeight = ke.clientHeight + "px";
ke.empty();
const re = (_.startsWith("/") ? _ : `${ee}/${_}`).split("/"), se = re.pop(), oe = re.join("/");
let le = "";
try {
le = await (0, import_obsidian5.request)(`${Oe}${oe}/${se}`);
} catch (_) {
le = "An error occurred!!\n" + _.toString();
}
const ue = le.replace(/\((.*?(.png)|(.jpg))\)/g, `(${Oe}${oe}/$1)`);
await import_obsidian.MarkdownRenderer.render(this.plugin.app, ` [Tips and Troubleshooting](${we}) [PageTop](${se})\n\n${ue}`, ke, `${Oe}`, this.plugin);
null == (ie = null == (ne = ke.querySelector(".sls-troubleshoot-anchor")) ? void 0 : ne.parentElement) || ie.setCssStyles({
position: "sticky",
top: "-1em",
backgroundColor: "var(--modal-background)"
});
ke.querySelectorAll("a.internal-link").forEach((_ => {
_.addEventListener("click", (async ee => {
const ne = _.getAttr("data-href");
if (ne) if (ne.startsWith("#")) {
ee.preventDefault();
const _ = Array.from(ke.querySelectorAll("[data-heading]")).find((_ => {
var ee;
return (null == (ee = _.getAttr("data-heading")) ? void 0 : ee.toLowerCase().split(" ").join("-")) == ne.substring(1).toLowerCase();
}));
if (_) {
_.setCssStyles({
scrollMargin: "3em"
});
_.scrollIntoView({
behavior: "instant",
block: "start"
});
}
} else {
ee.preventDefault();
await loadMarkdownPage(ne, oe);
ke.setCssStyles({
scrollMargin: "1em"
});
ke.scrollIntoView({
behavior: "instant",
block: "start"
});
}
}));
}));
ke.style.minHeight = "";
};
loadMarkdownPage(we);
addScreenElement("110", Ee);
const xe = oe.createDiv();
this.createEl(xe, "h3", {
text: "Remote configuration"
});
new Setting2(xe).autoWireDropDown("remoteType", {
holdValue: true,
options: {
[REMOTE_COUCHDB]: "CouchDB",
[REMOTE_MINIO]: "Minio,S3,R2"
},
onUpdate: ve
});
const onlyOnCouchDB = () => ({
visibility: this.isConfiguredAs("remoteType", REMOTE_COUCHDB)
}), onlyOnMinIO = () => ({
visibility: this.isConfiguredAs("remoteType", REMOTE_MINIO)
});
this.createEl(xe, "div", void 0, (_ => {
const ee = this.createEl(_, "div", {
text: ""
});
import_obsidian.MarkdownRenderer.render(this.plugin.app, "Kindly notice: this is a pretty experimental feature, hence we have some limitations. \n- Append only architecture. It will not shrink used storage if we do not perform a rebuild.\n- A bit fragile.\n- During the first synchronization, the entire history to date will be transferred. For this reason, it is preferable to do this while connected to a Wi-Fi network.\n- From the second, we always transfer only differences.\n\nHowever, your report is needed to stabilise this. I appreciate you for your great dedication.\n", ee, "/", this.plugin);
ee.addClass("op-warn-info");
new Setting2(_).autoWireText("endpoint", {
holdValue: true
});
new Setting2(_).autoWireText("accessKey", {
holdValue: true
});
new Setting2(_).autoWireText("secretKey", {
holdValue: true,
isPassword: true
});
new Setting2(_).autoWireText("region", {
holdValue: true
});
new Setting2(_).autoWireText("bucket", {
holdValue: true
});
new Setting2(_).autoWireToggle("useCustomRequestHandler", {
holdValue: true
});
new Setting2(_).setName("Test Connection").addButton((_ => _.setButtonText("Test").setDisabled(false).onClick((async () => {
await this.testConnection(this.editingSettings);
}))));
new Setting2(_).setName("Apply Settings").setClass("wizardHidden").addApplyButton([ "remoteType", "endpoint", "region", "accessKey", "secretKey", "bucket", "useCustomRequestHandler" ]).addOnUpdate(onlyOnMinIO);
}), onlyOnMinIO);
this.createEl(xe, "div", void 0, (_ => {
if (this.plugin.isMobile) this.createEl(_, "div", {
text: "Configured as using non-HTTPS. We cannot connect to the remote. Please set up the credentials and use HTTPS for the remote URI."
}, void 0, visibleOnly((() => !this.editingSettings.couchDB_URI.startsWith("https://")))).addClass("op-warn"); else this.createEl(_, "div", {
text: "Configured as using non-HTTPS. We might fail on mobile devices."
}, void 0, visibleOnly((() => !this.editingSettings.couchDB_URI.startsWith("https://")))).addClass("op-warn-info");
this.createEl(_, "div", {
text: 'These settings are kept locked while any synchronization options are enabled. Disable these options in the "Sync Settings" tab to unlock.'
}, void 0, visibleOnly((() => isAnySyncEnabled()))).addClass("sls-setting-hidden");
new Setting2(_).autoWireText("couchDB_URI", {
holdValue: true,
onUpdate: ve
});
new Setting2(_).autoWireText("couchDB_USER", {
holdValue: true,
onUpdate: ve
});
new Setting2(_).autoWireText("couchDB_PASSWORD", {
holdValue: true,
isPassword: true,
onUpdate: ve
});
new Setting2(_).autoWireText("couchDB_DBNAME", {
holdValue: true,
onUpdate: ve
});
new Setting2(_).setName("Test Database Connection").setClass("wizardHidden").setDesc("Open database connection. If the remote database is not found and you have the privilege to create a database, the database will be created.").addButton((_ => _.setButtonText("Test").setDisabled(false).onClick((async () => {
await this.testConnection();
}))));
new Setting2(_).setName("Check and fix database configuration").setDesc("Check the database configuration, and fix if there are any problems.").addButton((_ => _.setButtonText("Check").setDisabled(false).onClick((async () => {
const checkConfig = async () => {
var _, ne, ie, re, se, oe, le, ue, de, fe, he;
Logger("Checking database configuration", LOG_LEVEL_INFO);
const pe = createDiv();
pe.innerHTML = "";
ee.replaceChildren(pe);
const addResult2 = (_, ne) => {
const ie = createDiv();
ie.addClass("ob-btn-config-fix");
if (ne) ie.addClasses(ne);
ie.innerHTML = `${_}`;
ee.appendChild(ie);
};
try {
if (isCloudantURI(this.editingSettings.couchDB_URI)) {
Logger("This feature cannot be used with IBM Cloudant.", LOG_LEVEL_NOTICE);
return;
}
const pe = (await requestToCouchDB(this.editingSettings.couchDB_URI, this.editingSettings.couchDB_USER, this.editingSettings.couchDB_PASSWORD, window.origin)).json, addConfigFixButton = (_, ne, ie) => {
var re;
const se = createDiv();
se.addClass("ob-btn-config-fix");
se.innerHTML = ``;
const oe = ee.appendChild(se);
null == (re = oe.querySelector("button")) || re.addEventListener("click", (async () => {
Logger(`CouchDB Configuration: ${_} -> Set ${ne} to ${ie}`);
const re = await requestToCouchDB(this.editingSettings.couchDB_URI, this.editingSettings.couchDB_USER, this.editingSettings.couchDB_PASSWORD, void 0, ne, ie);
if (200 == re.status) {
Logger(`CouchDB Configuration: ${_} successfully updated`, LOG_LEVEL_NOTICE);
ee.removeChild(oe);
checkConfig();
} else {
Logger(`CouchDB Configuration: ${_} failed`, LOG_LEVEL_NOTICE);
Logger(re.text, LOG_LEVEL_VERBOSE);
}
}));
};
addResult2("---Notice---", [ "ob-btn-config-head" ]);
addResult2("If the server configuration is not persistent (e.g., running on docker), the values set from here will also be volatile. Once you are able to connect, please reflect the settings in the server's local.ini.", [ "ob-btn-config-info" ]);
addResult2("--Config check--", [ "ob-btn-config-head" ]);
if (!(this.editingSettings.couchDB_USER in pe.admins)) addResult2("⚠ You do not have administrative privileges."); else addResult2("✔ You have administrative privileges.");
if ("true" != (null == (_ = null == pe ? void 0 : pe.chttpd) ? void 0 : _.require_valid_user)) {
addResult2("❗ chttpd.require_valid_user is wrong.");
addConfigFixButton("Set chttpd.require_valid_user = true", "chttpd/require_valid_user", "true");
} else addResult2("✔ chttpd.require_valid_user is ok.");
if ("true" != (null == (ne = null == pe ? void 0 : pe.chttpd_auth) ? void 0 : ne.require_valid_user)) {
addResult2("❗ chttpd_auth.require_valid_user is wrong.");
addConfigFixButton("Set chttpd_auth.require_valid_user = true", "chttpd_auth/require_valid_user", "true");
} else addResult2("✔ chttpd_auth.require_valid_user is ok.");
if (!(null == pe ? void 0 : pe.httpd["WWW-Authenticate"])) {
addResult2("❗ httpd.WWW-Authenticate is missing");
addConfigFixButton("Set httpd.WWW-Authenticate", "httpd/WWW-Authenticate", 'Basic realm="couchdb"');
} else addResult2("✔ httpd.WWW-Authenticate is ok.");
if ("true" != (null == (ie = null == pe ? void 0 : pe.httpd) ? void 0 : ie.enable_cors)) {
addResult2("❗ httpd.enable_cors is wrong");
addConfigFixButton("Set httpd.enable_cors", "httpd/enable_cors", "true");
} else addResult2("✔ httpd.enable_cors is ok.");
if (!isCloudantURI(this.editingSettings.couchDB_URI)) {
if (Number(null != (se = null == (re = null == pe ? void 0 : pe.chttpd) ? void 0 : re.max_http_request_size) ? se : 0) < 4294967296) {
addResult2("❗ chttpd.max_http_request_size is low)");
addConfigFixButton("Set chttpd.max_http_request_size", "chttpd/max_http_request_size", "4294967296");
} else addResult2("✔ chttpd.max_http_request_size is ok.");
if (Number(null != (le = null == (oe = null == pe ? void 0 : pe.couchdb) ? void 0 : oe.max_document_size) ? le : 0) < 5e7) {
addResult2("❗ couchdb.max_document_size is low)");
addConfigFixButton("Set couchdb.max_document_size", "couchdb/max_document_size", "50000000");
} else addResult2("✔ couchdb.max_document_size is ok.");
}
if ("true" != (null == (ue = null == pe ? void 0 : pe.cors) ? void 0 : ue.credentials)) {
addResult2("❗ cors.credentials is wrong");
addConfigFixButton("Set cors.credentials", "cors/credentials", "true");
} else addResult2("✔ cors.credentials is ok.");
const ge = ((null != (fe = null == (de = null == pe ? void 0 : pe.cors) ? void 0 : de.origins) ? fe : "") + "").split(",");
if ("*" == (null == (he = null == pe ? void 0 : pe.cors) ? void 0 : he.origins) || -1 !== ge.indexOf("app://obsidian.md") && -1 !== ge.indexOf("capacitor://localhost") && -1 !== ge.indexOf("http://localhost")) addResult2("✔ cors.origins is ok."); else {
addResult2("❗ cors.origins is wrong");
addConfigFixButton("Set cors.origins", "cors/origins", "app://obsidian.md,capacitor://localhost,http://localhost");
}
addResult2("--Connection check--", [ "ob-btn-config-head" ]);
addResult2(`Current origin:${window.location.origin}`);
const me = [ "app://obsidian.md", "capacitor://localhost", "http://localhost" ];
for (const _ of me) {
const ee = await requestToCouchDB(this.editingSettings.couchDB_URI, this.editingSettings.couchDB_USER, this.editingSettings.couchDB_PASSWORD, _), ne = Object.fromEntries(Object.entries(ee.headers).map((_ => {
_[0] = `${_[0]}`.toLowerCase();
return _;
})));
addResult2(`Origin check:${_}`);
if ("true" != ne["access-control-allow-credentials"]) addResult2("❗ CORS is not allowing credentials"); else addResult2("✔ CORS credentials OK");
if (ne["access-control-allow-origin"] != _) addResult2(`❗ CORS Origin is unmatched:${origin}->${ne["access-control-allow-origin"]}`); else addResult2("✔ CORS origin OK");
}
addResult2("--Done--", [ "ob-btn-config-head" ]);
addResult2("If you have some trouble with Connection-check even though all Config-check has been passed, please check your reverse proxy's configuration.", [ "ob-btn-config-info" ]);
Logger("Checking configuration done", LOG_LEVEL_INFO);
} catch (_) {
if (401 == (null == _ ? void 0 : _.status)) {
addResult2("❗ Access forbidden.");
addResult2("We could not continue the test.");
Logger("Checking configuration done", LOG_LEVEL_INFO);
} else {
Logger("Checking configuration failed", LOG_LEVEL_NOTICE);
Logger(_);
}
}
};
await checkConfig();
}))));
const ee = this.createEl(_, "div", {
text: ""
});
new Setting2(_).setName("Apply Settings").setClass("wizardHidden").addApplyButton([ "remoteType", "couchDB_URI", "couchDB_USER", "couchDB_PASSWORD", "couchDB_DBNAME" ]).addOnUpdate(onlyOnCouchDB);
}), onlyOnCouchDB);
this.createEl(xe, "h4", {
text: "Effective Storage Using"
}).addClass("wizardHidden");
new Setting2(xe).autoWireToggle("useEden").setClass("wizardHidden");
const Ae = visibleOnly((() => this.isConfiguredAs("useEden", true)));
new Setting2(xe).autoWireNumeric("maxChunksInEden", {
onUpdate: Ae
}).setClass("wizardHidden");
new Setting2(xe).autoWireNumeric("maxTotalLengthInEden", {
onUpdate: Ae
}).setClass("wizardHidden");
new Setting2(xe).autoWireNumeric("maxAgeInEden", {
onUpdate: Ae
}).setClass("wizardHidden");
new Setting2(xe).autoWireToggle("enableCompression").setClass("wizardHidden");
this.createEl(xe, "h4", {
text: "Confidentiality"
});
new Setting2(xe).autoWireToggle("encrypt", {
holdValue: true
});
const Le = visibleOnly((() => this.isConfiguredAs("encrypt", true)));
new Setting2(xe).autoWireText("passphrase", {
holdValue: true,
isPassword: true,
onUpdate: Le
});
new Setting2(xe).autoWireToggle("usePathObfuscation", {
holdValue: true,
onUpdate: Le
});
new Setting2(xe).autoWireToggle("useDynamicIterationCount", {
holdValue: true,
onUpdate: Le
}).setClass("wizardHidden");
new Setting2(xe).setName("Apply").setDesc("Apply encryption settings").setClass("wizardHidden").addButton((_ => _.setButtonText("Just apply").setWarning().setDisabled(false).onClick((async () => {
await applyEncryption(false);
})))).addButton((_ => _.setButtonText("Apply and fetch").setWarning().setDisabled(false).onClick((async () => {
await rebuildDB("localOnly");
})))).addButton((_ => _.setButtonText("Apply and rebuild").setWarning().setDisabled(false).onClick((async () => {
await rebuildDB("rebuildBothByThisDevice");
})))).addOnUpdate((() => ({
isCta: this.isSomeDirty([ "passphrase", "useDynamicIterationCount", "usePathObfuscation", "encrypt" ]),
disabled: !this.isSomeDirty([ "passphrase", "useDynamicIterationCount", "usePathObfuscation", "encrypt" ])
})));
const checkWorkingPassphrase = async () => {
if (this.editingSettings.remoteType == REMOTE_MINIO) return true;
const _ = {
...this.editingSettings
}, ee = this.plugin.getReplicator();
if (!(ee instanceof LiveSyncCouchDBReplicator)) return true;
const ne = await ee.connectRemoteCouchDBWithSetting(_, this.plugin.isMobile, true);
if ("string" == typeof ne) {
Logger("Could not connect to the database.", LOG_LEVEL_NOTICE);
return false;
} else if (await checkSyncInfo(ne.db)) return true; else {
Logger("Failed to read remote database", LOG_LEVEL_NOTICE);
return false;
}
}, applyEncryption = async _ => {
if (!this.editingSettings.encrypt || "" != this.editingSettings.passphrase) if (!this.editingSettings.encrypt || await testCrypt()) {
if (await checkWorkingPassphrase() || _) {
if (!this.editingSettings.encrypt) this.editingSettings.passphrase = "";
this.saveAllDirtySettings();
this.plugin.addOnSetup.suspendAllSync();
this.plugin.addOnSetup.suspendExtraSync();
this.reloadAllSettings();
this.editingSettings.isConfigured = true;
await this.saveAllDirtySettings();
if (_) await this.plugin.addOnSetup.rebuildRemote(); else {
await this.plugin.markRemoteResolved();
await this.plugin.replicate(true);
}
}
} else Logger("WARNING! Your device does not support encryption.", LOG_LEVEL_NOTICE); else Logger("If you enable encryption, you have to set the passphrase", LOG_LEVEL_NOTICE);
}, rebuildDB = async _ => {
if (!this.editingSettings.encrypt || "" != this.editingSettings.passphrase) if (!this.editingSettings.encrypt || await testCrypt()) {
if (!this.editingSettings.encrypt) this.editingSettings.passphrase = "";
this.applyAllSettings();
this.plugin.addOnSetup.suspendAllSync();
this.plugin.addOnSetup.suspendExtraSync();
this.reloadAllSettings();
this.editingSettings.isConfigured = true;
Logger("All synchronizations have been temporarily disabled. Please enable them after the fetching, if you need them.", LOG_LEVEL_NOTICE);
await this.saveAllDirtySettings();
this.closeSetting();
await delay(2e3);
await performRebuildDB(this.plugin, _);
} else Logger("WARNING! Your device does not support encryption.", LOG_LEVEL_NOTICE); else Logger("If you enable encryption, you have to set the passphrase", LOG_LEVEL_NOTICE);
};
new Setting2(xe).setClass("wizardOnly").addButton((_ => _.setButtonText("Next").setCta().setDisabled(false).onClick((() => {
if (!this.editingSettings.encrypt) this.editingSettings.passphrase = "";
if (isCloudantURI(this.editingSettings.couchDB_URI)) this.editingSettings = {
...this.editingSettings,
...PREFERRED_SETTING_CLOUDANT
}; else if (this.editingSettings.remoteType == REMOTE_MINIO) this.editingSettings = {
...this.editingSettings,
...PREFERRED_JOURNAL_SYNC
}; else this.editingSettings = {
...this.editingSettings,
...PREFERRED_SETTING_SELF_HOSTED
};
changeDisplay("30");
}))));
addScreenElement("0", xe);
const Re = oe.createDiv();
this.createEl(Re, "h3", {
text: "General Settings"
});
this.createEl(Re, "h4", {
text: "Appearance"
});
const Te = Object.fromEntries([ [ "", "Default" ], ...SUPPORTED_I18N_LANGS.map((_ => [ _, $t(`lang-${_}`) ])) ]);
new Setting2(Re).autoWireDropDown("displayLanguage", {
options: Te
});
this.addOnSaved("displayLanguage", (() => this.display()));
new Setting2(Re).autoWireToggle("showStatusOnEditor");
new Setting2(Re).autoWireToggle("showOnlyIconsOnEditor", {
onUpdate: visibleOnly((() => this.isConfiguredAs("showStatusOnEditor", true)))
});
new Setting2(Re).autoWireToggle("showStatusOnStatusbar");
this.createEl(Re, "h4", {
text: "Logging"
});
new Setting2(Re).autoWireToggle("lessInformationInLog");
new Setting2(Re).autoWireToggle("showVerboseLog", {
onUpdate: visibleOnly((() => this.isConfiguredAs("lessInformationInLog", false)))
});
this.createEl(Re, "h4", {
text: "Performance tweaks"
});
new Setting2(Re).autoWireNumeric("hashCacheMaxCount", {
clampMin: 10
});
new Setting2(Re).autoWireNumeric("hashCacheMaxAmount", {
clampMin: 1
});
this.createEl(Re, "h4", {
text: "Share settings via markdown"
});
new Setting2(Re).autoWireText("settingSyncFile", {
holdValue: true
}).addApplyButton([ "settingSyncFile" ]);
new Setting2(Re).autoWireToggle("writeCredentialsForSettingSync");
new Setting2(Re).autoWireToggle("notifyAllSettingSyncFile");
this.createEl(Re, "h4", {
text: "Advanced Confidentiality"
});
new Setting2(Re).setName("Encrypting sensitive configuration items").autoWireDropDown("configPassphraseStore", {
options: {
"": "Default",
LOCALSTORAGE: "Use a custom passphrase",
ASK_AT_LAUNCH: "Ask an passphrase at every launch"
},
holdValue: true
}).setClass("wizardHidden");
new Setting2(Re).autoWireText("configPassphrase", {
isPassword: true,
holdValue: true
}).setClass("wizardHidden").addOnUpdate((() => ({
disabled: !this.isConfiguredAs("configPassphraseStore", "LOCALSTORAGE")
})));
new Setting2(Re).addApplyButton([ "configPassphrase", "configPassphraseStore" ]).setClass("wizardHidden");
addScreenElement("20", Re);
const Pe = oe.createDiv();
this.createEl(Pe, "h3", {
text: "Sync Settings"
});
if ("" != this.editingSettings.versionUpFlash) {
const _ = this.createEl(Pe, "div", {
text: this.editingSettings.versionUpFlash,
cls: "op-warn sls-setting-hidden"
}, (ee => {
this.createEl(ee, "button", {
text: "I got it and updated."
}, (ee => {
ee.addClass("mod-cta");
ee.addEventListener("click", (async () => {
this.editingSettings.versionUpFlash = "";
await this.saveAllDirtySettings();
_.remove();
}));
}));
}), visibleOnly((() => !this.isConfiguredAs("versionUpFlash", ""))));
}
this.createEl(Pe, "div", {
text: "Please select any preset to complete the wizard.",
cls: "wizardOnly"
}).addClasses([ "op-warn-info" ]);
const Ie = this.editingSettings.remoteType == REMOTE_COUCHDB ? {
NONE: "",
LIVESYNC: "LiveSync",
PERIODIC: "Periodic w/ batch",
DISABLE: "Disable all automatic"
} : {
NONE: "",
PERIODIC: "Periodic w/ batch",
DISABLE: "Disable all automatic"
};
new Setting2(Pe).autoWireDropDown("preset", {
options: Ie,
holdValue: true
}).addButton((_ => {
_.setButtonText("Apply");
_.onClick((async () => {
await this.saveSettings([ "preset" ]);
}));
}));
this.addOnSaved("preset", (async _ => {
if ("" == _) {
Logger("Select any preset.", LOG_LEVEL_NOTICE);
return;
}
const ee = {
batchSave: false,
liveSync: false,
periodicReplication: false,
syncOnSave: false,
syncOnEditorSave: false,
syncOnStart: false,
syncOnFileOpen: false,
syncAfterMerge: false
}, ne = {
...ee,
liveSync: true
}, ie = {
...ee,
batchSave: true,
periodicReplication: true,
syncOnSave: false,
syncOnEditorSave: false,
syncOnStart: true,
syncOnFileOpen: true,
syncAfterMerge: true
};
if ("LIVESYNC" == _) {
this.editingSettings = {
...this.editingSettings,
...ne
};
Logger("Synchronization setting configured as LiveSync.", LOG_LEVEL_NOTICE);
} else if ("PERIODIC" == _) {
this.editingSettings = {
...this.editingSettings,
...ie
};
Logger("Synchronization setting configured as Periodic sync with batch database update.", LOG_LEVEL_NOTICE);
} else {
Logger("All synchronizations disabled.", LOG_LEVEL_NOTICE);
this.editingSettings = {
...this.editingSettings,
...ee
};
}
await this.saveAllDirtySettings();
await this.plugin.realizeSettingSyncMode();
if (Se) {
this.closeSetting();
if (!this.editingSettings.isConfigured) {
this.editingSettings.isConfigured = true;
await this.saveAllDirtySettings();
await rebuildDB("localOnly");
Logger("All done! Please set up subsequent devices with 'Copy current settings as a new setup URI' and 'Use the copied setup URI'.", LOG_LEVEL_NOTICE);
await this.plugin.addOnSetup.command_copySetupURI();
} else this.plugin.askReload();
}
}));
this.createEl(Pe, "h4", {
text: "Synchronization Methods"
}).addClass("wizardHidden");
const De = visibleOnly((() => !this.isConfiguredAs("syncMode", "LIVESYNC"))), Be = visibleOnly((() => this.isConfiguredAs("syncMode", "PERIODIC"))), Ne = this.editingSettings.remoteType == REMOTE_COUCHDB ? {
ONEVENTS: "On events",
PERIODIC: "Periodic and On events",
LIVESYNC: "LiveSync"
} : {
ONEVENTS: "On events",
PERIODIC: "Periodic and On events"
};
new Setting2(Pe).autoWireDropDown("syncMode", {
options: Ne
}).setClass("wizardHidden");
this.addOnSaved("syncMode", (async _ => {
this.editingSettings.liveSync = false;
this.editingSettings.periodicReplication = false;
if ("LIVESYNC" == _) this.editingSettings.liveSync = true; else if ("PERIODIC" == _) this.editingSettings.periodicReplication = true;
await this.saveSettings([ "liveSync", "periodicReplication" ]);
await this.plugin.realizeSettingSyncMode();
}));
new Setting2(Pe).autoWireNumeric("periodicReplicationInterval", {
clampMax: 5e3,
onUpdate: Be
}).setClass("wizardHidden");
new Setting2(Pe).setClass("wizardHidden").autoWireToggle("syncOnSave", {
onUpdate: De
});
new Setting2(Pe).setClass("wizardHidden").autoWireToggle("syncOnEditorSave", {
onUpdate: De
});
new Setting2(Pe).setClass("wizardHidden").autoWireToggle("syncOnFileOpen", {
onUpdate: De
});
new Setting2(Pe).setClass("wizardHidden").autoWireToggle("syncOnStart", {
onUpdate: De
});
new Setting2(Pe).setClass("wizardHidden").autoWireToggle("syncAfterMerge", {
onUpdate: De
});
this.createEl(Pe, "h4", {
text: "Deletions propagation"
}).addClass("wizardHidden");
new Setting2(Pe).setClass("wizardHidden").autoWireToggle("trashInsteadDelete");
new Setting2(Pe).setClass("wizardHidden").autoWireToggle("doNotDeleteFolder");
this.createEl(Pe, "h4", {
text: "Conflict resolution"
}).addClass("wizardHidden");
new Setting2(Pe).setClass("wizardHidden").autoWireToggle("resolveConflictsByNewerFile");
new Setting2(Pe).setClass("wizardHidden").autoWireToggle("checkConflictOnlyOnOpen");
new Setting2(Pe).setClass("wizardHidden").autoWireToggle("showMergeDialogOnlyOnActive");
this.createEl(Pe, "h4", {
text: "Compatibility"
}).addClass("wizardHidden");
new Setting2(Pe).setClass("wizardHidden").autoWireToggle("disableMarkdownAutoMerge");
new Setting2(Pe).setClass("wizardHidden").autoWireToggle("writeDocumentsIfConflicted");
this.createEl(Pe, "h4", {
text: "Hidden files"
}).addClass("wizardHidden");
new Setting2(Pe).setName("Hidden file synchronization").setClass("wizardHidden").settingEl.createDiv("").innerText = this.editingSettings.syncInternalFiles ? "🔁 : Enabled" : "⏹️ : Disabled";
if (this.editingSettings.syncInternalFiles) new Setting2(Pe).setName("Disable Hidden files sync").setClass("wizardHidden").addButton((_ => {
_.setButtonText("Disable").onClick((async () => {
this.editingSettings.syncInternalFiles = false;
await this.saveAllDirtySettings();
this.display();
}));
})); else new Setting2(Pe).setName("Enable Hidden files sync").setClass("wizardHidden").addButton((_ => {
_.setButtonText("Merge").onClick((async () => {
this.closeSetting();
await this.plugin.addOnSetup.configureHiddenFileSync("MERGE");
}));
})).addButton((_ => {
_.setButtonText("Fetch").onClick((async () => {
this.closeSetting();
await this.plugin.addOnSetup.configureHiddenFileSync("FETCH");
}));
})).addButton((_ => {
_.setButtonText("Overwrite").onClick((async () => {
this.closeSetting();
await this.plugin.addOnSetup.configureHiddenFileSync("OVERWRITE");
}));
}));
new Setting2(Pe).setClass("wizardHidden").autoWireToggle("syncInternalFilesBeforeReplication", {
onUpdate: visibleOnly((() => this.isConfiguredAs("watchInternalFileChanges", false)))
});
new Setting2(Pe).setClass("wizardHidden").autoWireNumeric("syncInternalFilesInterval", {
clampMin: 10,
acceptZero: true
});
const Me = "\\/node_modules\\/, \\/\\.git\\/, ^\\.git\\/, \\/obsidian-livesync\\/", Fe = Me + ",\\/workspace$ ,\\/workspace.json$,\\/workspace-mobile.json$", je = this.editingSettings.syncInternalFilesIgnorePatterns.split(",").map((_ => _.trim())).filter((_ => "" != _)), $e = new Setting2(Pe).setName("Hidden files ignore patterns").setClass("wizardHidden").setDesc("");
new MultipleRegExpControl_default({
target: $e.controlEl,
props: {
patterns: je,
originals: [ ...je ],
apply: async _ => {
this.editingSettings.syncInternalFilesIgnorePatterns = _.map((_ => _.trim())).filter((_ => "" != _)).join(", ");
await this.saveAllDirtySettings();
this.display();
}
}
});
const addDefaultPatterns = async _ => {
const ee = this.editingSettings.syncInternalFilesIgnorePatterns.split(",").map((_ => _.trim())).filter((_ => "" != _)), ne = _.split(",").map((_ => _.trim())).filter((_ => "" != _)), ie = new Set([ ...ee, ...ne ]);
this.editingSettings.syncInternalFilesIgnorePatterns = [ ...ie ].join(", ");
await this.saveAllDirtySettings();
this.display();
};
new Setting2(Pe).setName("Add default patterns").setClass("wizardHidden").addButton((_ => {
_.setButtonText("Default").onClick((async () => {
await addDefaultPatterns(Me);
}));
})).addButton((_ => {
_.setButtonText("Cross-platform").onClick((async () => {
await addDefaultPatterns(Fe);
}));
}));
this.createEl(Pe, "h4", {
text: "Performance tweaks"
}).addClass("wizardHidden");
new Setting2(Pe).setClass("wizardHidden").autoWireToggle("batchSave");
new Setting2(Pe).setClass("wizardHidden").autoWireNumeric("batchSaveMinimumDelay", {
acceptZero: true,
onUpdate: visibleOnly((() => this.isConfiguredAs("batchSave", true)))
});
new Setting2(Pe).setClass("wizardHidden").autoWireNumeric("batchSaveMaximumDelay", {
acceptZero: true,
onUpdate: visibleOnly((() => this.isConfiguredAs("batchSave", true)))
});
new Setting2(Pe).setClass("wizardHidden").autoWireNumeric("customChunkSize", {
clampMin: 0
});
new Setting2(Pe).setClass("wizardHidden").autoWireToggle("readChunksOnline", {
onUpdate: onlyOnCouchDB
});
new Setting2(Pe).setClass("wizardHidden").autoWireToggle("enableChunkSplitterV2");
this.createEl(Pe, "h4", {
text: (0, import_obsidian.sanitizeHTMLToDom)("Targets")
}).addClass("wizardHidden");
const Ge = new Setting2(Pe).setName("Synchronising files").setDesc("(RegExp) Empty to sync all files. Set filter as a regular expression to limit synchronising files.").setClass("wizardHidden");
new MultipleRegExpControl_default({
target: Ge.controlEl,
props: {
patterns: this.editingSettings.syncOnlyRegEx.split("|[]|"),
originals: [ ...this.editingSettings.syncOnlyRegEx.split("|[]|") ],
apply: async _ => {
this.editingSettings.syncOnlyRegEx = _.map((_ => _.trim())).filter((_ => "" != _)).join("|[]|");
await this.saveAllDirtySettings();
this.display();
}
}
});
const Ve = new Setting2(Pe).setName("Non-Synchronising files").setDesc("(RegExp) If this is set, any changes to local and remote files that match this will be skipped.").setClass("wizardHidden");
new MultipleRegExpControl_default({
target: Ve.controlEl,
props: {
patterns: this.editingSettings.syncIgnoreRegEx.split("|[]|"),
originals: [ ...this.editingSettings.syncIgnoreRegEx.split("|[]|") ],
apply: async _ => {
this.editingSettings.syncIgnoreRegEx = _.map((_ => _.trim())).filter((_ => "" != _)).join("|[]|");
await this.saveAllDirtySettings();
this.display();
}
}
});
new Setting2(Pe).setClass("wizardHidden").autoWireNumeric("syncMaxSizeInMB", {
clampMin: 0
});
new Setting2(Pe).setClass("wizardHidden").autoWireToggle("useIgnoreFiles");
new Setting2(Pe).setClass("wizardHidden").autoWireTextArea("ignoreFiles", {
onUpdate: visibleOnly((() => this.isConfiguredAs("useIgnoreFiles", true)))
});
this.createEl(Pe, "h4", {
text: (0, import_obsidian.sanitizeHTMLToDom)("Advanced settings")
}, void 0, onlyOnCouchDB).addClass("wizardHidden");
this.createEl(Pe, "div", {
text: "If you reached the payload size limit when using IBM Cloudant, please decrease batch size and batch limit to a lower value."
}, void 0, onlyOnCouchDB).addClass("wizardHidden");
new Setting2(Pe).setClass("wizardHidden").autoWireNumeric("batch_size", {
clampMin: 2,
onUpdate: onlyOnCouchDB
});
new Setting2(Pe).setClass("wizardHidden").autoWireNumeric("batches_limit", {
clampMin: 2,
onUpdate: onlyOnCouchDB
});
new Setting2(Pe).setClass("wizardHidden").autoWireToggle("useTimeouts", {
onUpdate: onlyOnCouchDB
});
new Setting2(Pe).setClass("wizardHidden").autoWireNumeric("concurrencyOfReadChunksOnline", {
clampMin: 10,
onUpdate: onlyOnCouchDB
});
new Setting2(Pe).setClass("wizardHidden").autoWireNumeric("minimumIntervalOfReadChunksOnline", {
clampMin: 10,
onUpdate: onlyOnCouchDB
});
addScreenElement("30", Pe);
const Ue = oe.createDiv();
this.createEl(Ue, "h3", {
text: "Hatch"
});
new Setting2(Ue).setName("Make report to inform the issue").addButton((_ => _.setButtonText("Make report").setDisabled(false).onClick((async () => {
let _ = {};
const ee = "𝑅𝐸𝐷𝐴𝐶𝑇𝐸𝐷";
if (this.editingSettings.remoteType == REMOTE_COUCHDB) try {
const ne = await requestToCouchDB(this.editingSettings.couchDB_URI, this.editingSettings.couchDB_USER, this.editingSettings.couchDB_PASSWORD, window.origin);
Logger(JSON.stringify(ne.json, null, 2));
_ = ne.json;
_["couch_httpd_auth"].secret = ee;
_["couch_httpd_auth"].authentication_db = ee;
_["couch_httpd_auth"].authentication_redirect = ee;
_["couchdb"].uuid = ee;
_["admins"] = ee;
} catch (ee) {
_ = "Requesting information from the remote CouchDB has failed. If you are using IBM Cloudant, this is normal behaviour.";
} else if (this.editingSettings.remoteType == REMOTE_MINIO) _ = "Object Storage Synchronisation";
const ne = JSON.parse(JSON.stringify(this.editingSettings));
ne.couchDB_DBNAME = ee;
ne.couchDB_PASSWORD = ee;
const ie = ne.couchDB_URI.startsWith("http:") ? "(HTTP)" : ne.couchDB_URI.startsWith("https:") ? "(HTTPS)" : "";
ne.couchDB_URI = isCloudantURI(ne.couchDB_URI) ? "cloudant" : `self-hosted${ie}`;
ne.couchDB_USER = ee;
ne.passphrase = ee;
ne.encryptedPassphrase = ee;
ne.encryptedCouchDBConnection = ee;
ne.accessKey = ee;
ne.secretKey = ee;
ne.region = `${ee}(${ne.region.length} letters)`;
ne.bucket = `${ee}(${ne.bucket.length} letters)`;
ne.pluginSyncExtendedSetting = {};
const re = ne.endpoint;
if ("" == re) ne.endpoint = "Not configured or AWS"; else {
const _ = ne.endpoint.startsWith("http:") ? "(HTTP)" : ne.endpoint.startsWith("https:") ? "(HTTPS)" : "";
ne.endpoint = `${-1 !== re.indexOf(".r2.cloudflarestorage.") ? "R2" : "self-hosted?"}(${_})`;
}
const se = `---- Obsidian info ----\n${navigator.userAgent}\n---- remote config ----\n${(0,
import_obsidian.stringifyYaml)(_)}\n---- Plug-in config ---\nversion:${ge}\n${(0,
import_obsidian.stringifyYaml)(ne)}`;
console.log(se);
await navigator.clipboard.writeText(se);
Logger("Information has been copied to clipboard", LOG_LEVEL_NOTICE);
}))));
if (null == (ie = null == (ne = this.plugin) ? void 0 : ne.replicator) ? void 0 : ie.remoteLockedAndDeviceNotAccepted) {
const _ = this.createEl(Ue, "div", {
text: "To prevent unwanted vault corruption, the remote database has been locked for synchronization, and this device was not marked as 'resolved'. It caused by some operations like this. Re-initialized. Local database initialization should be required. Please back your vault up, reset the local database, and press 'Mark this device as resolved'. "
});
this.createEl(_, "button", {
text: "I'm ready, mark this device 'resolved'"
}, (ee => {
ee.addClass("mod-warning");
ee.addEventListener("click", (async () => {
await this.plugin.markRemoteResolved();
_.remove();
}));
}));
_.addClass("op-warn");
} else if (null == (se = null == (re = this.plugin) ? void 0 : re.replicator) ? void 0 : se.remoteLocked) {
const _ = this.createEl(Ue, "div", {
text: "To prevent unwanted vault corruption, the remote database has been locked for synchronization. (This device is marked 'resolved') When all your devices are marked 'resolved', unlock the database."
});
this.createEl(_, "button", {
text: "I'm ready, unlock the database"
}, (ee => {
ee.addClass("mod-warning");
ee.addEventListener("click", (async () => {
await this.plugin.markRemoteUnlocked();
_.remove();
}));
}));
_.addClass("op-warn");
}
new Setting2(Ue).setName("Back to non-configured").addButton((_ => _.setButtonText("Back").setDisabled(false).onClick((async () => {
this.editingSettings.isConfigured = false;
await this.saveAllDirtySettings();
this.plugin.askReload();
}))));
this.createEl(Ue, "div", {
text: "To stop the boot up sequence for fixing problems on databases, you can put redflag.md on top of your vault (Rebooting obsidian is required)."
}).addClass("op-warn-info");
const addResult = (_, ee, ne) => {
ze.appendChild(this.createEl(ze, "div", {}, (ie => {
ie.appendChild(this.createEl(ie, "h6", {
text: _
}));
ie.appendChild(this.createEl(ie, "div", {}, (_ => {
_.appendChild(this.createEl(_, "div", {
text: "Storage : Modified: " + (!ee ? "Missing:" : `${new Date(ee.stat.mtime).toLocaleString()}, Size:${ee.stat.size}`)
}));
_.appendChild(this.createEl(_, "div", {
text: "Database: Modified: " + (!ne ? "Missing:" : `${new Date(ne.mtime).toLocaleString()}, Size:${ne.size}`)
}));
})));
if (ne && ee) ie.appendChild(this.createEl(ie, "button", {
text: "Show history"
}, (_ => {
_.onClickEvent((() => {
this.plugin.showHistory(ee, ne._id);
}));
})));
if (ee) ie.appendChild(this.createEl(ie, "button", {
text: "Storage -> Database"
}, (_ => {
_.onClickEvent((() => {
this.plugin.updateIntoDB(ee, void 0, true);
ie.remove();
}));
})));
if (ne) ie.appendChild(this.createEl(ie, "button", {
text: "Database -> Storage"
}, (_ => {
_.onClickEvent((() => {
this.plugin.pullFile(this.plugin.getPath(ne), [], true, void 0, false);
ie.remove();
}));
})));
return ie;
})));
}, checkBetweenStorageAndDatabase = async (_, ee) => {
const ne = readAsBlob(ee), ie = createBlob(await this.plugin.vaultAccess.vaultReadAuto(_));
if (await isDocContentSame(ie, ne)) Logger(`Compare: SAME: ${_.path}`); else {
Logger(`Compare: CONTENT IS NOT MATCHED! ${_.path}`, LOG_LEVEL_NOTICE);
addResult(_.path, _, ee);
}
};
new Setting2(Ue).setName("Verify and repair all files").setDesc("Compare the content of files between on local database and storage. If not matched, you will be asked which one you want to keep.").addButton((_ => _.setButtonText("Verify all").setDisabled(false).setWarning().onClick((async () => {
const _ = this.app.vault.getFiles(), ee = [], ne = this.plugin.localDatabase.findAllNormalDocs();
for await (const _ of ne) ee.push(this.plugin.getPath(_));
const ie = [ ...new Set([ ...ee, ..._.map((_ => _.path)) ]) ];
let re = 0;
for (const ee of ie) {
re++;
Logger(`${re}/${_.length}\n${ee}`, LOG_LEVEL_NOTICE, "verify");
if (shouldBeIgnored(ee)) continue;
const ne = this.plugin.vaultAccess.getAbstractFileByPath(ee), ie = ne instanceof import_obsidian5.TFile ? ne : false;
if (!await this.plugin.isTargetFile(ee)) continue;
if (ie && this.plugin.isFileSizeExceeded(ie.stat.size)) continue;
const se = await this.plugin.localDatabase.getDBEntry(ee);
if (!se || !this.plugin.isFileSizeExceeded(se.size)) if (se || !ie) if (!se || ie) {
if (ie && se) await checkBetweenStorageAndDatabase(ie, se);
} else {
Logger(`Compare: Not found on the storage: ${ee}`, LOG_LEVEL_NOTICE);
addResult(ee, false, se);
} else {
Logger(`Compare: Not found on the local database: ${ee}`, LOG_LEVEL_NOTICE);
addResult(ee, ie, false);
}
}
Logger("done", LOG_LEVEL_NOTICE, "verify");
}))));
const ze = Ue.createDiv({
text: ""
});
new Setting2(Ue).setName("Check and convert non-path-obfuscated files").setDesc("").addButton((_ => _.setButtonText("Perform").setDisabled(false).setWarning().onClick((async () => {
var _, ee, ne;
for await (const ie of this.plugin.localDatabase.findAllDocNames()) if (!ie.startsWith("f:")) {
const re = await this.plugin.path2id(ie), se = await this.plugin.localDatabase.getRaw(ie);
if (!se) continue;
if ("newnote" != se.type && "plain" != se.type) continue;
if (null != (_ = null == se ? void 0 : se.deleted) ? _ : false) continue;
const oe = {
...se
};
oe._id = re;
oe.path = ie;
delete oe._rev;
try {
const _ = await this.plugin.localDatabase.getRaw(re, {
revs_info: true
});
null == (ee = _._revs_info) || ee.shift();
const le = null == (ne = _._revs_info) ? void 0 : ne.shift();
if (le) oe._rev = le.rev; else oe._rev = "1-" + `00000000000000000000000000000000${~~(1e9 * Math.random())}${~~(1e9 * Math.random())}${~~(1e9 * Math.random())}${~~(1e9 * Math.random())}`.slice(-32);
const ue = await this.plugin.localDatabase.putRaw(oe, {
force: true
});
if (ue.ok) {
Logger(`${ie} has been converted as conflicted document`, LOG_LEVEL_NOTICE);
se._deleted = true;
if ((await this.plugin.localDatabase.putRaw(se)).ok) Logger(`Old ${ie} has been deleted`, LOG_LEVEL_NOTICE);
await this.plugin.queueConflictCheck(ie);
} else {
Logger(`Converting ${ie} Failed!`, LOG_LEVEL_NOTICE);
Logger(ue, LOG_LEVEL_VERBOSE);
}
} catch (_) {
if (404 == (null == _ ? void 0 : _.status)) {
if ((await this.plugin.localDatabase.putRaw(oe)).ok) {
Logger(`${ie} has been converted`, LOG_LEVEL_NOTICE);
se._deleted = true;
if ((await this.plugin.localDatabase.putRaw(se)).ok) Logger(`Old ${ie} has been deleted`, LOG_LEVEL_NOTICE);
}
} else {
Logger(`Something went wrong while converting ${ie}`, LOG_LEVEL_NOTICE);
Logger(_, LOG_LEVEL_VERBOSE);
}
}
}
Logger("Converting finished", LOG_LEVEL_NOTICE);
}))));
new Setting2(Ue).setName("Delete all customization sync data").addButton((_ => _.setButtonText("Delete").setDisabled(false).setWarning().onClick((async () => {
Logger("Deleting customization sync data", LOG_LEVEL_NOTICE);
const _ = (await this.plugin.localDatabase.allDocsRaw({
startkey: "ix:",
endkey: "ix:",
include_docs: true
})).rows.map((_ => ({
..._.doc,
_deleted: true
})));
Logger(`${(await this.plugin.localDatabase.bulkDocsRaw(_)).length} items have been removed, to confirm how many items are left, please perform it again.`, LOG_LEVEL_NOTICE);
}))));
new Setting2(Ue).autoWireToggle("suspendFileWatching");
this.addOnSaved("suspendFileWatching", (() => this.plugin.askReload()));
new Setting2(Ue).autoWireToggle("suspendParseReplicationResult");
this.addOnSaved("suspendParseReplicationResult", (() => this.plugin.askReload()));
new Setting2(Ue).autoWireToggle("writeLogToTheFile");
this.createEl(Ue, "h4", {
text: (0, import_obsidian.sanitizeHTMLToDom)("Compatibility"),
cls: "wizardHidden"
});
new Setting2(Ue).setClass("wizardHidden").autoWireToggle("deleteMetadataOfDeletedFiles");
new Setting2(Ue).setClass("wizardHidden").autoWireNumeric("automaticallyDeleteMetadataOfDeletedFiles", {
onUpdate: visibleOnly((() => this.isConfiguredAs("deleteMetadataOfDeletedFiles", true)))
});
new Setting2(Ue).autoWireToggle("useIndexedDBAdapter", {
invert: true
});
this.addOnSaved("useIndexedDBAdapter", (async () => {
await this.saveAllDirtySettings();
await rebuildDB("localOnly");
}));
new Setting2(Ue).autoWireToggle("watchInternalFileChanges", {
invert: true
});
new Setting2(Ue).autoWireText("additionalSuffixOfDatabaseName", {
holdValue: true
}).addApplyButton([ "additionalSuffixOfDatabaseName" ]);
this.addOnSaved("additionalSuffixOfDatabaseName", (async _ => {
Logger("Suffix has been changed. Reopening database...", LOG_LEVEL_NOTICE);
await this.plugin.initializeDatabase();
}));
new Setting2(Ue).autoWireDropDown("hashAlg", {
options: {
"": "Old Algorithm",
xxhash32: "xxhash32 (Fast)",
xxhash64: "xxhash64 (Fastest)",
sha1: "Fallback (Without WebAssembly)"
}
});
this.addOnSaved("hashAlg", (async () => {
await this.plugin.localDatabase.prepareHashFunctions();
}));
new Setting2(Ue).autoWireToggle("doNotSuspendOnFetching");
new Setting2(Ue).autoWireToggle("disableCheckingConfigMismatch");
new Setting2(Ue).autoWireToggle("disableWorkerForGeneratingChunks");
new Setting2(Ue).autoWireToggle("processSmallFilesInUIThread", {
onUpdate: visibleOnly((() => this.isConfiguredAs("disableWorkerForGeneratingChunks", false)))
});
addScreenElement("50", Ue);
const qe = oe.createDiv();
this.createEl(qe, "h3", {
text: "Customization sync (beta)"
});
const He = enableOnly((() => this.isConfiguredAs("usePluginSync", false))), Ke = visibleOnly((() => this.isConfiguredAs("usePluginSync", true)));
new Setting2(qe).autoWireText("deviceAndVaultName", {
placeHolder: "desktop",
onUpdate: He
});
new Setting2(qe).autoWireToggle("usePluginSync", {
onUpdate: enableOnly((() => !this.isConfiguredAs("deviceAndVaultName", "")))
});
new Setting2(qe).autoWireToggle("autoSweepPlugins", {
onUpdate: Ke
});
new Setting2(qe).autoWireToggle("autoSweepPluginsPeriodic", {
onUpdate: visibleOnly((() => this.isConfiguredAs("usePluginSync", true) && this.isConfiguredAs("autoSweepPlugins", true)))
});
new Setting2(qe).autoWireToggle("notifyPluginOrSettingUpdated", {
onUpdate: Ke
});
new Setting2(qe).setName("Open").setDesc("Open the dialog").addButton((_ => {
_.setButtonText("Open").setDisabled(false).onClick((() => {
this.plugin.addOnConfigSync.showPluginSyncModal();
}));
})).addOnUpdate(Ke);
addScreenElement("60", qe);
const We = oe.createDiv();
this.createEl(We, "h3", {
text: "Maintenance"
});
this.createEl(We, "h4", {
text: "Remote"
});
new Setting2(We).setName("Perform compaction").setDesc("Compaction discards all of Eden in the non-latest revisions, reducing the storage usage. However, this operation requires the same free space on the remote as the current database.").addButton((_ => _.setButtonText("Perform").setDisabled(false).onClick((async () => {
const _ = this.plugin.replicator;
Logger("Compaction has been began", LOG_LEVEL_NOTICE, "compaction");
if (await _.compactRemote(this.editingSettings)) Logger("Compaction has been completed!", LOG_LEVEL_NOTICE, "compaction"); else Logger("Compaction has been failed!", LOG_LEVEL_NOTICE, "compaction");
})))).addOnUpdate(onlyOnCouchDB);
new Setting2(We).setName("Lock remote").setDesc("Lock remote to prevent synchronization with other devices.").addButton((_ => _.setButtonText("Lock").setDisabled(false).setWarning().onClick((async () => {
await this.plugin.markRemoteLocked();
}))));
new Setting2(We).setName("Overwrite remote").setDesc("Overwrite remote with local DB and passphrase.").addButton((_ => _.setButtonText("Send").setWarning().setDisabled(false).onClick((async () => {
await rebuildDB("remoteOnly");
}))));
new Setting2(We).setName("Reset journal received history").setDesc("Initialise journal received history. On the next sync, every item except this device sent will be downloaded again.").addButton((_ => _.setButtonText("Reset received").setWarning().setDisabled(false).onClick((async () => {
await this.plugin.getMinioJournalSyncClient().updateCheckPointInfo((_ => ({
..._,
receivedFiles: new Set,
knownIDs: new Set
})));
Logger("Journal received history has been cleared.", LOG_LEVEL_NOTICE);
})))).addOnUpdate(onlyOnMinIO);
new Setting2(We).setName("Reset journal sent history").setDesc("Initialise journal sent history. On the next sync, every item except this device received will be sent again.").addButton((_ => _.setButtonText("Reset sent history").setWarning().setDisabled(false).onClick((async () => {
await this.plugin.getMinioJournalSyncClient().updateCheckPointInfo((_ => ({
..._,
lastLocalSeq: 0,
sentIDs: new Set,
sentFiles: new Set
})));
Logger("Journal sent history has been cleared.", LOG_LEVEL_NOTICE);
})))).addOnUpdate(onlyOnMinIO);
new Setting2(We).setName("Reset all journal counter").setDesc("Initialise all journal history, On the next sync, every item will be received and sent.").addButton((_ => _.setButtonText("Reset all").setWarning().setDisabled(false).onClick((async () => {
await this.plugin.getMinioJournalSyncClient().resetCheckpointInfo();
Logger("Journal exchange history has been cleared.", LOG_LEVEL_NOTICE);
})))).addOnUpdate(onlyOnMinIO);
new Setting2(We).setName("Purge all journal counter").setDesc("Purge all sending and downloading cache.").addButton((_ => _.setButtonText("Reset all").setWarning().setDisabled(false).onClick((async () => {
await this.plugin.getMinioJournalSyncClient().resetAllCaches();
Logger("Journal sending and downloading cache has been cleared.", LOG_LEVEL_NOTICE);
})))).addOnUpdate(onlyOnMinIO);
new Setting2(We).setName("Make empty the bucket").setDesc("Delete all data on the remote.").addButton((_ => _.setButtonText("Delete").setWarning().setDisabled(false).onClick((async () => {
await this.plugin.getMinioJournalSyncClient().updateCheckPointInfo((_ => ({
..._,
receivedFiles: new Set,
knownIDs: new Set,
lastLocalSeq: 0,
sentIDs: new Set,
sentFiles: new Set
})));
await this.plugin.resetRemoteBucket();
Logger("the bucket has been cleared.", LOG_LEVEL_NOTICE);
})))).addOnUpdate(onlyOnMinIO);
this.createEl(We, "h4", {
text: "Local database"
});
new Setting2(We).setName("Fetch from remote").setDesc("Restore or reconstruct local database from remote.").addButton((_ => _.setButtonText("Fetch").setWarning().setDisabled(false).onClick((async () => {
await this.plugin.vaultAccess.vaultCreate(FLAGMD_REDFLAG3_HR, "");
this.plugin.performAppReload();
})))).addButton((_ => _.setButtonText("Fetch w/o restarting").setWarning().setDisabled(false).onClick((async () => {
await rebuildDB("localOnly");
}))));
new Setting2(We).setName("Fetch rebuilt DB (Save local documents before)").setDesc("Restore or reconstruct local database from remote database but use local chunks.").addButton((_ => _.setButtonText("Save and Fetch").setWarning().setDisabled(false).onClick((async () => {
await rebuildDB("localOnlyWithChunks");
})))).addOnUpdate(onlyOnCouchDB);
new Setting2(We).setName("Discard local database to reset or uninstall Self-hosted LiveSync").addButton((_ => _.setButtonText("Discard").setWarning().setDisabled(false).onClick((async () => {
await this.plugin.resetLocalDatabase();
await this.plugin.initializeDatabase();
}))));
this.createEl(We, "h4", {
text: "Both databases"
});
new Setting2(We).setName("(Beta2) Clean up databases").setDesc("Delete unused chunks to shrink the database. This feature requires disabling 'Use an old adapter for compatibility'").addButton((_ => _.setButtonText("DryRun").setDisabled(false).onClick((async () => {
await this.plugin.dryRunGC();
})))).addButton((_ => _.setButtonText("Perform cleaning").setDisabled(false).setWarning().onClick((async () => {
this.closeSetting();
await this.plugin.dbGC();
})))).addOnUpdate(onlyOnCouchDB);
new Setting2(We).setName("Rebuild everything").setDesc("Rebuild local and remote database with local files.").addButton((_ => _.setButtonText("Rebuild").setWarning().setDisabled(false).onClick((async () => {
await this.plugin.vaultAccess.vaultCreate(FLAGMD_REDFLAG2_HR, "");
this.plugin.performAppReload();
})))).addButton((_ => _.setButtonText("Rebuild w/o restarting").setWarning().setDisabled(false).onClick((async () => {
await rebuildDB("rebuildBothByThisDevice");
}))));
addScreenElement("70", We);
if ("" == this.selectedScreen) if (me != this.editingSettings.lastReadUpdates) if (this.editingSettings.isConfigured) changeDisplay("100"); else changeDisplay("110"); else if (isAnySyncEnabled()) changeDisplay("20"); else changeDisplay("110"); else changeDisplay(this.selectedScreen);
this.requestUpdate();
}
};
function isImage(_) {
const ee = _.split(".").splice(-1)[0].toLowerCase();
return [ "png", "jpg", "jpeg", "gif", "bmp", "webp" ].includes(ee);
}
function isComparableText(_) {
const ee = _.split(".").splice(-1)[0].toLowerCase();
return isPlainText(_) || [ "md", "mdx", "txt", "json" ].includes(ee);
}
function isComparableTextDecode(_) {
const ee = _.split(".").splice(-1)[0].toLowerCase();
return [ "json" ].includes(ee);
}
function readDocument(_) {
if (0 == _.data.length) return "";
if (isImage(_.path)) return new Uint8Array(decodeBinary(_.data));
if ("plain" == _.type || "plain" == _.datatype) return getDocData(_.data);
if (isComparableTextDecode(_.path)) return readString(new Uint8Array(decodeBinary(_.data)));
if (isComparableText(_.path)) return getDocData(_.data);
try {
return readString(new Uint8Array(decodeBinary(_.data)));
} catch (_) {}
return getDocData(_.data);
}
var DocumentHistoryModal = class extends import_obsidian.Modal {
constructor(_, ee, ne, ie, re) {
super(_);
this.showDiff = false;
this.revs_info = [];
this.currentText = "";
this.currentDeleted = false;
this.BlobURLs = new Map;
this.plugin = ee;
this.file = ne instanceof import_obsidian.TFile ? getPathFromTFile(ne) : ne;
this.id = ie;
this.initialRev = re;
if (!ne && ie) this.file = this.plugin.id2path(ie);
if ("1" == localStorage.getItem("ols-history-highlightdiff")) this.showDiff = true;
}
async loadFile(_) {
var ee, ne;
if (!this.id) this.id = await this.plugin.path2id(this.file);
const ie = this.plugin.localDatabase;
try {
const re = await ie.getRaw(this.id, {
revs_info: true
});
this.revs_info = null != (ne = null == (ee = re._revs_info) ? void 0 : ee.filter((_ => "available" == (null == _ ? void 0 : _.status)))) ? ne : [];
this.range.max = `${Math.max(this.revs_info.length - 1, 0)}`;
this.range.value = this.range.max;
this.fileInfo.setText(`${this.file} / ${this.revs_info.length} revisions`);
await this.loadRevs(_);
} catch (_) {
if (isErrorOfMissingDoc(_)) {
this.range.max = "0";
this.range.value = "";
this.range.disabled = true;
this.contentView.setText("History of this file was not recorded.");
} else {
this.contentView.setText("Error occurred.");
Logger(_, LOG_LEVEL_VERBOSE);
}
}
}
async loadRevs(_) {
if (0 == this.revs_info.length) return;
if (_) {
const ee = this.revs_info.findIndex((ee => ee.rev == _));
if (ee >= 0) this.range.value = "" + (this.revs_info.length - 1 - ee);
}
const ee = this.revs_info.length - 1 - this.range.value / 1, ne = this.revs_info[ee];
await this.showExactRev(ne.rev);
}
revokeURL(_) {
const ee = this.BlobURLs.get(_);
if (ee) URL.revokeObjectURL(ee);
this.BlobURLs.delete(_);
}
generateBlobURL(_, ee) {
this.revokeURL(_);
const ne = URL.createObjectURL(new Blob([ ee ], {
endings: "transparent",
type: "application/octet-stream"
}));
this.BlobURLs.set(_, ne);
return ne;
}
async showExactRev(_) {
const ee = this.plugin.localDatabase, ne = await ee.getDBEntry(this.file, {
rev: _
}, false, false, true);
this.currentText = "";
this.currentDeleted = false;
if (false === ne) {
this.currentDeleted = true;
this.info.innerHTML = "";
this.contentView.innerHTML = `Could not read this revision
(${_})`;
} else {
this.currentDoc = ne;
this.info.innerHTML = `Modified:${new Date(ne.mtime).toLocaleString()}`;
let _;
const ie = readDocument(ne);
this.currentDeleted = !!ne.deleted;
if (this.showDiff) {
const ne = this.revs_info.length - 1 - (this.range.value / 1 - 1);
if (ne >= 0 && ne < this.revs_info.length) {
const re = this.revs_info[ne].rev, se = await ee.getDBEntry(this.file, {
rev: re
}, false, false, true);
if (false != se) if ("string" == typeof ie) {
_ = "";
const ee = new import_diff_match_patch.diff_match_patch, ne = readDocument(se), re = ee.diff_main(ne, ie);
ee.diff_cleanupSemantic(re);
for (const ee of re) {
const ne = ee[0], ie = ee[1];
if (ne == import_diff_match_patch.DIFF_DELETE) _ += "" + escapeStringToHTML(ie) + ""; else if (ne == import_diff_match_patch.DIFF_EQUAL) _ += "" + escapeStringToHTML(ie) + ""; else if (ne == import_diff_match_patch.DIFF_INSERT) _ += "" + escapeStringToHTML(ie) + "";
}
_ = _.replace(/\n/g, "
");
} else if (isImage(this.file)) {
_ = `\n
\n

\n
)})
\n
\n
`;
this.contentView.removeClass("op-pre");
}
}
}
if (null == _) if ("string" != typeof ie) {
if (isImage(this.file)) {
_ = `\n
\n

\n
\n
`;
this.contentView.removeClass("op-pre");
}
} else _ = escapeStringToHTML(ie);
if (null == _) _ = "string" == typeof ie ? escapeStringToHTML(ie) : "Binary file";
this.contentView.innerHTML = (this.currentDeleted ? "(At this revision, the file has been deleted)\n" : "") + _;
}
}
onOpen() {
const {contentEl: _} = this;
this.titleEl.setText("Document History");
_.empty();
this.fileInfo = _.createDiv("");
this.fileInfo.addClass("op-info");
const ee = _.createDiv("");
ee.addClass("op-flex");
ee.createEl("input", {
type: "range"
}, (_ => {
this.range = _;
_.addEventListener("change", (_ => {
this.loadRevs();
}));
_.addEventListener("input", (_ => {
this.loadRevs();
}));
}));
_.createDiv("", (_ => {
_.createEl("label", {}, (_ => {
_.appendChild(createEl("input", {
type: "checkbox"
}, (_ => {
if (this.showDiff) _.checked = true;
_.addEventListener("input", (ee => {
this.showDiff = _.checked;
localStorage.setItem("ols-history-highlightdiff", true == this.showDiff ? "1" : "");
this.loadRevs();
}));
})));
_.appendText("Highlight diff");
}));
})).addClass("op-info");
this.info = _.createDiv("");
this.info.addClass("op-info");
this.loadFile(this.initialRev);
const ne = _.createDiv({
text: "Loading old revisions..."
});
this.contentView = ne;
ne.addClass("op-scrollable");
ne.addClass("op-pre");
const ie = _.createDiv("");
ie.createEl("button", {
text: "Copy to clipboard"
}, (_ => {
_.addClass("mod-cta");
_.addEventListener("click", (async () => {
await navigator.clipboard.writeText(this.currentText);
Logger("Old content copied to clipboard", LOG_LEVEL_NOTICE);
}));
}));
const focusFile = async _ => {
const ee = this.plugin.app.vault.getFileByPath(_);
if (ee) {
const _ = this.plugin.app.workspace.getLeaf(false);
await _.openFile(ee);
} else Logger("The file could not view on the editor", LOG_LEVEL_NOTICE);
};
ie.createEl("button", {
text: "Back to this revision"
}, (_ => {
_.addClass("mod-cta");
_.addEventListener("click", (async () => {
const _ = stripPrefix(this.file);
if (!isValidPath(_)) {
Logger("Path is not valid to write content.", LOG_LEVEL_INFO);
return;
}
if (!this.currentDoc) {
Logger("No active file loaded.", LOG_LEVEL_INFO);
return;
}
const ee = readContent(this.currentDoc);
await this.plugin.vaultAccess.adapterWrite(_, ee);
await focusFile(_);
this.close();
}));
}));
}
onClose() {
const {contentEl: _} = this;
_.empty();
this.BlobURLs.forEach((_ => {
console.log(_);
if (_) URL.revokeObjectURL(_);
}));
}
}, WrappedNotice = class {
constructor(_, ee) {
var ne;
let ie = "";
if (_ instanceof DocumentFragment) ie = null != (ne = _.textContent) ? ne : ""; else ie = _;
Logger(ie, LOG_LEVEL_NOTICE);
}
setMessage(_) {
var ee;
let ne = "";
if (_ instanceof DocumentFragment) ne = null != (ee = _.textContent) ? ee : ""; else ne = _;
Logger(ne, LOG_LEVEL_NOTICE);
return this;
}
hide() {}
}, _notice = WrappedNotice;
function setNoticeClass(_) {
_notice = _;
}
var idbProxyableTypes, cursorAdvanceMethods, StorageEventManager = class {}, StorageEventManagerObsidian = class extends StorageEventManager {
constructor(_) {
super();
this.totalQueued = reactiveSource(0);
this.batched = reactiveSource(0);
this.processing = reactiveSource(0);
this.bufferedQueuedItems = [];
this.concurrentProcessing = Semaphore(5);
this.waitedSince = new Map;
this.processingCount = 0;
this.plugin = _;
}
get shouldBatchSave() {
return this.plugin.shouldBatchSave;
}
get batchSaveMinimumDelay() {
return this.plugin.batchSaveMinimumDelay;
}
get batchSaveMaximumDelay() {
return this.plugin.batchSaveMaximumDelay;
}
beginWatch() {
const _ = this.plugin;
this.watchVaultChange = this.watchVaultChange.bind(this);
this.watchVaultCreate = this.watchVaultCreate.bind(this);
this.watchVaultDelete = this.watchVaultDelete.bind(this);
this.watchVaultRename = this.watchVaultRename.bind(this);
this.watchVaultRawEvents = this.watchVaultRawEvents.bind(this);
_.registerEvent(_.app.vault.on("modify", this.watchVaultChange));
_.registerEvent(_.app.vault.on("delete", this.watchVaultDelete));
_.registerEvent(_.app.vault.on("rename", this.watchVaultRename));
_.registerEvent(_.app.vault.on("create", this.watchVaultCreate));
_.registerEvent(_.app.vault.on("raw", this.watchVaultRawEvents));
}
watchVaultCreate(_, ee) {
this.appendQueue([ {
type: "CREATE",
file: _
} ], ee);
}
watchVaultChange(_, ee) {
this.appendQueue([ {
type: "CHANGED",
file: _
} ], ee);
}
watchVaultDelete(_, ee) {
this.appendQueue([ {
type: "DELETE",
file: _
} ], ee);
}
watchVaultRename(_, ee, ne) {
if (_ instanceof import_obsidian.TFile) this.appendQueue([ {
type: "DELETE",
file: {
path: ee,
mtime: _.stat.mtime,
ctime: _.stat.ctime,
size: _.stat.size,
deleted: true
},
skipBatchWait: true
}, {
type: "CREATE",
file: _,
skipBatchWait: true
} ], ne);
}
watchVaultRawEvents(_) {
if (this.plugin.settings.useIgnoreFiles && this.plugin.ignoreFiles.some((ee => _.endsWith(ee.trim())))) this.plugin.isTargetFile(_).then((() => this._watchVaultRawEvents(_))); else this._watchVaultRawEvents(_);
}
_watchVaultRawEvents(_) {
if (this.plugin.settings.syncInternalFiles || this.plugin.settings.usePluginSync) if (this.plugin.settings.watchInternalFileChanges) if (_.startsWith(this.plugin.app.vault.configDir)) if (!this.plugin.settings.syncInternalFilesIgnorePatterns.replace(/\n| /g, "").split(",").filter((_ => _)).map((_ => new RegExp(_, "i"))).some((ee => _.match(ee)))) this.appendQueue([ {
type: "INTERNAL",
file: {
path: _,
mtime: 0,
ctime: 0,
size: 0
}
} ], null);
}
async appendQueue(_, ee) {
var ne;
if (!this.plugin.settings.isConfigured) return;
if (this.plugin.settings.suspendFileWatching) return;
const ie = new Set;
for (const re of _) {
if (shouldBeIgnored(re.file.path)) continue;
const _ = [ 0, 0, 0, 0, 0, 0 ].map((_ => `${Math.floor(1e5 * Math.random())}`)).join("-"), se = re.type, oe = re.file, le = re.oldPath, ue = oe instanceof import_obsidian.TFile ? oe.stat.size : null != (ne = null == oe ? void 0 : oe.size) ? ne : 0;
if (this.plugin.isFileSizeExceeded(ue) && ("CREATE" == se || "CHANGED" == se)) {
Logger(`The storage file has been changed but exceeds the maximum size. Skipping: ${re.file.path}`, LOG_LEVEL_NOTICE);
continue;
}
if (oe instanceof import_obsidian.TFolder) continue;
if (!await this.plugin.isTargetFile(oe.path)) continue;
if (oe instanceof import_obsidian.TFile && ("CREATE" == se || "CHANGED" == se)) {
await delay(10);
if (this.plugin.vaultAccess.recentlyTouched(oe)) continue;
}
const de = oe instanceof import_obsidian.TFile ? {
ctime: oe.stat.ctime,
mtime: oe.stat.mtime,
file: oe,
path: oe.path,
size: oe.stat.size
} : oe;
let fe;
if (re.cachedData) fe = re.cachedData;
this.enqueue({
type: se,
args: {
file: de,
oldPath: le,
cache: fe,
ctx: ee
},
skipBatchWait: re.skipBatchWait,
key: _
});
ie.add(oe.path);
if (le) ie.add(le);
}
for (const _ of ie) fireAndForget((() => this.startStandingBy(_)));
}
enqueue(_) {
const ee = _.args.file.path;
if (this.shouldBatchSave) {
Logger(`Request cancel for waiting of previous ${ee}`, LOG_LEVEL_DEBUG);
finishWaitingForTimeout(`storage-event-manager-batchsave-${ee}`);
}
this.bufferedQueuedItems.push(_);
if ("DELETE" == _.type || "RENAME" == _.type) return this.flushQueue();
}
async startStandingBy(_) {
await skipIfDuplicated(`storage-event-manager-${_}`, (async () => {
Logger(`Processing ${_}: Starting`, LOG_LEVEL_DEBUG);
const ee = await this.concurrentProcessing.acquire();
try {
Logger(`Processing ${_}: Started`, LOG_LEVEL_DEBUG);
let ee = false;
do {
const ne = this.bufferedQueuedItems.find((ee => ee.args.file.path == _));
if (void 0 === ne) {
ee = true;
break;
}
const ie = ne.type, re = ne.type;
if (!ne.cancelled) {
if (!ne.skipBatchWait) {
if (this.shouldBatchSave && ("CREATE" == re || "CHANGED" == re)) {
const ee = this.waitedSince.get(_);
let re = true;
const se = Date.now();
if (void 0 !== ee) if (ee + 1e3 * this.batchSaveMaximumDelay < se) {
Logger(`Processing ${_}: Could not wait no more: ${ie}`, LOG_LEVEL_INFO);
re = false;
}
if (re) {
if (void 0 === ee) this.waitedSince.set(_, se);
ne.batched = true;
Logger(`Processing ${_}: Waiting for batch save delay: ${ie}`, LOG_LEVEL_DEBUG);
this.updateStatus();
if (!await waitForTimeout(`storage-event-manager-batchsave-${_}`, 1e3 * this.batchSaveMinimumDelay)) {
Logger(`Processing ${_}: Cancelled by new queue: ${ie}`, LOG_LEVEL_DEBUG);
this.cancelStandingBy(ne);
continue;
}
}
}
} else Logger(`Processing ${_}:Requested to perform immediately ${_}: ${ie}`, LOG_LEVEL_DEBUG);
Logger(`Processing ${_}: Request main to process: ${ie}`, LOG_LEVEL_DEBUG);
this.requestProcessQueue(ne);
} else {
Logger(`Processing ${_}: Cancelled (scheduled): ${ie}`, LOG_LEVEL_DEBUG);
this.cancelStandingBy(ne);
}
} while (!ee);
} finally {
ee();
}
Logger(`Processing ${_}: Finished`, LOG_LEVEL_DEBUG);
}));
}
cancelStandingBy(_) {
this.bufferedQueuedItems.remove(_);
this.updateStatus();
}
async requestProcessQueue(_) {
try {
this.processingCount++;
this.bufferedQueuedItems.remove(_);
this.updateStatus();
this.waitedSince.delete(_.args.file.path);
await this.plugin.handleFileEvent(_);
} finally {
this.processingCount--;
this.updateStatus();
}
}
isWaiting(_) {
return isWaitingForTimeout(`storage-event-manager-batchsave-${_}`);
}
flushQueue() {
this.bufferedQueuedItems.forEach((_ => _.skipBatchWait = true));
finishAllWaitingForTimeout("storage-event-manager-batchsave-", true);
}
cancelQueue(_) {
this.bufferedQueuedItems.forEach((ee => {
if (ee.key === _) ee.skipBatchWait = true;
}));
}
updateStatus() {
const _ = this.bufferedQueuedItems.filter((_ => !_.cancelled));
this.batched.value = _.filter((_ => _.batched && !_.skipBatchWait)).length;
this.processing.value = this.processingCount;
this.totalQueued.value = _.length - this.batched.value;
}
}, LiveSyncLocalDB = class {
constructor(_, ee) {
this.isReady = false;
this.xxhash64 = false;
this.hashCaches = new LRUCache(10, 1e3);
this.changeHandler = null;
this.chunkVersion = -1;
this.maxChunkVersion = -1;
this.minChunkVersion = -1;
this.needScanning = false;
this._chunkCollectProcessor = new QueueProcessor((async _ => {
try {
const ee = await this._collectChunks(_, false);
if (ee) ee.forEach((_ => sendValue(`chunk-fetch-${_._id}`, _))); else throw new Error("Failed: CollectChunksInternal");
} catch (ee) {
Logger("Exception raised while retrieving chunks", LOG_LEVEL_NOTICE);
Logger(ee, LOG_LEVEL_VERBOSE);
_.forEach((_ => sendValue(`chunk-fetch-${_}`, [])));
}
}), {
batchSize: 100,
interval: 100,
concurrentLimit: 1,
maintainDelay: true,
suspended: false,
totalRemainingReactiveSource: collectingChunks
});
this.auth = {
username: "",
password: ""
};
this.dbname = _;
this.env = ee;
this.refreshSettings();
}
get isOnDemandChunkEnabled() {
if (this.settings.remoteType !== REMOTE_COUCHDB) return false; else return this.settings.readChunksOnline;
}
onunload() {
var _, ee;
this.env.beforeOnUnload(this);
null == (_ = this.changeHandler) || _.cancel();
null == (ee = this.changeHandler) || ee.removeAllListeners();
this.localDatabase.removeAllListeners();
}
refreshSettings() {
const _ = this.env.getSettings();
this.settings = _;
this.hashCaches = new LRUCache(_.hashCacheMaxCount, _.hashCacheMaxAmount);
}
id2path(_, ee, ne) {
return this.env.id2path(_, ee, ne);
}
async path2id(_, ee) {
return await this.env.path2id(_, ee);
}
async close() {
var _, ee;
Logger("Database closed (by close)");
this.isReady = false;
null == (_ = this.changeHandler) || _.cancel();
null == (ee = this.changeHandler) || ee.removeAllListeners();
if (null != this.localDatabase) await this.localDatabase.close();
this.env.onClose(this);
}
async initializeDatabase() {
var _, ee;
await this.prepareHashFunctions();
if (null != this.localDatabase) await this.localDatabase.close();
null == (_ = this.changeHandler) || _.cancel();
null == (ee = this.changeHandler) || ee.removeAllListeners();
this.localDatabase = null;
this.localDatabase = this.env.createPouchDBInstance(this.dbname + "-livesync-v2", {
auto_compaction: false,
revs_limit: 100,
deterministic_revs: true
});
await this.env.onInitializeDatabase(this);
Logger("Opening Database...");
Logger("Database info", LOG_LEVEL_VERBOSE);
Logger(await this.localDatabase.info(), LOG_LEVEL_VERBOSE);
this.localDatabase.on("close", (() => {
var _;
Logger("Database closed.");
this.isReady = false;
this.localDatabase.removeAllListeners();
null == (_ = this.env.getReplicator()) || _.closeReplication();
}));
const ne = this.localDatabase.changes({
since: "now",
live: true,
filter: _ => "leaf" == _.type
}).on("change", (_ => {
if (!_.deleted) sendValue(`leaf-${_.id}`, _.doc);
}));
this.changeHandler = ne;
this.isReady = true;
Logger("Database is now ready.");
return true;
}
async prepareHashFunctions() {
if (null == this.h32) if ("sha1" != this.settings.hashAlg) try {
const {h32ToString: _, h32Raw: ee, h32: ne, h64: ie} = await e2();
this.xxhash64 = ie;
this.xxhash32 = ne;
this.h32 = _;
this.h32Raw = ee;
Logger("Newer xxhash has been initialised", LOG_LEVEL_VERBOSE);
} catch (_) {
Logger("Could not initialise xxhash: use v1", LOG_LEVEL_VERBOSE);
Logger(_);
try {
this.xxhash64 = false;
const {h32: _, h32Raw: ee} = await xxhash_wasm_default();
this.h32 = _;
this.h32Raw = ee;
this.xxhash32 = _ => ee(writeString(_));
} catch (_) {
Logger("Could not initialise xxhash: use sha1F", LOG_LEVEL_VERBOSE);
Logger(_);
this.settings.hashAlg = "sha1";
}
} else Logger("Fallback(SHA1) is used for hashing", LOG_LEVEL_VERBOSE);
}
async readChunk(_, ee) {
const ne = this.hashCaches.get(_);
if (ne) return ne;
let ie;
try {
ie = await this.localDatabase.get(_);
} catch (_) {
if (!isErrorOfMissingDoc(_)) throw _;
}
if (void 0 === ie && 0 != ee) {
const ne = await waitForValue(`leaf-${_}`, ee);
if (ne === RESULT_TIMED_OUT) throw new Error(`Timed out: ${_}`);
ie = ne;
}
if (void 0 === ie) throw new Error(`Missing chunks of: ${_}`);
if ("leaf" != ie.type) throw new Error(`Corrupted chunk has been detected: ${_}`);
this.hashCaches.set(_, ie.data);
return ie.data;
}
async getDBLeafWithTimeout(_, ee) {
try {
return await this.readChunk(_, ee);
} catch (_) {
Logger("Something went wrong while retrieving chunks");
Logger(_, LOG_LEVEL_VERBOSE);
throw _;
}
}
getDBLeaf(_, ee) {
return this.getDBLeafWithTimeout(_, ee ? LEAF_WAIT_TIMEOUT : 0);
}
async getDBEntryMeta(_, ee, ne = false) {
return getDBEntryMeta(this, _, ee, ne);
}
async getDBEntry(_, ee, ne = false, ie = true, re = false) {
return getDBEntry(this, _, ee, ne, ie, re);
}
async getDBEntryFromMeta(_, ee, ne = false, ie = true, re = false) {
return getDBEntryFromMeta(this, _, ee, ne, ie, re);
}
async deleteDBEntry(_, ee) {
return deleteDBEntry(this, _, ee);
}
async deleteDBEntryPrefix(_) {
return deleteDBEntryPrefix(this, _);
}
async putDBEntry(_) {
return putDBEntry(this, _);
}
async resetDatabase() {
var _, ee;
null == (_ = this.changeHandler) || _.cancel();
null == (ee = this.changeHandler) || ee.removeAllListeners();
this.env.getReplicator().closeReplication();
await this.env.onResetDatabase(this);
Logger("Database closed for reset Database.");
this.isReady = false;
await this.localDatabase.destroy();
this.localDatabase = null;
await this.initializeDatabase();
Logger("Local Database Reset", LOG_LEVEL_NOTICE);
}
isTargetFile(_) {
const ee = _.startsWith("i:") ? _.substring(2) : _;
if (ee.startsWith("ix:")) return true;
if (ee.startsWith("ps:")) return true;
if (ee.includes(":")) return false;
if (this.settings.syncOnlyRegEx) {
const _ = new RegExp(this.settings.syncOnlyRegEx);
if (!ee.match(_)) return false;
}
if (this.settings.syncIgnoreRegEx) {
const _ = new RegExp(this.settings.syncIgnoreRegEx);
if (ee.match(_)) return false;
}
return true;
}
async collectChunks(_, ee = false, ne) {
const ie = await this.collectChunksWithCache(_);
if (0 == ie.filter((_ => !_.chunk)).map((_ => _.id)).length) return ie.map((_ => _.chunk));
this._chunkCollectProcessor.batchSize = this.settings.concurrencyOfReadChunksOnline;
this._chunkCollectProcessor.interval = this.settings.minimumIntervalOfReadChunksOnline;
this._chunkCollectProcessor.enqueueAll(_);
const re = _.map((_ => waitForValue(`chunk-fetch-${_}`)));
return (await Promise.all(re)).filter(onlyNot(RESULT_TIMED_OUT));
}
async _collectChunks(_, ee = false) {
const ne = await this.collectChunksWithCache(_), ie = ne.filter((_ => !_.chunk)).map((_ => _.id));
if (0 == ie.length) return ne.map((_ => _.chunk));
const re = await this.env.getReplicator().fetchRemoteChunks(ie, ee);
if (false == re) {
Logger("Could not fetch chunks from the server. ", ee ? LOG_LEVEL_NOTICE : LOG_LEVEL_VERBOSE, "fetch");
return false;
}
re.forEach((_ => this.hashCaches.set(_._id, _.data)));
await this.localDatabase.bulkDocs(re, {
new_edits: false
});
const se = Object.fromEntries([ ...ne.map((_ => _.chunk)).filter((_ => false !== _)), ...re ].map((_ => [ _._id, _ ]))), oe = _.map((_ => {
var ee;
return null != (ee = null == se ? void 0 : se[_]) ? ee : void 0;
}));
if (oe.some((_ => void 0 === _))) return false; else return oe;
}
async* findAllChunks(_) {
const ee = [ () => this.findEntries("h:", "h:", null != _ ? _ : {}) ];
for (const _ of ee) {
const ee = _();
for await (const _ of ee) yield _;
}
}
async* findEntries(_, ee, ne) {
let ie = _, re = this.allDocsRaw({
limit: 100,
startkey: ie,
endkey: ee,
include_docs: true,
...ne
});
do {
const _ = await re;
if (0 === _.rows.length) break;
ie = `${_.rows[_.rows.length - 1].id}`;
re = this.allDocsRaw({
limit: 100,
skip: 1,
startkey: ie,
endkey: ee,
include_docs: true,
...ne
});
for (const ee of _.rows) {
const _ = ee.doc;
if ("type" in _) if ("newnote" == _.type || "plain" == _.type) yield _;
}
} while ("" != ie);
}
async* findAllDocs(_) {
const ee = [ () => this.findEntries("", "_", null != _ ? _ : {}), () => this.findEntries("_", "h:", null != _ ? _ : {}), () => this.findEntries("h:", "", null != _ ? _ : {}) ];
for (const _ of ee) {
const ee = _();
for await (const _ of ee) yield _;
}
}
async* findEntryNames(_, ee, ne) {
let ie = _, re = this.allDocsRaw({
limit: 100,
startkey: ie,
endkey: ee,
...ne
});
do {
const _ = await re;
if (0 == _.rows.length) {
ie = "";
break;
}
ie = `${_.rows[_.rows.length - 1].key}`;
re = this.allDocsRaw({
limit: 100,
skip: 1,
startkey: ie,
endkey: ee,
...ne
});
for (const ee of _.rows) yield ee.id;
} while ("" != ie);
}
async* findAllDocNames(_) {
const ee = [ () => this.findEntryNames("", "_", null != _ ? _ : {}), () => this.findEntryNames("_", "h:", null != _ ? _ : {}), () => this.findEntryNames("h:", "i:", null != _ ? _ : {}), () => this.findEntryNames("i:", "ix:", null != _ ? _ : {}), () => this.findEntryNames("ix:", "ps:", null != _ ? _ : {}), () => this.findEntryNames("ps:", "", null != _ ? _ : {}) ];
for (const _ of ee) {
const ee = _();
for await (const _ of ee) if (!_.startsWith("_")) if (_ != VERSIONINFO_DOCID) yield _;
}
}
async* findAllNormalDocs(_) {
const ee = [ () => this.findEntries("", "_", null != _ ? _ : {}), () => this.findEntries("_", "h:", null != _ ? _ : {}), () => this.findEntries("h:", "i:", null != _ ? _ : {}), () => this.findEntries("i:", "ix:", null != _ ? _ : {}), () => this.findEntries("ix:", "ps:", null != _ ? _ : {}), () => this.findEntries("ps:", "", null != _ ? _ : {}) ];
for (const _ of ee) {
const ee = _();
for await (const _ of ee) if (!_._id.startsWith("_")) if ("newnote" == _.type || "plain" == _.type) yield _;
}
}
async removeRevision(_, ee) {
try {
const ne = await this.localDatabase.get(_, {
rev: ee
});
ne._deleted = true;
await this.localDatabase.put(ne);
return true;
} catch (ne) {
if (isErrorOfMissingDoc(ne)) Logger(`Remove revision: Missing target revision, ${_}-${ee}`, LOG_LEVEL_VERBOSE);
}
return false;
}
getRaw(_, ee) {
return this.localDatabase.get(_, ee || {});
}
removeRaw(_, ee, ne) {
return this.localDatabase.remove(_, ee, ne || {});
}
putRaw(_, ee) {
return this.localDatabase.put(_, ee || {});
}
allDocsRaw(_) {
return this.localDatabase.allDocs(_);
}
bulkDocsRaw(_, ee) {
return this.localDatabase.bulkDocs(_, ee || {});
}
async collectChunksWithCache(_) {
const ee = _.map((_ => this.hashCaches.has(_) ? {
id: _,
chunk: this.hashCaches.get(_)
} : {
id: _,
chunk: false
})), ne = ee.filter((_ => false === _.chunk));
if (ne.length > 0) {
const _ = await this.localDatabase.allDocs({
keys: ne.map((_ => _.id)),
include_docs: true
}), ie = _.rows.filter((_ => !("error" in _))).map((_ => _.doc)), re = _.rows.filter((_ => "error" in _)).map((_ => _.key)), se = (await this.localDatabase.allDocs({
keys: re.map((_ => `_local/${_}`)),
include_docs: true
})).rows.filter((_ => !("error" in _))).map((_ => ({
..._.doc,
_id: _.id.substring(7)
}))), oe = Object.fromEntries(se.map((_ => [ _._id, _.data ])));
for (const _ of ie) {
oe[_._id] = _.data;
this.hashCaches.set(_._id, _.data);
}
return ee.map((_ => ({
id: _.id,
chunk: false !== _.chunk ? _.chunk : _.id in oe ? oe[_.id] : false
}))).map((_ => ({
id: _.id,
chunk: false !== _.chunk ? {
_id: _.id,
data: _.chunk,
type: "leaf"
} : false
})));
} else return ee.map((_ => ({
id: _.id,
chunk: {
_id: _.id,
data: _.chunk,
type: "leaf"
}
})));
}
}, instanceOfAny = (_, ee) => ee.some((ee => _ instanceof ee));
function getIdbProxyableTypes() {
return idbProxyableTypes || (idbProxyableTypes = [ IDBDatabase, IDBObjectStore, IDBIndex, IDBCursor, IDBTransaction ]);
}
function getCursorAdvanceMethods() {
return cursorAdvanceMethods || (cursorAdvanceMethods = [ IDBCursor.prototype.advance, IDBCursor.prototype.continue, IDBCursor.prototype.continuePrimaryKey ]);
}
var transactionDoneMap = new WeakMap, transformCache = new WeakMap, reverseTransformCache = new WeakMap;
function promisifyRequest(_) {
const ee = new Promise(((ee, ne) => {
const unlisten = () => {
_.removeEventListener("success", success);
_.removeEventListener("error", error);
}, success = () => {
ee(wrap(_.result));
unlisten();
}, error = () => {
ne(_.error);
unlisten();
};
_.addEventListener("success", success);
_.addEventListener("error", error);
}));
reverseTransformCache.set(ee, _);
return ee;
}
function cacheDonePromiseForTransaction(_) {
if (transactionDoneMap.has(_)) return;
const ee = new Promise(((ee, ne) => {
const unlisten = () => {
_.removeEventListener("complete", complete);
_.removeEventListener("error", error);
_.removeEventListener("abort", error);
}, complete = () => {
ee();
unlisten();
}, error = () => {
ne(_.error || new DOMException("AbortError", "AbortError"));
unlisten();
};
_.addEventListener("complete", complete);
_.addEventListener("error", error);
_.addEventListener("abort", error);
}));
transactionDoneMap.set(_, ee);
}
var idbProxyTraps = {
get(_, ee, ne) {
if (_ instanceof IDBTransaction) {
if ("done" === ee) return transactionDoneMap.get(_);
if ("store" === ee) return ne.objectStoreNames[1] ? void 0 : ne.objectStore(ne.objectStoreNames[0]);
}
return wrap(_[ee]);
},
set(_, ee, ne) {
_[ee] = ne;
return true;
},
has(_, ee) {
if (_ instanceof IDBTransaction && ("done" === ee || "store" === ee)) return true; else return ee in _;
}
};
function replaceTraps(_) {
idbProxyTraps = _(idbProxyTraps);
}
function wrapFunction(_) {
if (getCursorAdvanceMethods().includes(_)) return function(...ee) {
_.apply(unwrap(this), ee);
return wrap(this.request);
}; else return function(...ee) {
return wrap(_.apply(unwrap(this), ee));
};
}
function transformCachableValue(_) {
if ("function" == typeof _) return wrapFunction(_);
if (_ instanceof IDBTransaction) cacheDonePromiseForTransaction(_);
if (instanceOfAny(_, getIdbProxyableTypes())) return new Proxy(_, idbProxyTraps); else return _;
}
function wrap(_) {
if (_ instanceof IDBRequest) return promisifyRequest(_);
if (transformCache.has(_)) return transformCache.get(_);
const ee = transformCachableValue(_);
if (ee !== _) {
transformCache.set(_, ee);
reverseTransformCache.set(ee, _);
}
return ee;
}
var unwrap = _ => reverseTransformCache.get(_);
function openDB(_, ee, {blocked: ne, upgrade: ie, blocking: re, terminated: se} = {}) {
const oe = indexedDB.open(_, ee), le = wrap(oe);
if (ie) oe.addEventListener("upgradeneeded", (_ => {
ie(wrap(oe.result), _.oldVersion, _.newVersion, wrap(oe.transaction), _);
}));
if (ne) oe.addEventListener("blocked", (_ => ne(_.oldVersion, _.newVersion, _)));
le.then((_ => {
if (se) _.addEventListener("close", (() => se()));
if (re) _.addEventListener("versionchange", (_ => re(_.oldVersion, _.newVersion, _)));
})).catch((() => {}));
return le;
}
function deleteDB(_, {blocked: ee} = {}) {
const ne = indexedDB.deleteDatabase(_);
if (ee) ne.addEventListener("blocked", (_ => ee(_.oldVersion, _)));
return wrap(ne).then((() => {}));
}
var readMethods = [ "get", "getKey", "getAll", "getAllKeys", "count" ], writeMethods = [ "put", "add", "delete", "clear" ], cachedMethods = new Map;
function getMethod(_, ee) {
if (!(_ instanceof IDBDatabase && !(ee in _) && "string" == typeof ee)) return;
if (cachedMethods.get(ee)) return cachedMethods.get(ee);
const ne = ee.replace(/FromIndex$/, ""), ie = ee !== ne, re = writeMethods.includes(ne);
if (!(ne in (ie ? IDBIndex : IDBObjectStore).prototype) || !(re || readMethods.includes(ne))) return;
const method = async function(_, ...ee) {
const se = this.transaction(_, re ? "readwrite" : "readonly");
let oe = se.store;
if (ie) oe = oe.index(ee.shift());
return (await Promise.all([ oe[ne](...ee), re && se.done ]))[0];
};
cachedMethods.set(ee, method);
return method;
}
replaceTraps((_ => ({
..._,
get: (ee, ne, ie) => getMethod(ee, ne) || _.get(ee, ne, ie),
has: (ee, ne) => !!getMethod(ee, ne) || _.has(ee, ne)
})));
var advanceMethodProps = [ "continue", "continuePrimaryKey", "advance" ], methodMap = {}, advanceResults = new WeakMap, ittrProxiedCursorToOriginalProxy = new WeakMap, cursorIteratorTraps = {
get(_, ee) {
if (!advanceMethodProps.includes(ee)) return _[ee];
let ne = methodMap[ee];
if (!ne) ne = methodMap[ee] = function(..._) {
advanceResults.set(this, ittrProxiedCursorToOriginalProxy.get(this)[ee](..._));
};
return ne;
}
};
async function* iterate(..._) {
let ee = this;
if (!(ee instanceof IDBCursor)) ee = await ee.openCursor(..._);
if (!ee) return;
const ne = new Proxy(ee, cursorIteratorTraps);
ittrProxiedCursorToOriginalProxy.set(ne, ee);
reverseTransformCache.set(ne, unwrap(ee));
for (;ee; ) {
yield ne;
ee = await (advanceResults.get(ne) || ee.continue());
advanceResults.delete(ne);
}
}
function isIteratorProp(_, ee) {
return ee === Symbol.asyncIterator && instanceOfAny(_, [ IDBIndex, IDBObjectStore, IDBCursor ]) || "iterate" === ee && instanceOfAny(_, [ IDBIndex, IDBObjectStore ]);
}
replaceTraps((_ => ({
..._,
get(ee, ne, ie) {
if (isIteratorProp(ee, ne)) return iterate; else return _.get(ee, ne, ie);
},
has: (ee, ne) => isIteratorProp(ee, ne) || _.has(ee, ne)
})));
var databaseCache = {}, OpenKeyValueDatabase = async _ => {
if (_ in databaseCache) {
databaseCache[_].close();
delete databaseCache[_];
}
const ee = _, ne = openDB(_, 1, {
upgrade(_) {
_.createObjectStore(ee);
}
}), ie = await ne;
databaseCache[_] = ie;
return {
get: async _ => await ie.get(ee, _),
set: async (_, ne) => await ie.put(ee, ne, _),
del: async _ => await ie.delete(ee, _),
clear: async () => await ie.clear(ee),
keys: async (_, ne) => await ie.getAllKeys(ee, _, ne),
close() {
delete databaseCache[_];
return ie.close();
},
async destroy() {
delete databaseCache[_];
ie.close();
await deleteDB(_);
}
};
}, HiddenFileSync = class extends LiveSyncCommands {
constructor() {
super(...arguments);
this.periodicInternalFileScanProcessor = new PeriodicProcessor(this.plugin, (async () => this.settings.syncInternalFiles && this.localDatabase.isReady && await this.syncInternalFilesAndDatabase("push", false)));
this.internalFileProcessor = new QueueProcessor((async _ => {
Logger(`START :Applying hidden ${_.length} files change`, LOG_LEVEL_VERBOSE);
await this.syncInternalFilesAndDatabase("pull", false, false, _);
Logger(`DONE :Applying hidden ${_.length} files change`, LOG_LEVEL_VERBOSE);
}), {
batchSize: 100,
concurrentLimit: 1,
delay: 10,
yieldThreshold: 100,
suspended: false,
totalRemainingReactiveSource: hiddenFilesEventCount
});
this.recentProcessedInternalFiles = [];
this.conflictResolutionProcessor = new QueueProcessor((async _ => {
var ee, ne, ie;
const re = _[0];
sendSignal(`cancel-internal-conflict:${re}`);
try {
const _ = await this.path2id(re, ICHeader), se = await this.localDatabase.getRaw(_, {
conflicts: true
});
if (void 0 === se._conflicts) return [];
if (0 == se._conflicts.length) return [];
Logger(`Hidden file conflicted:${re}`);
const oe = se._conflicts.sort(((_, ee) => Number(_.split("-")[0]) - Number(ee.split("-")[0]))), le = se._rev, ue = oe[0];
if (re.endsWith(".json")) {
const de = oe[0], fe = Number(de.split("-")[0]), he = null != (ie = null == (ne = null == (ee = (await this.localDatabase.getRaw(_, {
revs_info: true
}))._revs_info) ? void 0 : ee.filter((_ => "available" == _.status && Number(_.rev.split("-")[0]) < fe)).first()) ? void 0 : ne.rev) ? ie : "", pe = await this.plugin.mergeObject(re, he, se._rev, de);
if (pe) {
Logger(`Object merge:${re}`, LOG_LEVEL_INFO);
const ee = stripAllPrefixes(re);
if (!await this.plugin.vaultAccess.adapterExists(ee)) await this.vaultAccess.ensureDirectory(ee);
await this.plugin.vaultAccess.adapterWrite(ee, pe);
const ne = await this.vaultAccess.adapterStat(ee);
if (!ne) throw new Error(`conflictResolutionProcessor: Failed to stat file ${ee}`);
await this.storeInternalFileToDatabase({
path: ee,
...ne
});
await this.extractInternalFileFromDatabase(ee);
await this.localDatabase.removeRevision(_, ue);
this.conflictResolutionProcessor.enqueue(re);
return [];
} else Logger("Object merge is not applicable.", LOG_LEVEL_VERBOSE);
return [ {
path: re,
revA: le,
revB: ue,
id: _,
doc: se
} ];
}
await this.resolveByNewerEntry(_, re, se, le, ue);
return [];
} catch (_) {
Logger(`Failed to resolve conflict (Hidden): ${re}`);
Logger(_, LOG_LEVEL_VERBOSE);
return [];
}
}), {
suspended: false,
batchSize: 1,
concurrentLimit: 5,
delay: 10,
keepResultUntilDownstreamConnected: true,
yieldThreshold: 10,
pipeTo: new QueueProcessor((async _ => {
const {id: ee, doc: ne, path: ie, revA: re, revB: se} = _[0], oe = await this.localDatabase.getDBEntry(ie, {
rev: re
}), le = await this.localDatabase.getDBEntry(ie, {
rev: se
});
if (false == oe || false == le) await this.resolveByNewerEntry(ee, ie, ne, re, se); else if (await this.showJSONMergeDialogAndMerge(oe, le)) this.conflictResolutionProcessor.enqueue(ie);
}), {
suspended: false,
batchSize: 1,
concurrentLimit: 1,
delay: 10,
keepResultUntilDownstreamConnected: false,
yieldThreshold: 10
})
});
}
get kvDB() {
return this.plugin.kvDB;
}
getConflictedDoc(_, ee) {
return this.plugin.getConflictedDoc(_, ee);
}
onunload() {
var _;
null == (_ = this.periodicInternalFileScanProcessor) || _.disable();
}
onload() {
this.plugin.addCommand({
id: "livesync-scaninternal",
name: "Sync hidden files",
callback: () => {
this.syncInternalFilesAndDatabase("safe", true);
}
});
}
async onInitializeDatabase(_) {
if (this.settings.syncInternalFiles) try {
Logger("Synchronizing hidden files...");
await this.syncInternalFilesAndDatabase("push", _);
Logger("Synchronizing hidden files done");
} catch (_) {
Logger("Synchronizing hidden files failed");
Logger(_, LOG_LEVEL_VERBOSE);
}
}
async beforeReplicate(_) {
if (this.localDatabase.isReady && this.settings.syncInternalFiles && this.settings.syncInternalFilesBeforeReplication && !this.settings.watchInternalFileChanges) await this.syncInternalFilesAndDatabase("push", _);
}
async onResume() {
var _;
null == (_ = this.periodicInternalFileScanProcessor) || _.disable();
if (!this.plugin.suspended) {
if (this.settings.syncInternalFiles) await this.syncInternalFilesAndDatabase("safe", false);
this.periodicInternalFileScanProcessor.enable(this.settings.syncInternalFiles && this.settings.syncInternalFilesInterval ? 1e3 * this.settings.syncInternalFilesInterval : 0);
}
}
parseReplicationResultItem(_) {
return false;
}
realizeSettingSyncMode() {
var _;
null == (_ = this.periodicInternalFileScanProcessor) || _.disable();
if (this.plugin.suspended) return Promise.resolve();
if (!this.plugin.isReady) return Promise.resolve();
this.periodicInternalFileScanProcessor.enable(this.settings.syncInternalFiles && this.settings.syncInternalFilesInterval ? 1e3 * this.settings.syncInternalFilesInterval : 0);
return Promise.resolve();
}
procInternalFile(_) {
this.internalFileProcessor.enqueue(_);
}
async watchVaultRawEventsAsync(_) {
var ee, ne, ie;
if (!this.settings.syncInternalFiles) return;
const re = normalizePath(this.app.vault.configDir);
if ((!this.settings.usePluginSync ? [] : Object.values(this.settings.pluginSyncExtendedSetting).filter((_ => _.mode == MODE_SELECTIVE || _.mode == MODE_PAUSED)).map((_ => _.files)).flat().map((_ => `${re}/${_}`.toLowerCase()))).some((ee => ee.startsWith(_.toLowerCase())))) {
Logger(`Hidden file skipped: ${_} is synchronized in customization sync.`, LOG_LEVEL_VERBOSE);
return;
}
const se = await this.vaultAccess.adapterStat(_);
if (null != se && "file" != se.type) return;
const oe = null == se ? 0 : null != (ee = null == se ? void 0 : se.mtime) ? ee : 0, le = ~~(oe / 1e3), ue = `${_}-${le}`;
if (0 != oe && this.recentProcessedInternalFiles.contains(ue)) return;
this.recentProcessedInternalFiles = [ ue, ...this.recentProcessedInternalFiles ].slice(0, 100);
const de = addPrefix(_, ICHeader), fe = await this.localDatabase.getDBEntryMeta(de);
if (~~((fe && fe.mtime || 0) / 1e3) != le) if (0 == le) await this.deleteInternalFileOnDatabase(_); else await this.storeInternalFileToDatabase({
path: _,
mtime: oe,
ctime: null != (ne = null == se ? void 0 : se.ctime) ? ne : oe,
size: null != (ie = null == se ? void 0 : se.size) ? ie : 0
});
}
async resolveConflictOnInternalFiles() {
const _ = this.localDatabase.findEntries(ICHeader, ICHeaderEnd, {
conflicts: true
});
this.conflictResolutionProcessor.suspend();
try {
for await (const ee of _) if ("_conflicts" in ee) if (isInternalMetadata(ee._id)) this.conflictResolutionProcessor.enqueue(ee.path);
} catch (_) {
Logger("something went wrong on resolving all conflicted internal files");
Logger(_, LOG_LEVEL_VERBOSE);
}
await this.conflictResolutionProcessor.startPipeline().waitForAllProcessed();
}
async resolveByNewerEntry(_, ee, ne, ie, re) {
var se;
const oe = await this.localDatabase.getRaw(_, {
rev: re
}), le = ("mtime" in ne && ne.mtime || 0) < ("mtime" in oe && oe.mtime || 0) ? ie : re;
await this.localDatabase.removeRevision(_, le);
Logger(`Older one has been deleted:${ee}`);
if (0 === (null == (se = (await this.localDatabase.getRaw(_, {
conflicts: true
}))._conflicts) ? void 0 : se.length)) await this.extractInternalFileFromDatabase(stripAllPrefixes(ee)); else this.conflictResolutionProcessor.enqueue(ee);
}
queueConflictCheck(_) {
this.conflictResolutionProcessor.enqueue(_);
}
async syncInternalFilesAndDatabase(_, ee, ne = false, ie = false) {
await this.resolveConflictOnInternalFiles();
const re = ee ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO;
Logger("Scanning hidden files.", re, "sync_internal");
const se = this.settings.syncInternalFilesIgnorePatterns.replace(/\n| /g, "").split(",").filter((_ => _)).map((_ => new RegExp(_, "i"))), oe = normalizePath(this.app.vault.configDir);
let le = ne ? ne : await this.scanInternalFiles();
const ue = !this.settings.usePluginSync ? [] : Object.values(this.settings.pluginSyncExtendedSetting).filter((_ => _.mode == MODE_SELECTIVE || _.mode == MODE_PAUSED)).map((_ => _.files)).flat().map((_ => `${oe}/${_}`.toLowerCase()));
le = le.filter((_ => ue.every((ee => !_.path.toLowerCase().startsWith(ee)))));
const de = (await this.localDatabase.allDocsRaw({
startkey: ICHeader,
endkey: ICHeaderEnd,
include_docs: true
})).rows.map((_ => _.doc)).filter((_ => !_.deleted)), fe = [ ...new Set([ ...le.map((_ => normalizePath(_.path))), ...de.map((_ => stripAllPrefixes(this.getPath(_)))) ]) ].filter((_ => !ie || ie && -1 !== ie.indexOf(_))).filter((_ => ue.every((ee => !_.toLowerCase().startsWith(ee))))), he = fe.length;
let pe = 0, ge = 0;
const me = {}, countUpdatedFolder = _ => {
const ee = _.split("/");
let ne = ee.shift(), ie = "";
ge++;
for (;ne; ) {
ie += ("" != ie ? "/" : "") + ne;
ie = normalizePath(ie);
if (!(ie in me)) me[ie] = 0;
me[ie]++;
ne = ee.shift();
}
};
let ye = {};
ye = await this.kvDB.get("diff-caches-internal") || {};
const ve = le.reduce(((_, ee) => {
_[ee.path] = ee;
return _;
}), {}), Se = de.reduce(((_, ee) => {
_[stripAllPrefixes(this.getPath(ee))] = ee;
return _;
}), {});
await new QueueProcessor((async _ => {
const ee = _[0];
pe++;
if (pe % 100 == 0) Logger(`Hidden file: ${pe}/${he}`, re, "sync_internal");
if (!ee) return [];
if (se.some((_ => ee.match(_)))) return [];
if (await this.plugin.isIgnoredByIgnoreFiles(ee)) return [];
const ne = ee in ve ? ve[ee] : void 0, ie = ee in Se ? Se[ee] : void 0;
return [ {
filename: ee,
fileOnStorage: ne,
fileOnDatabase: ie
} ];
}), {
suspended: true,
batchSize: 1,
concurrentLimit: 10,
delay: 0,
totalRemainingReactiveSource: hiddenFilesProcessingCount
}).pipeTo(new QueueProcessor((async ee => {
const {filename: ne, fileOnStorage: ie, fileOnDatabase: re} = ee[0];
if (ie && re) {
const ee = ne in ye ? ye[ne] : {
storageMtime: 0,
docMtime: 0
};
if ("pullForce" != _ && "pushForce" != _ && re.mtime == ee.docMtime && ie.mtime == ee.storageMtime) return;
const se = function compareMTime2(_, ee) {
return ~~(_ / 1e3) - ~~(ee / 1e3);
}(ie.mtime, re.mtime);
if (se > 0 || "pushForce" == _) await this.storeInternalFileToDatabase(ie);
if (se < 0 || "pullForce" == _) if (!await this.extractInternalFileFromDatabase(ne)) return;
ee.docMtime = re.mtime;
ee.storageMtime = ie.mtime;
ye[ne] = ee;
countUpdatedFolder(ne);
} else if (!ie && re) {
if ("push" == _ || "pushForce" == _) {
if (re.deleted) return;
await this.deleteInternalFileOnDatabase(ne, false);
} else if ("pull" == _ || "pullForce" == _) {
if (await this.extractInternalFileFromDatabase(ne)) countUpdatedFolder(ne);
} else if ("safe" == _) {
if (re.deleted) return;
if (await this.extractInternalFileFromDatabase(ne)) countUpdatedFolder(ne);
}
} else if (ie && !re) if ("push" == _ || "pushForce" == _ || "safe" == _) await this.storeInternalFileToDatabase(ie); else await this.extractInternalFileFromDatabase(ie.path); else throw new Error("Invalid state on hidden file sync");
}), {
suspended: true,
batchSize: 1,
concurrentLimit: 5,
delay: 0
})).root.enqueueAll(fe).startPipeline().waitForAllDoneAndTerminate();
await this.kvDB.set("diff-caches-internal", ye);
if (("pull" == _ || "pullForce" == _) && 0 != ge) if (oe in me) {
let _ = me[oe];
try {
const ee = Object.values(this.app.plugins.manifests), ne = this.app.plugins.enabledPlugins, ie = ee.filter((_ => ne.has(_.id)));
for (const ee of ie) if (ee.dir && ee.dir in me) {
_ -= me[ee.dir];
const ne = ee.id, ie = ee.name;
this.plugin.askInPopup(`updated-${ne}`, `Files in ${ie} has been updated, Press {HERE} to reload ${ie}, or press elsewhere to dismiss this message.`, (_ => {
_.text = "HERE";
_.addEventListener("click", (async () => {
Logger(`Unloading plugin: ${ie}`, LOG_LEVEL_NOTICE, "plugin-reload-" + ne);
await this.app.plugins.unloadPlugin(ne);
await this.app.plugins.loadPlugin(ne);
Logger(`Plugin reloaded: ${ie}`, LOG_LEVEL_NOTICE, "plugin-reload-" + ne);
}));
}));
}
} catch (_) {
Logger("Error on checking plugin status.");
Logger(_, LOG_LEVEL_VERBOSE);
}
if (0 != _) if (!this.plugin.isReloadingScheduled) this.plugin.askInPopup("updated-any-hidden", "Hidden files have been synchronised, Press {HERE} to schedule a reload of Obsidian, or press elsewhere to dismiss this message.", (_ => {
_.text = "HERE";
_.addEventListener("click", (() => {
this.plugin.scheduleAppReload();
}));
}));
}
Logger(`Hidden files scanned: ${ge} files had been modified`, re, "sync_internal");
}
async storeInternalFileToDatabase(_, ee = false) {
if (await this.plugin.isIgnoredByIgnoreFiles(_.path)) return;
const ne = await this.path2id(_.path, ICHeader), ie = addPrefix(_.path, ICHeader), re = createBlob(await this.plugin.vaultAccess.adapterReadAuto(_.path)), se = _.mtime;
return await serialized("file-" + ie, (async () => {
try {
const oe = await this.localDatabase.getDBEntry(ie, void 0, false, false);
let le;
if (false === oe) le = {
_id: ne,
path: ie,
data: re,
mtime: se,
ctime: se,
datatype: "newnote",
size: _.size,
children: [],
deleted: false,
type: "newnote",
eden: {}
}; else {
if (await isDocContentSame(readAsBlob(oe), re) && !ee) return;
le = {
...oe,
data: re,
mtime: se,
size: _.size,
datatype: oe.datatype,
children: [],
deleted: false,
type: oe.datatype
};
}
const ue = await this.localDatabase.putDBEntry(le);
Logger(`STORAGE --\x3e DB:${_.path}: (hidden) Done`);
return ue;
} catch (ee) {
Logger(`STORAGE --\x3e DB:${_.path}: (hidden) Failed`);
Logger(ee, LOG_LEVEL_VERBOSE);
return false;
}
}));
}
async deleteInternalFileOnDatabase(_, ee = false) {
const ne = await this.path2id(_, ICHeader), ie = addPrefix(_, ICHeader), re = (new Date).getTime();
if (!await this.plugin.isIgnoredByIgnoreFiles(_)) await serialized("file-" + ie, (async () => {
try {
const ee = await this.localDatabase.getDBEntryMeta(ie, void 0, true);
let se;
if (false === ee) se = {
_id: ne,
path: ie,
mtime: re,
ctime: re,
size: 0,
children: [],
deleted: true,
type: "newnote",
eden: {}
}; else {
const ne = await this.localDatabase.getRaw(ee._id, {
conflicts: true
});
if (void 0 !== ne._conflicts) for (const ie of ne._conflicts) {
await this.localDatabase.removeRevision(ee._id, ie);
Logger(`STORAGE -x> DB:${_}: (hidden) conflict removed ${ee._rev} => ${ie}`, LOG_LEVEL_VERBOSE);
}
if (ee.deleted) {
Logger(`STORAGE -x> DB:${_}: (hidden) already deleted`);
return;
}
se = {
...ee,
mtime: re,
size: 0,
children: [],
deleted: true,
type: "newnote"
};
}
await this.localDatabase.putRaw(se);
Logger(`STORAGE -x> DB:${_}: (hidden) Done`);
} catch (ee) {
Logger(`STORAGE -x> DB:${_}: (hidden) Failed`);
Logger(ee, LOG_LEVEL_VERBOSE);
return false;
}
}));
}
async extractInternalFileFromDatabase(_, ee = false) {
const ne = await this.plugin.vaultAccess.adapterExists(_), ie = addPrefix(_, ICHeader);
if (!await this.plugin.isIgnoredByIgnoreFiles(_)) return await serialized("file-" + ie, (async () => {
var re;
try {
const se = await this.localDatabase.getDBEntry(ie, {
conflicts: true
}, false, true, true);
if (false === se) throw new Error(`File not found on database.:${_}`);
if (null == (re = null == se ? void 0 : se._conflicts) ? void 0 : re.length) {
Logger(`Hidden file ${_} has conflicted revisions, to keep in safe, writing to storage has been prevented`, LOG_LEVEL_INFO);
return;
}
if (se.deleted || se._deleted || false) {
if (!ne) Logger(`STORAGE {
Logger("Opening data-merging dialog", LOG_LEVEL_VERBOSE);
const ie = [ _, ee ], re = stripAllPrefixes(_.path);
new JsonResolveModal(this.app, re, [ _, ee ], (async (_, ee) => {
var se, oe, le;
try {
const ue = re;
let de = false;
if (!ee && !_) {
Logger(`Skipped merging: ${ue}`);
ne(false);
return;
}
if (ee || _) for (const ee of ie) if (ee._rev != _) if (await this.localDatabase.deleteDBEntry(this.getPath(ee), {
rev: ee._rev
})) {
Logger(`Conflicted revision has been deleted: ${ue}`);
de = true;
}
if (!_ && ee) {
if (!await this.plugin.vaultAccess.adapterExists(ue)) await this.vaultAccess.ensureDirectory(ue);
await this.plugin.vaultAccess.adapterWrite(ue, ee);
const _ = await this.plugin.vaultAccess.adapterStat(ue);
if (!_) throw new Error("Stat failed");
const ne = null != (se = null == _ ? void 0 : _.mtime) ? se : 0;
await this.storeInternalFileToDatabase({
path: ue,
mtime: ne,
ctime: null != (oe = null == _ ? void 0 : _.ctime) ? oe : ne,
size: null != (le = null == _ ? void 0 : _.size) ? le : 0
}, true);
try {
await this.app.vault.adapter.reconcileInternalFile(ue);
} catch (_) {
Logger("Failed to call internal API(reconcileInternalFile)", LOG_LEVEL_VERBOSE);
Logger(_, LOG_LEVEL_VERBOSE);
}
Logger(`STORAGE <-- DB:${ue}: written (hidden,merged)`);
}
if (de) {
await this.extractInternalFileFromDatabase(ue, false);
Logger(`STORAGE --\x3e DB:${ue}: extracted (hidden,merged)`);
}
ne(true);
} catch (_) {
Logger("Could not merge conflicted json");
Logger(_, LOG_LEVEL_VERBOSE);
ne(false);
}
})).open();
}));
}
async scanInternalFiles() {
var _, ee, ne, ie, re, se;
const oe = normalizePath(this.app.vault.configDir), le = this.settings.syncInternalFilesIgnorePatterns.replace(/\n| /g, "").split(",").filter((_ => _)).map((_ => new RegExp(_, "i"))), ue = !this.settings.usePluginSync ? [] : Object.values(this.settings.pluginSyncExtendedSetting).filter((_ => _.mode == MODE_SELECTIVE || _.mode == MODE_PAUSED)).map((_ => _.files)).flat().map((_ => `${oe}/${_}`.toLowerCase())), de = this.app.vault.getRoot().path, fe = (await this.getFiles(de, [], void 0, le)).filter((_ => _.startsWith("."))).filter((_ => !_.startsWith(".trash"))).filter((_ => ue.every((ee => !_.toLowerCase().startsWith(ee))))).map((async _ => ({
path: _,
stat: await this.plugin.vaultAccess.adapterStat(_)
}))), he = [];
for (const oe of fe) {
const le = await oe;
if (await this.plugin.isIgnoredByIgnoreFiles(le.path)) continue;
const ue = null != (ee = null == (_ = le.stat) ? void 0 : _.mtime) ? ee : 0, de = null != (ie = null == (ne = le.stat) ? void 0 : ne.ctime) ? ie : ue, fe = null != (se = null == (re = le.stat) ? void 0 : re.size) ? se : 0;
he.push({
...le,
mtime: ue,
ctime: de,
size: fe
});
}
return he;
}
async getFiles(_, ee, ne, ie) {
let re;
try {
re = await this.app.vault.adapter.list(_);
} catch (ee) {
Logger(`Could not traverse(HiddenSync):${_}`, LOG_LEVEL_INFO);
Logger(ee, LOG_LEVEL_VERBOSE);
return [];
}
const se = [ ...re.files.filter((_ => !ee.some((ee => _.endsWith(ee))))).filter((_ => !ne || ne.some((ee => _.match(ee))))).filter((_ => !ie || ie.every((ee => !_.match(ee))))) ];
let oe = [];
for (const _ of se) if (!await this.plugin.isIgnoredByIgnoreFiles(_)) oe.push(_);
e: for (const _ of re.folders) {
for (const ne of ee) if (_.endsWith(ne)) continue e;
if (!ie || !ie.some((ee => _.match(ee)))) if (!await this.plugin.isIgnoredByIgnoreFiles(_)) oe = oe.concat(await this.getFiles(_, ee, ne, ie));
}
return oe;
}
}, SetupLiveSync = class extends LiveSyncCommands {
onunload() {}
onload() {
this.plugin.registerObsidianProtocolHandler("setuplivesync", (async _ => await this.setupWizard(_.settings)));
this.plugin.addCommand({
id: "livesync-copysetupuri",
name: "Copy settings as a new setup URI",
callback: () => fireAndForget(this.command_copySetupURI())
});
this.plugin.addCommand({
id: "livesync-copysetupuri-short",
name: "Copy settings as a new setup URI (With customization sync)",
callback: () => fireAndForget(this.command_copySetupURIWithSync())
});
this.plugin.addCommand({
id: "livesync-copysetupurifull",
name: "Copy settings as a new setup URI (Full)",
callback: () => fireAndForget(this.command_copySetupURIFull())
});
this.plugin.addCommand({
id: "livesync-opensetupuri",
name: "Use the copied setup URI (Formerly Open setup URI)",
callback: () => fireAndForget(this.command_openSetupURI())
});
}
onInitializeDatabase(_) {}
beforeReplicate(_) {}
onResume() {}
parseReplicationResultItem(_) {
return false;
}
async realizeSettingSyncMode() {}
async command_copySetupURI(_ = true) {
const ee = await askString(this.app, "Encrypt your settings", "The passphrase to encrypt the setup URI", "", true);
if (false === ee) return;
const ne = {
...this.settings,
configPassphraseStore: "",
encryptedCouchDBConnection: "",
encryptedPassphrase: ""
};
if (_) delete ne.pluginSyncExtendedSetting;
const ie = Object.keys(ne);
for (const _ of ie) if (JSON.stringify(_ in ne ? ne[_] : "") == JSON.stringify(_ in DEFAULT_SETTINGS ? DEFAULT_SETTINGS[_] : "*")) delete ne[_];
const re = encodeURIComponent(await encrypt(JSON.stringify(ne), ee, false)), se = `${configURIBase}${re}`;
await navigator.clipboard.writeText(se);
Logger("Setup URI copied to clipboard", LOG_LEVEL_NOTICE);
}
async command_copySetupURIFull() {
const _ = await askString(this.app, "Encrypt your settings", "The passphrase to encrypt the setup URI", "", true);
if (false === _) return;
const ee = {
...this.settings,
configPassphraseStore: "",
encryptedCouchDBConnection: "",
encryptedPassphrase: ""
}, ne = encodeURIComponent(await encrypt(JSON.stringify(ee), _, false)), ie = `${configURIBase}${ne}`;
await navigator.clipboard.writeText(ie);
Logger("Setup URI copied to clipboard", LOG_LEVEL_NOTICE);
}
async command_copySetupURIWithSync() {
await this.command_copySetupURI(false);
}
async command_openSetupURI() {
const _ = await askString(this.app, "Easy setup", "Set up URI", `${configURIBase}aaaaa`);
if (false === _) return;
if (!_.startsWith(`${configURIBase}`)) {
Logger("Set up URI looks wrong.", LOG_LEVEL_NOTICE);
return;
}
const ee = decodeURIComponent(_.substring(configURIBase.length));
console.dir(ee);
await this.setupWizard(ee);
}
async setupWizard(_) {
try {
const ee = JSON.parse(JSON.stringify(this.settings)), ne = await askString(this.app, "Passphrase", "The passphrase to decrypt your setup URI", "", true);
if (false === ne) return;
const ie = await JSON.parse(await decrypt(_, ne, false));
if (ie) {
if ("yes" == await askYesNo(this.app, "Importing LiveSync's conf, OK?")) {
const _ = Object.assign({}, DEFAULT_SETTINGS, ie);
this.plugin.replicator.closeReplication();
this.settings.suspendFileWatching = true;
console.dir(_);
_.configPassphraseStore = "";
_.encryptedPassphrase = "";
_.encryptedCouchDBConnection = "";
_.additionalSuffixOfDatabaseName = `${"appId" in this.app ? this.app.appId : ""}`;
const ne = "Just import setting", re = "Set it up as secondary or subsequent device", se = "Secondary device but try keeping local changes", oe = "Reconfigure and reconstitute the data", le = "Leave everything to me";
_.syncInternalFiles = false;
_.usePluginSync = false;
_.isConfigured = true;
if (!_.useIndexedDBAdapter) _.useIndexedDBAdapter = true;
const ue = await askSelectString(this.app, "How would you like to set it up?", [ re, oe, se, ne, le ]);
if (ue == ne) {
this.plugin.settings = _;
this.plugin.usedPassphrase = "";
await this.plugin.saveSettings();
} else if (ue == re) {
this.plugin.settings = _;
this.plugin.usedPassphrase = "";
await this.fetchLocal();
} else if (ue == se) {
this.plugin.settings = _;
this.plugin.usedPassphrase = "";
await this.fetchLocalWithRebuild();
} else if (ue == oe) {
const ee = "I know this operation will rebuild all my databases with files on this device, and files that are on the remote database and I didn't synchronize to any other devices will be lost and want to proceed indeed.";
if (await askSelectString(this.app, "Do you really want to do this?", [ "Cancel", ee ]) != ee) return;
this.plugin.settings = _;
this.plugin.usedPassphrase = "";
await this.rebuildEverything();
} else if (ue == le) {
const ne = await askYesNo(this.app, "Keep local DB?"), ie = await askYesNo(this.app, "Keep remote DB?");
if ("yes" == ne && "yes" == ie) {
this.plugin.settings = _;
this.plugin.usedPassphrase = "";
this.suspendAllSync();
this.suspendExtraSync();
await this.plugin.saveSettings();
if ("yes" == await askYesNo(this.app, "Unlock and replicate?")) {
await this.plugin.replicate(true);
await this.plugin.markRemoteUnlocked();
}
Logger("Configuration loaded.", LOG_LEVEL_NOTICE);
return;
}
if ("no" == ne && "no" == ie) if ("yes" != await askYesNo(this.app, "Drop everything?")) {
Logger("Cancelled", LOG_LEVEL_NOTICE);
this.plugin.settings = ee;
return;
}
let re;
this.plugin.settings = _;
this.plugin.usedPassphrase = "";
await this.plugin.saveSettings();
if ("no" == ne) {
await this.plugin.resetLocalDatabase();
await this.plugin.localDatabase.initializeDatabase();
if ("yes" == await askYesNo(this.app, "Rebuild the database?")) re = this.plugin.initializeDatabase(true); else await this.plugin.markRemoteResolved();
}
if ("no" == ie) {
await this.plugin.tryResetRemoteDatabase();
await this.plugin.markRemoteLocked();
}
if ("no" == ne || "no" == ie) if ("yes" == await askYesNo(this.app, "Replicate once?")) {
if (null != re) await re;
await this.plugin.replicate(true);
}
}
}
Logger("Configuration loaded.", LOG_LEVEL_NOTICE);
} else Logger("Cancelled.", LOG_LEVEL_NOTICE);
} catch (_) {
Logger("Couldn't parse or decrypt configuration uri.", LOG_LEVEL_NOTICE);
}
}
suspendExtraSync() {
Logger("Hidden files and plugin synchronization have been temporarily disabled. Please enable them after the fetching, if you need them.", LOG_LEVEL_NOTICE);
this.plugin.settings.syncInternalFiles = false;
this.plugin.settings.usePluginSync = false;
this.plugin.settings.autoSweepPlugins = false;
}
async askHiddenFileConfiguration(_) {
this.plugin.addOnSetup.suspendExtraSync();
const ee = `Would you like to enable \`Hidden File Synchronization\` or \`Customization sync\`?\n${_.enableFetch ? " - Fetch: Use files stored from other devices. \n" : ""}${_.enableOverwrite ? "- Overwrite: Use files from this device. \n" : ""}- Custom: Synchronize only customization files with a dedicated interface.\n- Keep them disabled: Do not use hidden file synchronization.\nOf course, we are able to disable these features.`, ne = "Fetch", ie = "Overwrite", re = "Custom", se = "keep them disabled", oe = [];
if (null == _ ? void 0 : _.enableFetch) oe.push(ne);
if (null == _ ? void 0 : _.enableOverwrite) oe.push(ie);
oe.push(re);
oe.push(se);
const le = await confirmWithMessage(this.plugin, "Hidden file sync", ee, oe, se, 40);
if (le == ne) await this.configureHiddenFileSync("FETCH"); else if (le == ie) await this.configureHiddenFileSync("OVERWRITE"); else if (le == se) await this.configureHiddenFileSync("DISABLE"); else if (le == re) await this.configureHiddenFileSync("CUSTOMIZE");
}
async configureHiddenFileSync(_) {
this.plugin.addOnSetup.suspendExtraSync();
if ("DISABLE" != _) {
if ("CUSTOMIZE" != _) {
Logger("Gathering files for enabling Hidden File Sync", LOG_LEVEL_NOTICE);
if ("FETCH" == _) await this.plugin.addOnHiddenFileSync.syncInternalFilesAndDatabase("pullForce", true); else if ("OVERWRITE" == _) await this.plugin.addOnHiddenFileSync.syncInternalFilesAndDatabase("pushForce", true); else if ("MERGE" == _) await this.plugin.addOnHiddenFileSync.syncInternalFilesAndDatabase("safe", true);
this.plugin.settings.syncInternalFiles = true;
await this.plugin.saveSettings();
Logger("Done! Restarting the app is strongly recommended!", LOG_LEVEL_NOTICE);
} else if ("CUSTOMIZE" == _) {
if (!this.plugin.deviceAndVaultName) {
let _ = await askString(this.app, "Device name", "Please set this device name", "desktop");
if (!_) {
if (import_obsidian.Platform.isAndroidApp) _ = "android-app"; else if (import_obsidian.Platform.isIosApp) _ = "ios"; else if (import_obsidian.Platform.isMacOS) _ = "macos"; else if (import_obsidian.Platform.isMobileApp) _ = "mobile-app"; else if (import_obsidian.Platform.isMobile) _ = "mobile"; else if (import_obsidian.Platform.isSafari) _ = "safari"; else if (import_obsidian.Platform.isDesktop) _ = "desktop"; else if (import_obsidian.Platform.isDesktopApp) _ = "desktop-app"; else _ = "unknown";
_ += Math.random().toString(36).slice(-4);
}
this.plugin.deviceAndVaultName = _;
}
this.plugin.settings.usePluginSync = true;
await this.plugin.saveSettings();
await this.plugin.addOnConfigSync.scanAllConfigFiles(true);
}
} else {
this.plugin.settings.syncInternalFiles = false;
this.plugin.settings.usePluginSync = false;
await this.plugin.saveSettings();
}
}
suspendAllSync() {
this.plugin.settings.liveSync = false;
this.plugin.settings.periodicReplication = false;
this.plugin.settings.syncOnSave = false;
this.plugin.settings.syncOnEditorSave = false;
this.plugin.settings.syncOnStart = false;
this.plugin.settings.syncOnFileOpen = false;
this.plugin.settings.syncAfterMerge = false;
}
async suspendReflectingDatabase() {
if (!this.plugin.settings.doNotSuspendOnFetching) if (this.plugin.settings.remoteType != REMOTE_MINIO) {
Logger("Suspending reflection: Database and storage changes will not be reflected in each other until completely finished the fetching.", LOG_LEVEL_NOTICE);
this.plugin.settings.suspendParseReplicationResult = true;
this.plugin.settings.suspendFileWatching = true;
await this.plugin.saveSettings();
}
}
async resumeReflectingDatabase() {
if (!this.plugin.settings.doNotSuspendOnFetching) if (this.plugin.settings.remoteType != REMOTE_MINIO) {
Logger("Database and storage reflection has been resumed!", LOG_LEVEL_NOTICE);
this.plugin.settings.suspendParseReplicationResult = false;
this.plugin.settings.suspendFileWatching = false;
await this.plugin.syncAllFiles(true);
await this.plugin.loadQueuedFiles();
await this.plugin.saveSettings();
}
}
async askUseNewAdapter() {
if (!this.plugin.settings.useIndexedDBAdapter) {
const _ = "Now this plugin has been configured to use the old database adapter for keeping compatibility. Do you want to deactivate it?", ee = "Yes, disable and use latest", ne = [ ee, "No, keep compatibility" ];
if (await confirmWithMessage(this.plugin, "Database adapter", _, ne, ee, 10) == ee) this.plugin.settings.useIndexedDBAdapter = true;
}
}
async resetLocalDatabase() {
if (this.plugin.settings.isConfigured && "" == this.plugin.settings.additionalSuffixOfDatabaseName) await this.plugin.resetLocalDatabase();
this.plugin.settings.additionalSuffixOfDatabaseName = `${"appId" in this.app ? this.app.appId : ""}`;
await this.plugin.resetLocalDatabase();
}
async fetchRemoteChunks() {
if (!this.plugin.settings.doNotSuspendOnFetching && this.plugin.settings.readChunksOnline && this.plugin.settings.remoteType == REMOTE_COUCHDB) {
Logger("Fetching chunks", LOG_LEVEL_NOTICE);
const _ = this.plugin.getReplicator(), ee = await _.connectRemoteCouchDBWithSetting(this.settings, this.plugin.getIsMobile(), true);
if ("string" == typeof ee) Logger(ee, LOG_LEVEL_NOTICE); else await fetchAllUsedChunks(this.localDatabase.localDatabase, ee.db);
Logger("Fetching chunks done", LOG_LEVEL_NOTICE);
}
}
async fetchLocal(_) {
this.suspendExtraSync();
await this.askUseNewAdapter();
this.plugin.settings.isConfigured = true;
await this.suspendReflectingDatabase();
await this.plugin.realizeSettingSyncMode();
await this.resetLocalDatabase();
await delay(1e3);
await this.plugin.openDatabase();
this.plugin.isReady = true;
if (_) await this.plugin.initializeDatabase(true);
await this.plugin.markRemoteResolved();
await delay(500);
await this.plugin.replicateAllFromServer(true);
await delay(1e3);
await this.plugin.replicateAllFromServer(true);
await this.resumeReflectingDatabase();
await this.askHiddenFileConfiguration({
enableFetch: true
});
}
async fetchLocalWithRebuild() {
return await this.fetchLocal(true);
}
async rebuildRemote() {
this.suspendExtraSync();
this.plugin.settings.isConfigured = true;
await this.plugin.realizeSettingSyncMode();
await this.plugin.markRemoteLocked();
await this.plugin.tryResetRemoteDatabase();
await this.plugin.markRemoteLocked();
await delay(500);
await this.askHiddenFileConfiguration({
enableOverwrite: true
});
await delay(1e3);
await this.plugin.replicateAllToServer(true);
await delay(1e3);
await this.plugin.replicateAllToServer(true);
}
async rebuildEverything() {
this.suspendExtraSync();
await this.askUseNewAdapter();
this.plugin.settings.isConfigured = true;
await this.plugin.realizeSettingSyncMode();
await this.resetLocalDatabase();
await delay(1e3);
await this.plugin.initializeDatabase(true);
await this.plugin.markRemoteLocked();
await this.plugin.tryResetRemoteDatabase();
await this.plugin.markRemoteLocked();
await delay(500);
await this.askHiddenFileConfiguration({
enableOverwrite: true
});
await delay(1e3);
await this.plugin.replicateAllToServer(true);
await delay(1e3);
await this.plugin.replicateAllToServer(true);
}
};
function add_css5(_) {
append_styles(_, "svelte-1vjy5r1", ".svelte-1vjy5r1.svelte-1vjy5r1.svelte-1vjy5r1{box-sizing:border-box}.globalhistory.svelte-1vjy5r1.svelte-1vjy5r1.svelte-1vjy5r1{margin-bottom:2em}table.svelte-1vjy5r1.svelte-1vjy5r1.svelte-1vjy5r1{width:100%}.more.svelte-1vjy5r1>div.svelte-1vjy5r1.svelte-1vjy5r1{display:flex}.more.svelte-1vjy5r1>div.svelte-1vjy5r1>button.svelte-1vjy5r1{flex-grow:1}th.svelte-1vjy5r1.svelte-1vjy5r1.svelte-1vjy5r1{position:sticky;top:0;backdrop-filter:blur(10px)}td.mtime.svelte-1vjy5r1.svelte-1vjy5r1.svelte-1vjy5r1{white-space:break-spaces}td.path.svelte-1vjy5r1.svelte-1vjy5r1.svelte-1vjy5r1{word-break:break-word}.row.svelte-1vjy5r1.svelte-1vjy5r1.svelte-1vjy5r1{display:flex;flex-direction:row;flex-wrap:wrap}.row.svelte-1vjy5r1>label.svelte-1vjy5r1.svelte-1vjy5r1{display:flex;align-items:center;min-width:5em}.row.svelte-1vjy5r1>input.svelte-1vjy5r1.svelte-1vjy5r1{flex-grow:1}.filenames.svelte-1vjy5r1.svelte-1vjy5r1.svelte-1vjy5r1{display:flex;flex-direction:column}.filenames.svelte-1vjy5r1>.path.svelte-1vjy5r1.svelte-1vjy5r1{font-size:70%}.rev.svelte-1vjy5r1.svelte-1vjy5r1.svelte-1vjy5r1{text-overflow:ellipsis;max-width:3em;display:inline-block;overflow:hidden;white-space:nowrap}");
}
function get_each_context5(_, ee, ne) {
const ie = _.slice();
ie[26] = ee[ne];
return ie;
}
function create_if_block_53(_) {
let ee;
return {
c() {
ee = element("div");
ee.textContent = "Gathering information...";
attr(ee, "class", " svelte-1vjy5r1");
},
m(_, ne) {
insert(_, ee, ne);
},
d(_) {
if (_) detach(ee);
}
};
}
function create_if_block_44(_) {
let ee;
return {
c() {
ee = element("th");
ee.textContent = "Chunks";
attr(ee, "class", "svelte-1vjy5r1");
},
m(_, ne) {
insert(_, ee, ne);
},
d(_) {
if (_) detach(ee);
}
};
}
function create_else_block_23(_) {
let ee, ne, ie, re;
return {
c() {
ee = element("div");
ne = element("button");
ne.textContent = "+1 week";
attr(ne, "class", "svelte-1vjy5r1");
attr(ee, "class", "svelte-1vjy5r1");
},
m(se, oe) {
insert(se, ee, oe);
append(ee, ne);
if (!ie) {
re = listen(ne, "click", _[17]);
ie = true;
}
},
p: noop2,
d(_) {
if (_) detach(ee);
ie = false;
re();
}
};
}
function create_if_block_34(_) {
let ee;
return {
c() {
ee = element("div");
attr(ee, "class", " svelte-1vjy5r1");
},
m(_, ne) {
insert(_, ee, ne);
},
p: noop2,
d(_) {
if (_) detach(ee);
}
};
}
function create_else_block_14(_) {
let ee, ne = _[26].rev + "";
return {
c() {
ee = text(ne);
},
m(_, ne) {
insert(_, ee, ne);
},
p(_, ie) {
if (32 & ie && ne !== (ne = _[26].rev + "")) set_data(ee, ne);
},
d(_) {
if (_) detach(ee);
}
};
}
function create_if_block_24(_) {
let ee, ne, ie, re, se = _[26].rev + "";
function click_handler_2() {
return _[19](_[26]);
}
return {
c() {
ee = element("a");
ne = text(se);
attr(ee, "class", "svelte-1vjy5r1");
},
m(_, se) {
insert(_, ee, se);
append(ee, ne);
if (!ie) {
re = listen(ee, "click", click_handler_2);
ie = true;
}
},
p(ee, ie) {
_ = ee;
if (32 & ie && se !== (se = _[26].rev + "")) set_data(ne, se);
},
d(_) {
if (_) detach(ee);
ie = false;
re();
}
};
}
function create_if_block_14(_) {
let ee, ne, ie = _[26].chunks + "";
return {
c() {
ee = element("td");
ne = text(ie);
attr(ee, "class", "svelte-1vjy5r1");
},
m(_, ie) {
insert(_, ee, ie);
append(ee, ne);
},
p(_, ee) {
if (32 & ee && ie !== (ie = _[26].chunks + "")) set_data(ne, ie);
},
d(_) {
if (_) detach(ee);
}
};
}
function create_each_block5(_) {
let ee, ne, ie, re, se, oe, le, ue, de, fe, he, pe, ge, me, ye, ve, Se, Ee, Ce, we, Oe, ke, xe = _[26].mtimeDisp + "", Ae = _[26].dirname.split("/").join("/") + "", Le = _[26].filename + "", Re = _[26].changes + "";
function click_handler_1() {
return _[18](_[26]);
}
function select_block_type_1(_, ee) {
if (_[26].isPlain) return create_if_block_24; else return create_else_block_14;
}
let Te = select_block_type_1(_), Pe = Te(_), Ie = _[1] && create_if_block_14(_);
return {
c() {
ee = element("tr");
ne = element("td");
ie = text(xe);
re = space();
se = element("td");
oe = element("div");
le = element("span");
ue = text("/");
de = text(Ae);
fe = space();
he = element("span");
pe = element("a");
ge = text(Le);
me = space();
ye = element("td");
ve = element("span");
Pe.c();
Se = space();
Ee = element("td");
Ce = text(Re);
we = space();
if (Ie) Ie.c();
attr(ne, "class", "mtime svelte-1vjy5r1");
attr(le, "class", "path svelte-1vjy5r1");
attr(pe, "class", "svelte-1vjy5r1");
attr(he, "class", "filename svelte-1vjy5r1");
attr(oe, "class", "filenames svelte-1vjy5r1");
attr(se, "class", "path svelte-1vjy5r1");
attr(ve, "class", "rev svelte-1vjy5r1");
attr(ye, "class", "svelte-1vjy5r1");
attr(Ee, "class", "svelte-1vjy5r1");
attr(ee, "class", "svelte-1vjy5r1");
},
m(_, xe) {
insert(_, ee, xe);
append(ee, ne);
append(ne, ie);
append(ee, re);
append(ee, se);
append(se, oe);
append(oe, le);
append(le, ue);
append(le, de);
append(oe, fe);
append(oe, he);
append(he, pe);
append(pe, ge);
append(ee, me);
append(ee, ye);
append(ye, ve);
Pe.m(ve, null);
append(ee, Se);
append(ee, Ee);
append(Ee, Ce);
append(ee, we);
if (Ie) Ie.m(ee, null);
if (!Oe) {
ke = listen(pe, "click", click_handler_1);
Oe = true;
}
},
p(ne, re) {
_ = ne;
if (32 & re && xe !== (xe = _[26].mtimeDisp + "")) set_data(ie, xe);
if (32 & re && Ae !== (Ae = _[26].dirname.split("/").join("/") + "")) set_data(de, Ae);
if (32 & re && Le !== (Le = _[26].filename + "")) set_data(ge, Le);
if (Te === (Te = select_block_type_1(_)) && Pe) Pe.p(_, re); else {
Pe.d(1);
Pe = Te(_);
if (Pe) {
Pe.c();
Pe.m(ve, null);
}
}
if (32 & re && Re !== (Re = _[26].changes + "")) set_data(Ce, Re);
if (_[1]) if (Ie) Ie.p(_, re); else {
Ie = create_if_block_14(_);
Ie.c();
Ie.m(ee, null);
} else if (Ie) {
Ie.d(1);
Ie = null;
}
},
d(_) {
if (_) detach(ee);
Pe.d();
if (Ie) Ie.d();
Oe = false;
ke();
}
};
}
function create_else_block4(_) {
let ee, ne, ie, re;
return {
c() {
ee = element("div");
ne = element("button");
ne.textContent = "+1 week";
attr(ne, "class", "svelte-1vjy5r1");
attr(ee, "class", "svelte-1vjy5r1");
},
m(se, oe) {
insert(se, ee, oe);
append(ee, ne);
if (!ie) {
re = listen(ne, "click", _[20]);
ie = true;
}
},
p: noop2,
d(_) {
if (_) detach(ee);
ie = false;
re();
}
};
}
function create_if_block4(_) {
let ee;
return {
c() {
ee = element("div");
attr(ee, "class", " svelte-1vjy5r1");
},
m(_, ne) {
insert(_, ee, ne);
},
p: noop2,
d(_) {
if (_) detach(ee);
}
};
}
function create_fragment5(_) {
let ee, ne, ie, re, se, oe, le, ue, de, fe, he, pe, ge, me, ye, ve, Se, Ee, Ce, we, Oe, ke, xe, Ae, Le, Re, Te, Pe, Ie, De, Be, Ne, Me, Fe, je, $e, Ge, Ve, Ue, ze, qe, He, Ke, We, Xe, Je, Qe, Ye = _[6] && create_if_block_53(_), Ze = _[1] && create_if_block_44(_);
function select_block_type(_, ee) {
if (_[6]) return create_if_block_34; else return create_else_block_23;
}
let tt = select_block_type(_), nt = tt(_), it = ensure_array_like(_[5]), rt = [];
for (let ee = 0; ee < it.length; ee += 1) rt[ee] = create_each_block5(get_each_context5(_, it, ee));
function select_block_type_2(_, ee) {
if (_[6]) return create_if_block4; else return create_else_block4;
}
let st = select_block_type_2(_), ot = st(_);
return {
c() {
ee = element("div");
ne = element("h1");
ne.textContent = "Vault history";
ie = space();
re = element("div");
se = element("div");
oe = element("label");
oe.textContent = "From:";
le = element("input");
ue = space();
de = element("div");
fe = element("label");
fe.textContent = "To:";
he = element("input");
pe = space();
ge = element("div");
me = element("label");
me.textContent = "Info:";
ye = space();
ve = element("label");
Se = element("input");
Ee = element("span");
Ee.textContent = "Diff";
Ce = space();
we = element("label");
Oe = element("input");
ke = element("span");
ke.textContent = "Chunks";
xe = space();
Ae = element("label");
Le = element("input");
Re = element("span");
Re.textContent = "File integrity";
Te = space();
if (Ye) Ye.c();
Pe = space();
Ie = element("table");
De = element("tr");
Be = element("th");
Be.textContent = "Date";
Ne = space();
Me = element("th");
Me.textContent = "Path";
Fe = space();
je = element("th");
je.textContent = "Rev";
$e = space();
Ge = element("th");
Ge.textContent = "Stat";
Ve = space();
if (Ze) Ze.c();
Ue = space();
ze = element("tr");
qe = element("td");
nt.c();
He = space();
for (let _ = 0; _ < rt.length; _ += 1) rt[_].c();
Ke = space();
We = element("tr");
Xe = element("td");
ot.c();
attr(ne, "class", "svelte-1vjy5r1");
attr(oe, "for", "");
attr(oe, "class", "svelte-1vjy5r1");
attr(le, "type", "date");
le.disabled = _[6];
attr(le, "class", "svelte-1vjy5r1");
attr(se, "class", "row svelte-1vjy5r1");
attr(fe, "for", "");
attr(fe, "class", "svelte-1vjy5r1");
attr(he, "type", "date");
he.disabled = _[6];
attr(he, "class", "svelte-1vjy5r1");
attr(de, "class", "row svelte-1vjy5r1");
attr(me, "for", "");
attr(me, "class", "svelte-1vjy5r1");
attr(Se, "type", "checkbox");
Se.disabled = _[6];
attr(Se, "class", "svelte-1vjy5r1");
attr(Ee, "class", "svelte-1vjy5r1");
attr(ve, "class", "svelte-1vjy5r1");
attr(Oe, "type", "checkbox");
Oe.disabled = _[6];
attr(Oe, "class", "svelte-1vjy5r1");
attr(ke, "class", "svelte-1vjy5r1");
attr(we, "class", "svelte-1vjy5r1");
attr(Le, "type", "checkbox");
Le.disabled = _[6];
attr(Le, "class", "svelte-1vjy5r1");
attr(Re, "class", "svelte-1vjy5r1");
attr(Ae, "class", "svelte-1vjy5r1");
attr(ge, "class", "row svelte-1vjy5r1");
attr(re, "class", "control svelte-1vjy5r1");
attr(Be, "class", "svelte-1vjy5r1");
attr(Me, "class", "svelte-1vjy5r1");
attr(je, "class", "svelte-1vjy5r1");
attr(Ge, "class", "svelte-1vjy5r1");
attr(De, "class", "svelte-1vjy5r1");
attr(qe, "colspan", "5");
attr(qe, "class", "more svelte-1vjy5r1");
attr(ze, "class", "svelte-1vjy5r1");
attr(Xe, "colspan", "5");
attr(Xe, "class", "more svelte-1vjy5r1");
attr(We, "class", "svelte-1vjy5r1");
attr(Ie, "class", "svelte-1vjy5r1");
attr(ee, "class", "globalhistory svelte-1vjy5r1");
},
m(tt, it) {
insert(tt, ee, it);
append(ee, ne);
append(ee, ie);
append(ee, re);
append(re, se);
append(se, oe);
append(se, le);
set_input_value(le, _[3]);
append(re, ue);
append(re, de);
append(de, fe);
append(de, he);
set_input_value(he, _[4]);
append(re, pe);
append(re, ge);
append(ge, me);
append(ge, ye);
append(ge, ve);
append(ve, Se);
Se.checked = _[0];
append(ve, Ee);
append(ge, Ce);
append(ge, we);
append(we, Oe);
Oe.checked = _[1];
append(we, ke);
append(ge, xe);
append(ge, Ae);
append(Ae, Le);
Le.checked = _[2];
append(Ae, Re);
append(ee, Te);
if (Ye) Ye.m(ee, null);
append(ee, Pe);
append(ee, Ie);
append(Ie, De);
append(De, Be);
append(De, Ne);
append(De, Me);
append(De, Fe);
append(De, je);
append(De, $e);
append(De, Ge);
append(De, Ve);
if (Ze) Ze.m(De, null);
append(Ie, Ue);
append(Ie, ze);
append(ze, qe);
nt.m(qe, null);
append(Ie, He);
for (let _ = 0; _ < rt.length; _ += 1) if (rt[_]) rt[_].m(Ie, null);
append(Ie, Ke);
append(Ie, We);
append(We, Xe);
ot.m(Xe, null);
if (!Je) {
Qe = [ listen(le, "input", _[12]), listen(he, "input", _[13]), listen(Se, "change", _[14]), listen(Oe, "change", _[15]), listen(Le, "change", _[16]) ];
Je = true;
}
},
p(_, [ne]) {
if (64 & ne) le.disabled = _[6];
if (8 & ne) set_input_value(le, _[3]);
if (64 & ne) he.disabled = _[6];
if (16 & ne) set_input_value(he, _[4]);
if (64 & ne) Se.disabled = _[6];
if (1 & ne) Se.checked = _[0];
if (64 & ne) Oe.disabled = _[6];
if (2 & ne) Oe.checked = _[1];
if (64 & ne) Le.disabled = _[6];
if (4 & ne) Le.checked = _[2];
if (_[6]) if (Ye) ; else {
Ye = create_if_block_53(_);
Ye.c();
Ye.m(ee, Pe);
} else if (Ye) {
Ye.d(1);
Ye = null;
}
if (_[1]) if (Ze) ; else {
Ze = create_if_block_44(_);
Ze.c();
Ze.m(De, null);
} else if (Ze) {
Ze.d(1);
Ze = null;
}
if (tt === (tt = select_block_type(_)) && nt) nt.p(_, ne); else {
nt.d(1);
nt = tt(_);
if (nt) {
nt.c();
nt.m(qe, null);
}
}
if (1570 & ne) {
it = ensure_array_like(_[5]);
let ee;
for (ee = 0; ee < it.length; ee += 1) {
const ie = get_each_context5(_, it, ee);
if (rt[ee]) rt[ee].p(ie, ne); else {
rt[ee] = create_each_block5(ie);
rt[ee].c();
rt[ee].m(Ie, Ke);
}
}
for (;ee < rt.length; ee += 1) rt[ee].d(1);
rt.length = it.length;
}
if (st === (st = select_block_type_2(_)) && ot) ot.p(_, ne); else {
ot.d(1);
ot = st(_);
if (ot) {
ot.c();
ot.m(Xe, null);
}
}
},
i: noop2,
o: noop2,
d(_) {
if (_) detach(ee);
if (Ye) Ye.d();
if (Ze) Ze.d();
nt.d();
destroy_each(rt, _);
ot.d();
Je = false;
run_all(Qe);
}
};
}
function mtimeToDate(_) {
return new Date(_).toLocaleString();
}
function instance5(_, ee, ne) {
let {plugin: ie} = ee, re = false, se = false, oe = false, le = Date.now() - 6048e5, ue = Date.now() + 1728e5;
const de = (new Date).getTimezoneOffset();
let fe = new Date(le - de).toISOString().split("T")[0], he = new Date(ue - de).toISOString().split("T")[0], pe = [], ge = false;
async function getHistory(_, ee, de) {
ne(6, ge = true);
const fe = [], he = await async function fetchChanges() {
var _, ee, de;
try {
const ne = ie.localDatabase;
let fe = [];
for await (const he of ne.findAllNormalDocs()) {
if (he.mtime < le) continue;
if (!isAnyNote(he)) continue;
const pe = ie.getPath(he), ge = isPlainText(he.path);
let me;
const ye = (null !== (_ = (await ne.getRaw(he._id, {
revs_info: true
}))._revs_info) && void 0 !== _ ? _ : []).reverse(), ve = -1, Se = 0, Ee = 1;
for (const _ of ye) if ("available" == _.status) {
const ye = !ge && re || oe && _.rev == he._rev ? await ne.getDBEntry(pe, {
rev: _.rev
}, false, false, true) : await ne.getDBEntryMeta(pe, {
rev: _.rev
}, true);
if (false === ye) continue;
const Ce = _.rev, we = "mtime" in ye ? ye.mtime : 0;
if (le > we) continue;
if (ue < we) continue;
let Oe = "";
if (re && !ge) {
const _ = getDocData(ye.data);
if (void 0 === me) me = _;
if (me != _) {
const ee = new import_diff_match_patch.diff_match_patch, ne = ee.diff_main(me, _);
ee.diff_cleanupSemantic(ne);
me = _;
const ie = {
[ve]: 0,
[Se]: 0,
[Ee]: 0
}, re = ne.reduce(((_, ee) => {
var ne;
return {
..._,
[ee[0]]: (null !== (ne = _[ee[0]]) && void 0 !== ne ? ne : 0) + ee[1].length
};
}), ie);
Oe = `-${re[ve]}, +${re[Ee]}`;
}
}
const ke = ye._deleted || (null == ye ? void 0 : ye.deleted) || false;
if (ke) Oe += " 🗑️";
if (Ce == he._rev) if (oe) {
const _ = ie.vaultAccess.getAbstractFileByPath(stripAllPrefixes(ie.getPath(he)));
if (_ instanceof import_obsidian.TFile) {
const ee = await ie.vaultAccess.adapterReadAuto(_), ne = readAsBlob(ye);
if (await isDocContentSame(ee, ne)) Oe += " ⚖️"; else Oe += " ⚠️";
}
}
const xe = ie.getPath(ye), [Ae, ...Le] = xe.split("/").reverse();
let Re = "";
if (se) {
const _ = null !== (ee = null == ye ? void 0 : ye.children) && void 0 !== ee ? ee : [], ie = await ne.allDocsRaw({
keys: [ ..._ ]
}), re = ie.rows.length, se = ie.rows.filter((_ => "error" in _)).length;
if (0 == se) Re = `✅ ${re}`; else Re = `🔎 ${se} ✅ ${re}`;
}
fe.push({
id: ye._id,
rev: ye._rev,
path: xe,
dirname: Le.reverse().join("/"),
filename: Ae,
mtime: we,
mtimeDisp: mtimeToDate(we),
size: null !== (de = null == ye ? void 0 : ye.size) && void 0 !== de ? de : 0,
isDeleted: ke,
changes: Oe,
chunks: Re,
isPlain: ge
});
}
}
return [ ...fe ].sort(((_, ee) => ee.mtime - _.mtime));
} finally {
ne(6, ge = false);
}
}();
fe.push(...he);
ne(5, pe = [ ...fe ]);
}
function nextWeek() {
ne(4, he = new Date(ue - de + 6048e5).toISOString().split("T")[0]);
}
function prevWeek() {
ne(3, fe = new Date(le - de - 6048e5).toISOString().split("T")[0]);
}
onMount((async () => {
await getHistory();
}));
onDestroy((() => {}));
function showHistory(_, ee) {
new DocumentHistoryModal(ie.app, ie, _, void 0, ee).open();
}
function openFile(_) {
ie.app.workspace.openLinkText(_, _);
}
_.$$set = _ => {
if ("plugin" in _) ne(11, ie = _.plugin);
};
_.$$.update = () => {
if (31 & _.$$.dirty) {
le = new Date(fe).getTime() + de;
ue = new Date(he).getTime() + de;
getHistory();
}
};
return [ re, se, oe, fe, he, pe, ge, nextWeek, prevWeek, showHistory, openFile, ie, function input0_input_handler() {
fe = this.value;
ne(3, fe);
}, function input1_input_handler() {
he = this.value;
ne(4, he);
}, function input2_change_handler() {
re = this.checked;
ne(0, re);
}, function input3_change_handler() {
se = this.checked;
ne(1, se);
}, function input4_change_handler() {
oe = this.checked;
ne(2, oe);
}, () => nextWeek(), _ => openFile(_.path), _ => showHistory(_.path, (null == _ ? void 0 : _.rev) || ""), () => prevWeek() ];
}
var GlobalHistory = class extends SvelteComponent {
constructor(_) {
super();
init2(this, _, instance5, create_fragment5, safe_not_equal, {
plugin: 11
}, add_css5);
}
}, GlobalHistory_default = GlobalHistory, VIEW_TYPE_GLOBAL_HISTORY = "global-history", GlobalHistoryView = class extends import_obsidian.ItemView {
constructor(_, ee) {
super(_);
this.icon = "clock";
this.title = "";
this.navigation = true;
this.plugin = ee;
}
getIcon() {
return "clock";
}
getViewType() {
return VIEW_TYPE_GLOBAL_HISTORY;
}
getDisplayText() {
return "Vault history";
}
async onOpen() {
this.component = new GlobalHistory_default({
target: this.contentEl,
props: {
plugin: this.plugin
}
});
}
async onClose() {
var _;
null == (_ = this.component) || _.$destroy();
}
}, import_obsidian6 = require("obsidian");
function add_css6(_) {
append_styles(_, "svelte-1j0mkaj", ".svelte-1j0mkaj.svelte-1j0mkaj{box-sizing:border-box}.logpane.svelte-1j0mkaj.svelte-1j0mkaj{display:flex;height:100%;flex-direction:column}.log.svelte-1j0mkaj.svelte-1j0mkaj{overflow-y:scroll;user-select:text;padding-bottom:2em}.log.svelte-1j0mkaj>pre.svelte-1j0mkaj{margin:0}.log.svelte-1j0mkaj>pre.wrap-right.svelte-1j0mkaj{word-break:break-all;max-width:100%;width:100%;white-space:normal}.row.svelte-1j0mkaj.svelte-1j0mkaj{display:flex;flex-direction:row;justify-content:flex-end}.row.svelte-1j0mkaj>label.svelte-1j0mkaj{display:flex;align-items:center;min-width:5em;margin-right:1em}");
}
function get_each_context6(_, ee, ne) {
const ie = _.slice();
ie[11] = ee[ne];
return ie;
}
function create_each_block6(_) {
let ee, ne, ie = _[11] + "";
return {
c() {
ee = element("pre");
ne = text(ie);
attr(ee, "class", "svelte-1j0mkaj");
toggle_class(ee, "wrap-right", _[1]);
},
m(_, ie) {
insert(_, ee, ie);
append(ee, ne);
},
p(_, re) {
if (1 & re && ie !== (ie = _[11] + "")) set_data(ne, ie);
if (2 & re) toggle_class(ee, "wrap-right", _[1]);
},
d(_) {
if (_) detach(ee);
}
};
}
function create_fragment6(_) {
let ee, ne, ie, re, se, oe, le, ue, de, fe, he, pe, ge, me, ye, ve, Se, Ee, Ce = ensure_array_like(_[0]), we = [];
for (let ee = 0; ee < Ce.length; ee += 1) we[ee] = create_each_block6(get_each_context6(_, Ce, ee));
return {
c() {
ee = element("div");
ne = element("div");
ie = element("div");
re = element("label");
se = element("input");
oe = element("span");
oe.textContent = "Wrap";
le = space();
ue = element("label");
de = element("input");
fe = element("span");
fe.textContent = "Auto scroll";
he = space();
pe = element("label");
ge = element("input");
me = element("span");
me.textContent = "Pause";
ye = space();
ve = element("div");
for (let _ = 0; _ < we.length; _ += 1) we[_].c();
attr(se, "type", "checkbox");
attr(se, "class", "svelte-1j0mkaj");
attr(oe, "class", "svelte-1j0mkaj");
attr(re, "class", "svelte-1j0mkaj");
attr(de, "type", "checkbox");
attr(de, "class", "svelte-1j0mkaj");
attr(fe, "class", "svelte-1j0mkaj");
attr(ue, "class", "svelte-1j0mkaj");
attr(ge, "type", "checkbox");
attr(ge, "class", "svelte-1j0mkaj");
attr(me, "class", "svelte-1j0mkaj");
attr(pe, "class", "svelte-1j0mkaj");
attr(ie, "class", "row svelte-1j0mkaj");
attr(ne, "class", "control svelte-1j0mkaj");
attr(ve, "class", "log svelte-1j0mkaj");
attr(ee, "class", "logpane svelte-1j0mkaj");
},
m(Ce, Oe) {
insert(Ce, ee, Oe);
append(ee, ne);
append(ne, ie);
append(ie, re);
append(re, se);
se.checked = _[1];
append(re, oe);
append(ie, le);
append(ie, ue);
append(ue, de);
de.checked = _[2];
append(ue, fe);
append(ie, he);
append(ie, pe);
append(pe, ge);
ge.checked = _[3];
append(pe, me);
append(ee, ye);
append(ee, ve);
for (let _ = 0; _ < we.length; _ += 1) if (we[_]) we[_].m(ve, null);
_[8](ve);
if (!Se) {
Ee = [ listen(se, "change", _[5]), listen(de, "change", _[6]), listen(ge, "change", _[7]) ];
Se = true;
}
},
p(_, [ee]) {
if (2 & ee) se.checked = _[1];
if (4 & ee) de.checked = _[2];
if (8 & ee) ge.checked = _[3];
if (3 & ee) {
Ce = ensure_array_like(_[0]);
let ne;
for (ne = 0; ne < Ce.length; ne += 1) {
const ie = get_each_context6(_, Ce, ne);
if (we[ne]) we[ne].p(ie, ee); else {
we[ne] = create_each_block6(ie);
we[ne].c();
we[ne].m(ve, null);
}
}
for (;ne < we.length; ne += 1) we[ne].d(1);
we.length = Ce.length;
}
},
i: noop2,
o: noop2,
d(ne) {
if (ne) detach(ee);
destroy_each(we, ne);
_[8](null);
Se = false;
run_all(Ee);
}
};
}
function instance6(_, ee, ne) {
let ie, re, se = [], oe = false, le = true, ue = false;
function updateLog(_) {
const ee = _.value;
if (!ue) {
ne(0, se = [ ...ee ]);
setTimeout((() => {
if (re) ne(4, re.scrollTop = re.scrollHeight, re);
}), 10);
}
}
onMount((async () => {
logMessages.onChanged(updateLog);
Logger("Log window opened");
ie = () => logMessages.offChanged(updateLog);
}));
onDestroy((() => {
if (ie) ie();
}));
return [ se, oe, le, ue, re, function input0_change_handler() {
oe = this.checked;
ne(1, oe);
}, function input1_change_handler() {
le = this.checked;
ne(2, le);
}, function input2_change_handler() {
ue = this.checked;
ne(3, ue);
}, function div2_binding(_) {
binding_callbacks[_ ? "unshift" : "push"]((() => {
re = _;
ne(4, re);
}));
} ];
}
var LogPane = class extends SvelteComponent {
constructor(_) {
super();
init2(this, _, instance6, create_fragment6, safe_not_equal, {}, add_css6);
}
}, LogPane_default = LogPane, VIEW_TYPE_LOG = "log-log", LogPaneView = class extends import_obsidian6.ItemView {
constructor(_, ee) {
super(_);
this.icon = "view-log";
this.title = "";
this.navigation = true;
this.plugin = ee;
}
getIcon() {
return "view-log";
}
getViewType() {
return VIEW_TYPE_LOG;
}
getDisplayText() {
return "Self-hosted LiveSync Log";
}
async onOpen() {
this.component = new LogPane_default({
target: this.contentEl,
props: {}
});
}
async onClose() {
var _;
null == (_ = this.component) || _.$destroy();
}
};
function getFileLockKey(_) {
return `fl:${"string" == typeof _ ? _ : _.path}`;
}
function toArrayBuffer(_) {
if (_ instanceof Uint8Array) return _.buffer;
if (_ instanceof DataView) return _.buffer; else return _;
}
async function processReadFile(_, ee) {
return await serialized(getFileLockKey(_), (() => ee()));
}
async function processWriteFile(_, ee) {
return await serialized(getFileLockKey(_), (() => ee()));
}
var HttpAuthLocation, HttpApiKeyAuthLocation, EndpointURLScheme, AlgorithmId, FieldPosition, SerializedFileAccess = class {
constructor(_) {
this.touchedFiles = [];
this.app = _;
}
async adapterStat(_) {
const ee = _ instanceof import_obsidian.TFile ? _.path : _;
return await processReadFile(_, (() => this.app.vault.adapter.stat(ee)));
}
async adapterExists(_) {
const ee = _ instanceof import_obsidian.TFile ? _.path : _;
return await processReadFile(_, (() => this.app.vault.adapter.exists(ee)));
}
async adapterRemove(_) {
const ee = _ instanceof import_obsidian.TFile ? _.path : _;
return await processReadFile(_, (() => this.app.vault.adapter.remove(ee)));
}
async adapterRead(_) {
const ee = _ instanceof import_obsidian.TFile ? _.path : _;
return await processReadFile(_, (() => this.app.vault.adapter.read(ee)));
}
async adapterReadBinary(_) {
const ee = _ instanceof import_obsidian.TFile ? _.path : _;
return await processReadFile(_, (() => this.app.vault.adapter.readBinary(ee)));
}
async adapterReadAuto(_) {
const ee = _ instanceof import_obsidian.TFile ? _.path : _;
if (isPlainText(ee)) return await processReadFile(_, (() => this.app.vault.adapter.read(ee))); else return await processReadFile(_, (() => this.app.vault.adapter.readBinary(ee)));
}
async adapterWrite(_, ee, ne) {
const ie = _ instanceof import_obsidian.TFile ? _.path : _;
if ("string" == typeof ee) return await processWriteFile(_, (() => this.app.vault.adapter.write(ie, ee, ne))); else return await processWriteFile(_, (() => this.app.vault.adapter.writeBinary(ie, toArrayBuffer(ee), ne)));
}
async vaultCacheRead(_) {
return await processReadFile(_, (() => this.app.vault.cachedRead(_)));
}
async vaultRead(_) {
return await processReadFile(_, (() => this.app.vault.read(_)));
}
async vaultReadBinary(_) {
return await processReadFile(_, (() => this.app.vault.readBinary(_)));
}
async vaultReadAuto(_) {
if (isPlainText(_.path)) return await processReadFile(_, (() => this.app.vault.read(_))); else return await processReadFile(_, (() => this.app.vault.readBinary(_)));
}
async vaultModify(_, ee, ne) {
if ("string" == typeof ee) return await processWriteFile(_, (async () => {
const ie = await this.app.vault.read(_);
if (ee === ie) {
if (ne && ne.mtime) markChangesAreSame(_, _.stat.mtime, ne.mtime);
return false;
}
await this.app.vault.modify(_, ee, ne);
return true;
})); else return await processWriteFile(_, (async () => {
const ie = await this.app.vault.readBinary(_);
if (await isDocContentSame(createBinaryBlob(ie), createBinaryBlob(ee))) {
if (ne && ne.mtime) markChangesAreSame(_, _.stat.mtime, ne.mtime);
return false;
}
await this.app.vault.modifyBinary(_, toArrayBuffer(ee), ne);
return true;
}));
}
async vaultCreate(_, ee, ne) {
if ("string" == typeof ee) return await processWriteFile(_, (() => this.app.vault.create(_, ee, ne))); else return await processWriteFile(_, (() => this.app.vault.createBinary(_, toArrayBuffer(ee), ne)));
}
trigger(_, ...ee) {
return this.app.vault.trigger(_, ...ee);
}
async adapterAppend(_, ee, ne) {
return await this.app.vault.adapter.append(_, ee, ne);
}
async delete(_, ee = false) {
return await processWriteFile(_, (() => this.app.vault.delete(_, ee)));
}
async trash(_, ee = false) {
return await processWriteFile(_, (() => this.app.vault.trash(_, ee)));
}
getAbstractFileByPath(_) {
return this.app.vault.getAbstractFileByPath(_);
}
getFiles() {
return this.app.vault.getFiles();
}
async ensureDirectory(_) {
const ee = _.split("/");
ee.pop();
let ne = "";
for (const _ of ee) {
ne += _;
try {
await this.app.vault.adapter.mkdir(ne);
} catch (_) {
if ("Folder already exists." == (null == _ ? void 0 : _.message)) ; else {
Logger("Folder Create Error");
Logger(_);
}
}
ne += "/";
}
}
touch(_) {
const ee = _ instanceof import_obsidian.TFile ? _ : this.getAbstractFileByPath(_), ne = `${ee.path}-${ee.stat.mtime}-${ee.stat.size}`;
this.touchedFiles.unshift(ne);
this.touchedFiles = this.touchedFiles.slice(0, 100);
}
recentlyTouched(_) {
const ee = _ instanceof import_obsidian.TFile ? `${_.path}-${_.stat.mtime}-${_.stat.size}` : `${_.path}-${_.mtime}-${_.size}`;
if (-1 == this.touchedFiles.indexOf(ee)) return false; else return true;
}
clearTouched() {
this.touchedFiles = [];
}
}, getHttpHandlerExtensionConfiguration = _ => {
let ee = _.httpHandler;
return {
setHttpHandler(_) {
ee = _;
},
httpHandler: () => ee,
updateHttpClientConfig(_, ne) {
ee.updateHttpClientConfig(_, ne);
},
httpHandlerConfigs: () => ee.httpHandlerConfigs()
};
}, resolveHttpHandlerRuntimeConfig = _ => ({
httpHandler: _.httpHandler()
});
(function(_) {
_["HEADER"] = "header";
_["QUERY"] = "query";
})(HttpAuthLocation || (HttpAuthLocation = {}));
(function(_) {
_["HEADER"] = "header";
_["QUERY"] = "query";
})(HttpApiKeyAuthLocation || (HttpApiKeyAuthLocation = {}));
(function(_) {
_["HTTP"] = "http";
_["HTTPS"] = "https";
})(EndpointURLScheme || (EndpointURLScheme = {}));
(function(_) {
_["MD5"] = "md5";
_["CRC32"] = "crc32";
_["CRC32C"] = "crc32c";
_["SHA1"] = "sha1";
_["SHA256"] = "sha256";
})(AlgorithmId || (AlgorithmId = {}));
(function(_) {
_[_["HEADER"] = 0] = "HEADER";
_[_["TRAILER"] = 1] = "TRAILER";
})(FieldPosition || (FieldPosition = {}));
var IniSectionType, RequestHandlerProtocol, SMITHY_CONTEXT_KEY = "__smithy_context";
(function(_) {
_["PROFILE"] = "profile";
_["SSO_SESSION"] = "sso-session";
_["SERVICES"] = "services";
})(IniSectionType || (IniSectionType = {}));
(function(_) {
_["HTTP_0_9"] = "http/0.9";
_["HTTP_1_0"] = "http/1.0";
_["TDS_8_0"] = "tds/8.0";
})(RequestHandlerProtocol || (RequestHandlerProtocol = {}));
var HttpRequest = class _HttpRequest {
constructor(_) {
this.method = _.method || "GET";
this.hostname = _.hostname || "localhost";
this.port = _.port;
this.query = _.query || {};
this.headers = _.headers || {};
this.body = _.body;
this.protocol = _.protocol ? ":" !== _.protocol.slice(-1) ? `${_.protocol}:` : _.protocol : "https:";
this.path = _.path ? "/" !== _.path.charAt(0) ? `/${_.path}` : _.path : "/";
this.username = _.username;
this.password = _.password;
this.fragment = _.fragment;
}
static isInstance(_) {
if (!_) return false;
const ee = _;
return "method" in ee && "protocol" in ee && "hostname" in ee && "path" in ee && "object" == typeof ee["query"] && "object" == typeof ee["headers"];
}
clone() {
const _ = new _HttpRequest({
...this,
headers: {
...this.headers
}
});
if (_.query) _.query = cloneQuery(_.query);
return _;
}
};
function cloneQuery(_) {
return Object.keys(_).reduce(((ee, ne) => {
const ie = _[ne];
return {
...ee,
[ne]: Array.isArray(ie) ? [ ...ie ] : ie
};
}), {});
}
var HttpResponse = class {
constructor(_) {
this.statusCode = _.statusCode;
this.reason = _.reason;
this.headers = _.headers || {};
this.body = _.body;
}
static isInstance(_) {
if (!_) return false;
const ee = _;
return "number" == typeof ee.statusCode && "object" == typeof ee.headers;
}
};
function isValidHostname(_) {
return /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/.test(_);
}
function addExpectContinueMiddleware(_) {
return ee => async ne => {
const {request: ie} = ne;
if (HttpRequest.isInstance(ie) && ie.body && "node" === _.runtime) ie.headers = {
...ie.headers,
Expect: "100-continue"
};
return ee({
...ne,
request: ie
});
};
}
var addExpectContinueMiddlewareOptions = {
step: "build",
tags: [ "SET_EXPECT_HEADER", "EXPECT_HEADER" ],
name: "addExpectContinueMiddleware",
override: true
}, getAddExpectContinuePlugin = _ => ({
applyToStack: ee => {
ee.add(addExpectContinueMiddleware(_), addExpectContinueMiddlewareOptions);
}
});
function resolveHostHeaderConfig(_) {
return _;
}
var hostHeaderMiddleware = _ => ee => async ne => {
if (!HttpRequest.isInstance(ne.request)) return ee(ne);
const {request: ie} = ne, {handlerProtocol: re = ""} = _.requestHandler.metadata || {};
if (re.indexOf("h2") >= 0 && !ie.headers[":authority"]) {
delete ie.headers["host"];
ie.headers[":authority"] = ie.hostname + (ie.port ? ":" + ie.port : "");
} else if (!ie.headers["host"]) {
let _ = ie.hostname;
if (null != ie.port) _ += `:${ie.port}`;
ie.headers["host"] = _;
}
return ee(ne);
}, hostHeaderMiddlewareOptions = {
name: "hostHeaderMiddleware",
step: "build",
priority: "low",
tags: [ "HOST" ],
override: true
}, getHostHeaderPlugin = _ => ({
applyToStack: ee => {
ee.add(hostHeaderMiddleware(_), hostHeaderMiddlewareOptions);
}
}), loggerMiddleware = () => (_, ee) => async ne => {
var ie, re;
try {
const re = await _(ne), {clientName: se, commandName: oe, logger: le, dynamoDbDocumentClientOptions: ue = {}} = ee, {overrideInputFilterSensitiveLog: de, overrideOutputFilterSensitiveLog: fe} = ue, he = null != de ? de : ee.inputFilterSensitiveLog, pe = null != fe ? fe : ee.outputFilterSensitiveLog, {$metadata: ge, ...me} = re.output;
null == (ie = null == le ? void 0 : le.info) || ie.call(le, {
clientName: se,
commandName: oe,
input: he(ne.input),
output: pe(me),
metadata: ge
});
return re;
} catch (_) {
const {clientName: ie, commandName: se, logger: oe, dynamoDbDocumentClientOptions: le = {}} = ee, {overrideInputFilterSensitiveLog: ue} = le, de = null != ue ? ue : ee.inputFilterSensitiveLog;
null == (re = null == oe ? void 0 : oe.error) || re.call(oe, {
clientName: ie,
commandName: se,
input: de(ne.input),
error: _,
metadata: _.$metadata
});
throw _;
}
}, loggerMiddlewareOptions = {
name: "loggerMiddleware",
tags: [ "LOGGER" ],
step: "initialize",
override: true
}, getLoggerPlugin = _ => ({
applyToStack: _ => {
_.add(loggerMiddleware(), loggerMiddlewareOptions);
}
}), TRACE_ID_HEADER_NAME = "X-Amzn-Trace-Id", ENV_LAMBDA_FUNCTION_NAME = "AWS_LAMBDA_FUNCTION_NAME", ENV_TRACE_ID = "_X_AMZN_TRACE_ID", recursionDetectionMiddleware = _ => ee => async ne => {
const {request: ie} = ne;
if (!HttpRequest.isInstance(ie) || "node" !== _.runtime || ie.headers.hasOwnProperty(TRACE_ID_HEADER_NAME)) return ee(ne);
const re = process.env[ENV_LAMBDA_FUNCTION_NAME], se = process.env[ENV_TRACE_ID], nonEmptyString = _ => "string" == typeof _ && _.length > 0;
if (nonEmptyString(re) && nonEmptyString(se)) ie.headers[TRACE_ID_HEADER_NAME] = se;
return ee({
...ne,
request: ie
});
}, addRecursionDetectionMiddlewareOptions = {
step: "build",
tags: [ "RECURSION_DETECTION" ],
name: "recursionDetectionMiddleware",
override: true,
priority: "low"
}, getRecursionDetectionPlugin = _ => ({
applyToStack: ee => {
ee.add(recursionDetectionMiddleware(_), addRecursionDetectionMiddlewareOptions);
}
}), NoOpLogger = class {
trace() {}
debug() {}
info() {}
warn() {}
error() {}
}, getAllAliases = (_, ee) => {
const ne = [];
if (_) ne.push(_);
if (ee) for (const _ of ee) ne.push(_);
return ne;
}, getMiddlewareNameWithAliases = (_, ee) => `${_ || "anonymous"}${ee && ee.length > 0 ? ` (a.k.a. ${ee.join(",")})` : ""}`, constructStack = () => {
let _ = [], ee = [], ne = false;
const ie = new Set, cloneTo = ne => {
var ie;
_.forEach((_ => {
ne.add(_.middleware, {
..._
});
}));
ee.forEach((_ => {
ne.addRelativeTo(_.middleware, {
..._
});
}));
null == (ie = ne.identifyOnResolve) || ie.call(ne, re.identifyOnResolve());
return ne;
}, expandRelativeMiddlewareList = _ => {
const ee = [];
_.before.forEach((_ => {
if (0 === _.before.length && 0 === _.after.length) ee.push(_); else ee.push(...expandRelativeMiddlewareList(_));
}));
ee.push(_);
_.after.reverse().forEach((_ => {
if (0 === _.before.length && 0 === _.after.length) ee.push(_); else ee.push(...expandRelativeMiddlewareList(_));
}));
return ee;
}, getMiddlewareList = (ne = false) => {
const ie = [], re = [], se = {};
_.forEach((_ => {
const ee = {
..._,
before: [],
after: []
};
for (const _ of getAllAliases(ee.name, ee.aliases)) se[_] = ee;
ie.push(ee);
}));
ee.forEach((_ => {
const ee = {
..._,
before: [],
after: []
};
for (const _ of getAllAliases(ee.name, ee.aliases)) se[_] = ee;
re.push(ee);
}));
re.forEach((_ => {
if (_.toMiddleware) {
const ee = se[_.toMiddleware];
if (void 0 === ee) {
if (ne) return;
throw new Error(`${_.toMiddleware} is not found when adding ${getMiddlewareNameWithAliases(_.name, _.aliases)} middleware ${_.relation} ${_.toMiddleware}`);
}
if ("after" === _.relation) ee.after.push(_);
if ("before" === _.relation) ee.before.push(_);
}
}));
var oe;
return (oe = ie, oe.sort(((_, ee) => stepWeights[ee.step] - stepWeights[_.step] || priorityWeights[ee.priority || "normal"] - priorityWeights[_.priority || "normal"]))).map(expandRelativeMiddlewareList).reduce(((_, ee) => {
_.push(...ee);
return _;
}), []);
}, re = {
add: (ee, ne = {}) => {
const {name: re, override: se, aliases: oe} = ne, le = {
step: "initialize",
priority: "normal",
middleware: ee,
...ne
}, ue = getAllAliases(re, oe);
if (ue.length > 0) {
if (ue.some((_ => ie.has(_)))) {
if (!se) throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(re, oe)}'`);
for (const ee of ue) {
const ne = _.findIndex((_ => {
var ne;
return _.name === ee || (null == (ne = _.aliases) ? void 0 : ne.some((_ => _ === ee)));
}));
if (-1 === ne) continue;
const ie = _[ne];
if (ie.step !== le.step || le.priority !== ie.priority) throw new Error(`"${getMiddlewareNameWithAliases(ie.name, ie.aliases)}" middleware with ${ie.priority} priority in ${ie.step} step cannot be overridden by "${getMiddlewareNameWithAliases(re, oe)}" middleware with ${le.priority} priority in ${le.step} step.`);
_.splice(ne, 1);
}
}
for (const _ of ue) ie.add(_);
}
_.push(le);
},
addRelativeTo: (_, ne) => {
const {name: re, override: se, aliases: oe} = ne, le = {
middleware: _,
...ne
}, ue = getAllAliases(re, oe);
if (ue.length > 0) {
if (ue.some((_ => ie.has(_)))) {
if (!se) throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(re, oe)}'`);
for (const _ of ue) {
const ne = ee.findIndex((ee => {
var ne;
return ee.name === _ || (null == (ne = ee.aliases) ? void 0 : ne.some((ee => ee === _)));
}));
if (-1 === ne) continue;
const ie = ee[ne];
if (ie.toMiddleware !== le.toMiddleware || ie.relation !== le.relation) throw new Error(`"${getMiddlewareNameWithAliases(ie.name, ie.aliases)}" middleware ${ie.relation} "${ie.toMiddleware}" middleware cannot be overridden by "${getMiddlewareNameWithAliases(re, oe)}" middleware ${le.relation} "${le.toMiddleware}" middleware.`);
ee.splice(ne, 1);
}
}
for (const _ of ue) ie.add(_);
}
ee.push(le);
},
clone: () => cloneTo(constructStack()),
use: _ => {
_.applyToStack(re);
},
remove: ne => {
if ("string" == typeof ne) return (ne => {
let re = false;
const filterCb = _ => {
const ee = getAllAliases(_.name, _.aliases);
if (ee.includes(ne)) {
re = true;
for (const _ of ee) ie.delete(_);
return false;
}
return true;
};
_ = _.filter(filterCb);
ee = ee.filter(filterCb);
return re;
})(ne); else return (ne => {
let re = false;
const filterCb = _ => {
if (_.middleware === ne) {
re = true;
for (const ee of getAllAliases(_.name, _.aliases)) ie.delete(ee);
return false;
}
return true;
};
_ = _.filter(filterCb);
ee = ee.filter(filterCb);
return re;
})(ne);
},
removeByTag: ne => {
let re = false;
const filterCb = _ => {
const {tags: ee, name: se, aliases: oe} = _;
if (ee && ee.includes(ne)) {
const _ = getAllAliases(se, oe);
for (const ee of _) ie.delete(ee);
re = true;
return false;
}
return true;
};
_ = _.filter(filterCb);
ee = ee.filter(filterCb);
return re;
},
concat: _ => {
var ee, ie;
const re = cloneTo(constructStack());
re.use(_);
re.identifyOnResolve(ne || re.identifyOnResolve() || (null != (ie = null == (ee = _.identifyOnResolve) ? void 0 : ee.call(_)) ? ie : false));
return re;
},
applyToStack: cloneTo,
identify: () => getMiddlewareList(true).map((_ => {
var ee;
const ne = null != (ee = _.step) ? ee : _.relation + " " + _.toMiddleware;
return getMiddlewareNameWithAliases(_.name, _.aliases) + " - " + ne;
})),
identifyOnResolve(_) {
if ("boolean" == typeof _) ne = _;
return ne;
},
resolve: (_, ee) => {
for (const ne of getMiddlewareList().map((_ => _.middleware)).reverse()) _ = ne(_, ee);
if (ne) console.log(re.identify());
return _;
}
};
return re;
}, stepWeights = {
initialize: 5,
serialize: 4,
build: 3,
finalizeRequest: 2,
deserialize: 1
}, priorityWeights = {
high: 3,
normal: 2,
low: 1
}, Client = class {
constructor(_) {
this.middlewareStack = constructStack();
this.config = _;
}
send(_, ee, ne) {
const ie = "function" != typeof ee ? ee : void 0, re = "function" == typeof ee ? ee : ne, se = _.resolveMiddleware(this.middlewareStack, this.config, ie);
if (re) se(_).then((_ => re(null, _.output)), (_ => re(_))).catch((() => {})); else return se(_).then((_ => _.output));
}
destroy() {
if (this.config.requestHandler.destroy) this.config.requestHandler.destroy();
}
}, alphabetByEncoding = {}, alphabetByValue = new Array(64);
for (let _ = 0, ee = "A".charCodeAt(0), ne = "Z".charCodeAt(0); _ + ee <= ne; _++) {
const ne = String.fromCharCode(_ + ee);
alphabetByEncoding[ne] = _;
alphabetByValue[_] = ne;
}
for (let _ = 0, ee = "a".charCodeAt(0), ne = "z".charCodeAt(0); _ + ee <= ne; _++) {
const ne = String.fromCharCode(_ + ee), ie = _ + 26;
alphabetByEncoding[ne] = ie;
alphabetByValue[ie] = ne;
}
for (let _ = 0; _ < 10; _++) {
alphabetByEncoding[_.toString(10)] = _ + 52;
const ee = _.toString(10), ne = _ + 52;
alphabetByEncoding[ee] = ne;
alphabetByValue[ne] = ee;
}
alphabetByEncoding["+"] = 62;
alphabetByValue[62] = "+";
alphabetByEncoding["/"] = 63;
alphabetByValue[63] = "/";
var bitsPerLetter = 6, bitsPerByte = 8, maxLetterValue = 63, fromBase64 = _ => {
let ee = _.length / 4 * 3;
if ("==" === _.slice(-2)) ee -= 2; else if ("=" === _.slice(-1)) ee--;
const ne = new ArrayBuffer(ee), ie = new DataView(ne);
for (let ee = 0; ee < _.length; ee += 4) {
let ne = 0, re = 0;
for (let ie = ee, se = ee + 3; ie <= se; ie++) if ("=" !== _[ie]) {
if (!(_[ie] in alphabetByEncoding)) throw new TypeError(`Invalid character ${_[ie]} in base64 string.`);
ne |= alphabetByEncoding[_[ie]] << (se - ie) * bitsPerLetter;
re += bitsPerLetter;
} else ne >>= bitsPerLetter;
const se = ee / 4 * 3;
ne >>= re % bitsPerByte;
const oe = Math.floor(re / bitsPerByte);
for (let _ = 0; _ < oe; _++) {
const ee = (oe - _ - 1) * bitsPerByte;
ie.setUint8(se + _, (ne & 255 << ee) >> ee);
}
}
return new Uint8Array(ne);
}, fromUtf8 = _ => (new TextEncoder).encode(_), toUint8Array = _ => {
if ("string" == typeof _) return fromUtf8(_);
if (ArrayBuffer.isView(_)) return new Uint8Array(_.buffer, _.byteOffset, _.byteLength / Uint8Array.BYTES_PER_ELEMENT); else return new Uint8Array(_);
}, toUtf8 = _ => {
if ("string" == typeof _) return _;
if ("object" != typeof _ || "number" != typeof _.byteOffset || "number" != typeof _.byteLength) throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");
return new TextDecoder("utf-8").decode(_);
};
function toBase64(_) {
let ee;
if ("string" == typeof _) ee = fromUtf8(_); else ee = _;
const ne = "object" == typeof ee && "number" == typeof ee.length, ie = "object" == typeof ee && "number" == typeof ee.byteOffset && "number" == typeof ee.byteLength;
if (!ne && !ie) throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");
let re = "";
for (let _ = 0; _ < ee.length; _ += 3) {
let ne = 0, ie = 0;
for (let re = _, se = Math.min(_ + 3, ee.length); re < se; re++) {
ne |= ee[re] << (se - re - 1) * bitsPerByte;
ie += bitsPerByte;
}
const se = Math.ceil(ie / bitsPerLetter);
ne <<= se * bitsPerLetter - ie;
for (let _ = 1; _ <= se; _++) {
const ee = (se - _) * bitsPerLetter;
re += alphabetByValue[(ne & maxLetterValue << ee) >> ee];
}
re += "==".slice(0, 4 - se);
}
return re;
}
function transformToString(_, ee = "utf-8") {
if ("base64" === ee) return toBase64(_); else return toUtf8(_);
}
function transformFromString(_, ee) {
if ("base64" === ee) return Uint8ArrayBlobAdapter.mutate(fromBase64(_)); else return Uint8ArrayBlobAdapter.mutate(fromUtf8(_));
}
var Uint8ArrayBlobAdapter = class _Uint8ArrayBlobAdapter extends Uint8Array {
static fromString(_, ee = "utf-8") {
switch (typeof _) {
case "string":
return transformFromString(_, ee);
default:
throw new Error(`Unsupported conversion from ${typeof _} to Uint8ArrayBlobAdapter.`);
}
}
static mutate(_) {
Object.setPrototypeOf(_, _Uint8ArrayBlobAdapter.prototype);
return _;
}
transformToString(_ = "utf-8") {
return transformToString(this, _);
}
}, getAwsChunkedEncodingStream = (_, ee) => {
const {base64Encoder: ne, bodyLengthChecker: ie, checksumAlgorithmFn: re, checksumLocationName: se, streamHasher: oe} = ee, le = void 0 !== ne && void 0 !== ie && void 0 !== re && void 0 !== se && void 0 !== oe, ue = le ? oe(re, _) : void 0, de = _.getReader();
return new ReadableStream({
async pull(_) {
const {value: ee, done: re} = await de.read();
if (re) {
_.enqueue("0\r\n");
if (le) {
const ee = ne(await ue);
_.enqueue(`${se}:${ee}\r\n`);
_.enqueue("\r\n");
}
_.close();
} else _.enqueue(`${(ie(ee) || 0).toString(16)}\r\n${ee}\r\n`);
}
});
}, escapeUri = _ => encodeURIComponent(_).replace(/[!'()*]/g, hexEncode), hexEncode = _ => `%${_.charCodeAt(0).toString(16).toUpperCase()}`;
function buildQueryString(_) {
const ee = [];
for (let ne of Object.keys(_).sort()) {
const ie = _[ne];
ne = escapeUri(ne);
if (Array.isArray(ie)) for (let _ = 0, re = ie.length; _ < re; _++) ee.push(`${ne}=${escapeUri(ie[_])}`); else {
let _ = ne;
if (ie || "string" == typeof ie) _ += `=${escapeUri(ie)}`;
ee.push(_);
}
}
return ee.join("&");
}
function requestTimeout(_ = 0) {
return new Promise(((ee, ne) => {
if (_) setTimeout((() => {
const ee = new Error(`Request did not complete within ${_} ms`);
ee.name = "TimeoutError";
ne(ee);
}), _);
}));
}
var keepAliveSupport = {
supported: Boolean("undefined" != typeof Request && "keepalive" in new Request("https://[::1]"))
}, FetchHttpHandler = class _FetchHttpHandler {
static create(_) {
if ("function" == typeof (null == _ ? void 0 : _.handle)) return _; else return new _FetchHttpHandler(_);
}
constructor(_) {
if ("function" == typeof _) this.configProvider = _().then((_ => _ || {})); else {
this.config = null != _ ? _ : {};
this.configProvider = Promise.resolve(this.config);
}
}
destroy() {}
async handle(_, {abortSignal: ee} = {}) {
var ne, ie;
if (!this.config) this.config = await this.configProvider;
const re = this.config.requestTimeout, se = true === this.config.keepAlive;
if (null == ee ? void 0 : ee.aborted) {
const _ = new Error("Request aborted");
_.name = "AbortError";
return Promise.reject(_);
}
let oe = _.path;
const le = buildQueryString(_.query || {});
if (le) oe += `?${le}`;
if (_.fragment) oe += `#${_.fragment}`;
let ue = "";
if (null != _.username || null != _.password) ue = `${null != (ne = _.username) ? ne : ""}:${null != (ie = _.password) ? ie : ""}@`;
const {port: de, method: fe} = _, he = `${_.protocol}//${ue}${_.hostname}${de ? `:${de}` : ""}${oe}`, pe = {
body: "GET" === fe || "HEAD" === fe ? void 0 : _.body,
headers: new Headers(_.headers),
method: fe
};
if ("undefined" != typeof AbortController) pe["signal"] = ee;
if (keepAliveSupport.supported) pe["keepalive"] = se;
const ge = new Request(he, pe), me = [ fetch(ge).then((_ => {
const ee = _.headers, ne = {};
for (const _ of ee.entries()) ne[_[0]] = _[1];
if (!(null != _.body)) return _.blob().then((ee => ({
response: new HttpResponse({
headers: ne,
reason: _.statusText,
statusCode: _.status,
body: ee
})
}))); else return {
response: new HttpResponse({
headers: ne,
reason: _.statusText,
statusCode: _.status,
body: _.body
})
};
})), requestTimeout(re) ];
if (ee) me.push(new Promise(((_, ne) => {
ee.onabort = () => {
const _ = new Error("Request aborted");
_.name = "AbortError";
ne(_);
};
})));
return Promise.race(me);
}
updateHttpClientConfig(_, ee) {
this.config = void 0;
this.configProvider = this.configProvider.then((ne => {
ne[_] = ee;
return ne;
}));
}
httpHandlerConfigs() {
var _;
return null != (_ = this.config) ? _ : {};
}
}, streamCollector = _ => {
if ("function" == typeof Blob && _ instanceof Blob) return collectBlob(_); else return collectStream(_);
};
async function collectBlob(_) {
const ee = await readToBase64(_), ne = fromBase64(ee);
return new Uint8Array(ne);
}
async function collectStream(_) {
let ee = new Uint8Array(0);
const ne = _.getReader();
let ie = false;
for (;!ie; ) {
const {done: _, value: re} = await ne.read();
if (re) {
const _ = ee;
ee = new Uint8Array(_.length + re.length);
ee.set(_);
ee.set(re, _.length);
}
ie = _;
}
return ee;
}
function readToBase64(_) {
return new Promise(((ee, ne) => {
const ie = new FileReader;
ie.onloadend = () => {
var _;
if (2 !== ie.readyState) return ne(new Error("Reader aborted too early"));
const re = null != (_ = ie.result) ? _ : "", se = re.indexOf(","), oe = se > -1 ? se + 1 : re.length;
ee(re.substring(oe));
};
ie.onabort = () => ne(new Error("Read aborted"));
ie.onerror = () => ne(ie.error);
ie.readAsDataURL(_);
}));
}
var SHORT_TO_HEX = {}, HEX_TO_SHORT = {};
for (let _ = 0; _ < 256; _++) {
let ee = _.toString(16).toLowerCase();
if (1 === ee.length) ee = `0${ee}`;
SHORT_TO_HEX[_] = ee;
HEX_TO_SHORT[ee] = _;
}
function fromHex(_) {
if (_.length % 2 != 0) throw new Error("Hex encoded strings must have an even number length");
const ee = new Uint8Array(_.length / 2);
for (let ne = 0; ne < _.length; ne += 2) {
const ie = _.slice(ne, ne + 2).toLowerCase();
if (ie in HEX_TO_SHORT) ee[ne / 2] = HEX_TO_SHORT[ie]; else throw new Error(`Cannot decode unrecognized sequence ${ie} as hexadecimal`);
}
return ee;
}
function toHex(_) {
let ee = "";
for (let ne = 0; ne < _.byteLength; ne++) ee += SHORT_TO_HEX[_[ne]];
return ee;
}
var ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed.", sdkStreamMixin = _ => {
var ee, ne;
if (!isBlobInstance(_) && !isReadableStreamInstance(_)) {
const ie = (null == (ne = null == (ee = null == _ ? void 0 : _.__proto__) ? void 0 : ee.constructor) ? void 0 : ne.name) || _;
throw new Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${ie}`);
}
let ie = false;
const transformToByteArray = async () => {
if (ie) throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED);
ie = true;
return await streamCollector(_);
};
return Object.assign(_, {
transformToByteArray,
transformToString: async _ => {
const ee = await transformToByteArray();
if ("base64" === _) return toBase64(ee); else if ("hex" === _) return toHex(ee); else if (void 0 === _ || "utf8" === _ || "utf-8" === _) return toUtf8(ee); else if ("function" == typeof TextDecoder) return new TextDecoder(_).decode(ee); else throw new Error("TextDecoder is not available, please make sure polyfill is provided.");
},
transformToWebStream: () => {
if (ie) throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED);
ie = true;
if (isBlobInstance(_)) return (_ => {
if ("function" != typeof _.stream) throw new Error("Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.\nIf you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body");
return _.stream();
})(_); else if (isReadableStreamInstance(_)) return _; else throw new Error(`Cannot transform payload to web stream, got ${_}`);
}
});
}, isBlobInstance = _ => "function" == typeof Blob && _ instanceof Blob, isReadableStreamInstance = _ => "function" == typeof ReadableStream && _ instanceof ReadableStream, collectBody = async (_ = new Uint8Array, ee) => {
if (_ instanceof Uint8Array) return Uint8ArrayBlobAdapter.mutate(_);
if (!_) return Uint8ArrayBlobAdapter.mutate(new Uint8Array);
const ne = ee.streamCollector(_);
return Uint8ArrayBlobAdapter.mutate(await ne);
}, Command = class {
constructor() {
this.middlewareStack = constructStack();
}
static classBuilder() {
return new ClassBuilder;
}
resolveMiddlewareWithContext(_, ee, ne, {middlewareFn: ie, clientName: re, commandName: se, inputFilterSensitiveLog: oe, outputFilterSensitiveLog: le, smithyContext: ue, additionalContext: de, CommandCtor: fe}) {
for (const re of ie.bind(this)(fe, _, ee, ne)) this.middlewareStack.use(re);
const he = _.concat(this.middlewareStack), {logger: pe} = ee, ge = {
logger: pe,
clientName: re,
commandName: se,
inputFilterSensitiveLog: oe,
outputFilterSensitiveLog: le,
[SMITHY_CONTEXT_KEY]: {
...ue
},
...de
}, {requestHandler: me} = ee;
return he.resolve((_ => me.handle(_.request, ne || {})), ge);
}
}, ClassBuilder = class {
constructor() {
this._init = () => {};
this._ep = {};
this._middlewareFn = () => [];
this._commandName = "";
this._clientName = "";
this._additionalContext = {};
this._smithyContext = {};
this._inputFilterSensitiveLog = _ => _;
this._outputFilterSensitiveLog = _ => _;
this._serializer = null;
this._deserializer = null;
}
init(_) {
this._init = _;
}
ep(_) {
this._ep = _;
return this;
}
m(_) {
this._middlewareFn = _;
return this;
}
s(_, ee, ne = {}) {
this._smithyContext = {
service: _,
operation: ee,
...ne
};
return this;
}
c(_ = {}) {
this._additionalContext = _;
return this;
}
n(_, ee) {
this._clientName = _;
this._commandName = ee;
return this;
}
f(_ = (_ => _), ee = (_ => _)) {
this._inputFilterSensitiveLog = _;
this._outputFilterSensitiveLog = ee;
return this;
}
ser(_) {
this._serializer = _;
return this;
}
de(_) {
this._deserializer = _;
return this;
}
build() {
const _ = this;
let ee;
return ee = class extends Command {
static getEndpointParameterInstructions() {
return _._ep;
}
constructor(...[ee]) {
super();
this.serialize = _._serializer;
this.deserialize = _._deserializer;
this.input = null != ee ? ee : {};
_._init(this);
}
resolveMiddleware(ne, ie, re) {
return this.resolveMiddlewareWithContext(ne, ie, re, {
CommandCtor: ee,
middlewareFn: _._middlewareFn,
clientName: _._clientName,
commandName: _._commandName,
inputFilterSensitiveLog: _._inputFilterSensitiveLog,
outputFilterSensitiveLog: _._outputFilterSensitiveLog,
smithyContext: _._smithyContext,
additionalContext: _._additionalContext
});
}
};
}
}, SENSITIVE_STRING = "***SensitiveInformation***", createAggregatedClient = (_, ee) => {
for (const ne of Object.keys(_)) {
const ie = _[ne], methodImpl = async function(_, ee, ne) {
const re = new ie(_);
if ("function" == typeof ee) this.send(re, ee); else if ("function" == typeof ne) {
if ("object" != typeof ee) throw new Error("Expected http options but got " + typeof ee);
this.send(re, ee || {}, ne);
} else return this.send(re, ee);
}, re = (ne[0].toLowerCase() + ne.slice(1)).replace(/Command$/, "");
ee.prototype[re] = methodImpl;
}
}, parseBoolean = _ => {
switch (_) {
case "true":
return true;
case "false":
return false;
default:
throw new Error(`Unable to parse boolean value "${_}"`);
}
}, expectNumber = _ => {
if (null != _) {
if ("string" == typeof _) {
const ee = parseFloat(_);
if (!Number.isNaN(ee)) {
if (String(ee) !== String(_)) logger.warn(stackTraceWarning(`Expected number but observed string: ${_}`));
return ee;
}
}
if ("number" == typeof _) return _;
throw new TypeError(`Expected number, got ${typeof _}: ${_}`);
}
}, MAX_FLOAT = Math.ceil(2 ** 127 * (2 - 2 ** -23)), expectFloat32 = _ => {
const ee = expectNumber(_);
if (void 0 !== ee && !Number.isNaN(ee) && ee !== 1 / 0 && ee !== -1 / 0) if (Math.abs(ee) > MAX_FLOAT) throw new TypeError(`Expected 32-bit float, got ${_}`);
return ee;
}, expectLong = _ => {
if (null != _) {
if (Number.isInteger(_) && !Number.isNaN(_)) return _;
throw new TypeError(`Expected integer, got ${typeof _}: ${_}`);
}
}, expectInt32 = _ => expectSizedInt(_, 32), expectShort = _ => expectSizedInt(_, 16), expectByte = _ => expectSizedInt(_, 8), expectSizedInt = (_, ee) => {
const ne = expectLong(_);
if (void 0 !== ne && castInt(ne, ee) !== ne) throw new TypeError(`Expected ${ee}-bit integer, got ${_}`);
return ne;
}, castInt = (_, ee) => {
switch (ee) {
case 32:
return Int32Array.of(_)[0];
case 16:
return Int16Array.of(_)[0];
case 8:
return Int8Array.of(_)[0];
}
}, expectNonNull = (_, ee) => {
if (null == _) {
if (ee) throw new TypeError(`Expected a non-null value for ${ee}`);
throw new TypeError("Expected a non-null value");
}
return _;
}, expectObject = _ => {
if (null == _) return;
if ("object" == typeof _ && !Array.isArray(_)) return _;
const ee = Array.isArray(_) ? "array" : typeof _;
throw new TypeError(`Expected object, got ${ee}: ${_}`);
}, expectString = _ => {
if (null != _) {
if ("string" == typeof _) return _;
if ([ "boolean", "number", "bigint" ].includes(typeof _)) {
logger.warn(stackTraceWarning(`Expected string, got ${typeof _}: ${_}`));
return String(_);
}
throw new TypeError(`Expected string, got ${typeof _}: ${_}`);
}
}, expectUnion = _ => {
if (null == _) return;
const ee = expectObject(_), ne = Object.entries(ee).filter((([, _]) => null != _)).map((([_]) => _));
if (0 === ne.length) throw new TypeError("Unions must have exactly one non-null member. None were found.");
if (ne.length > 1) throw new TypeError(`Unions must have exactly one non-null member. Keys ${ne} were not null.`);
return ee;
}, strictParseFloat32 = _ => {
if ("string" == typeof _) return expectFloat32(parseNumber2(_)); else return expectFloat32(_);
}, NUMBER_REGEX = /(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g, parseNumber2 = _ => {
const ee = _.match(NUMBER_REGEX);
if (null === ee || ee[0].length !== _.length) throw new TypeError("Expected real number, got implicit NaN");
return parseFloat(_);
}, strictParseLong = _ => {
if ("string" == typeof _) return expectLong(parseNumber2(_)); else return expectLong(_);
}, strictParseInt32 = _ => {
if ("string" == typeof _) return expectInt32(parseNumber2(_)); else return expectInt32(_);
}, strictParseShort = _ => {
if ("string" == typeof _) return expectShort(parseNumber2(_)); else return expectShort(_);
}, strictParseByte = _ => {
if ("string" == typeof _) return expectByte(parseNumber2(_)); else return expectByte(_);
}, stackTraceWarning = _ => String(new TypeError(_).stack || _).split("\n").slice(0, 5).filter((_ => !_.includes("stackTraceWarning"))).join("\n"), logger = {
warn: console.warn
}, DAYS = [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], MONTHS = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];
function dateToUtcString(_) {
const ee = _.getUTCFullYear(), ne = _.getUTCMonth(), ie = _.getUTCDay(), re = _.getUTCDate(), se = _.getUTCHours(), oe = _.getUTCMinutes(), le = _.getUTCSeconds(), ue = re < 10 ? `0${re}` : `${re}`, de = se < 10 ? `0${se}` : `${se}`, fe = oe < 10 ? `0${oe}` : `${oe}`, he = le < 10 ? `0${le}` : `${le}`;
return `${DAYS[ie]}, ${ue} ${MONTHS[ne]} ${ee} ${de}:${fe}:${he} GMT`;
}
var RFC3339 = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/), RFC3339_WITH_OFFSET = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/), parseRfc3339DateTimeWithOffset = _ => {
if (null == _) return;
if ("string" != typeof _) throw new TypeError("RFC-3339 date-times must be expressed as strings");
const ee = RFC3339_WITH_OFFSET.exec(_);
if (!ee) throw new TypeError("Invalid RFC-3339 date-time value");
const [ne, ie, re, se, oe, le, ue, de, fe] = ee, he = strictParseShort(stripLeadingZeroes(ie)), pe = parseDateValue(re, "month", 1, 12), ge = parseDateValue(se, "day", 1, 31), me = buildDate(he, pe, ge, {
hours: oe,
minutes: le,
seconds: ue,
fractionalMilliseconds: de
});
if ("Z" != fe.toUpperCase()) me.setTime(me.getTime() - parseOffsetToMilliseconds(fe));
return me;
}, IMF_FIXDATE = new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/), RFC_850_DATE = new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/), ASC_TIME = new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/), parseRfc7231DateTime = _ => {
if (null == _) return;
if ("string" != typeof _) throw new TypeError("RFC-7231 date-times must be expressed as strings");
let ee = IMF_FIXDATE.exec(_);
if (ee) {
const [_, ne, ie, re, se, oe, le, ue] = ee;
return buildDate(strictParseShort(stripLeadingZeroes(re)), parseMonthByShortName(ie), parseDateValue(ne, "day", 1, 31), {
hours: se,
minutes: oe,
seconds: le,
fractionalMilliseconds: ue
});
}
ee = RFC_850_DATE.exec(_);
if (ee) {
const [_, ne, ie, re, se, oe, le, ue] = ee;
return adjustRfc850Year(buildDate(parseTwoDigitYear(re), parseMonthByShortName(ie), parseDateValue(ne, "day", 1, 31), {
hours: se,
minutes: oe,
seconds: le,
fractionalMilliseconds: ue
}));
}
ee = ASC_TIME.exec(_);
if (ee) {
const [_, ne, ie, re, se, oe, le, ue] = ee;
return buildDate(strictParseShort(stripLeadingZeroes(ue)), parseMonthByShortName(ne), parseDateValue(ie.trimLeft(), "day", 1, 31), {
hours: re,
minutes: se,
seconds: oe,
fractionalMilliseconds: le
});
}
throw new TypeError("Invalid RFC-7231 date-time value");
}, buildDate = (_, ee, ne, ie) => {
const re = ee - 1;
validateDayOfMonth(_, re, ne);
return new Date(Date.UTC(_, re, ne, parseDateValue(ie.hours, "hour", 0, 23), parseDateValue(ie.minutes, "minute", 0, 59), parseDateValue(ie.seconds, "seconds", 0, 60), parseMilliseconds(ie.fractionalMilliseconds)));
}, parseTwoDigitYear = _ => {
const ee = (new Date).getUTCFullYear(), ne = 100 * Math.floor(ee / 100) + strictParseShort(stripLeadingZeroes(_));
if (ne < ee) return ne + 100; else return ne;
}, FIFTY_YEARS_IN_MILLIS = 15768e8, adjustRfc850Year = _ => {
if (_.getTime() - (new Date).getTime() > FIFTY_YEARS_IN_MILLIS) return new Date(Date.UTC(_.getUTCFullYear() - 100, _.getUTCMonth(), _.getUTCDate(), _.getUTCHours(), _.getUTCMinutes(), _.getUTCSeconds(), _.getUTCMilliseconds())); else return _;
}, parseMonthByShortName = _ => {
const ee = MONTHS.indexOf(_);
if (ee < 0) throw new TypeError(`Invalid month: ${_}`);
return ee + 1;
}, DAYS_IN_MONTH = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ], validateDayOfMonth = (_, ee, ne) => {
let ie = DAYS_IN_MONTH[ee];
if (1 === ee && isLeapYear(_)) ie = 29;
if (ne > ie) throw new TypeError(`Invalid day for ${MONTHS[ee]} in ${_}: ${ne}`);
}, isLeapYear = _ => _ % 4 == 0 && (_ % 100 != 0 || _ % 400 == 0), parseDateValue = (_, ee, ne, ie) => {
const re = strictParseByte(stripLeadingZeroes(_));
if (re < ne || re > ie) throw new TypeError(`${ee} must be between ${ne} and ${ie}, inclusive`);
return re;
}, parseMilliseconds = _ => {
if (null == _) return 0; else return 1e3 * strictParseFloat32("0." + _);
}, parseOffsetToMilliseconds = _ => {
const ee = _[0];
let ne = 1;
if ("+" == ee) ne = 1; else if ("-" == ee) ne = -1; else throw new TypeError(`Offset direction, ${ee}, must be "+" or "-"`);
return ne * (60 * Number(_.substring(1, 3)) + Number(_.substring(4, 6))) * 60 * 1e3;
}, stripLeadingZeroes = _ => {
let ee = 0;
for (;ee < _.length - 1 && "0" === _.charAt(ee); ) ee++;
if (0 === ee) return _; else return _.slice(ee);
}, ServiceException = class _ServiceException extends Error {
constructor(_) {
super(_.message);
Object.setPrototypeOf(this, _ServiceException.prototype);
this.name = _.name;
this.$fault = _.$fault;
this.$metadata = _.$metadata;
}
}, decorateServiceException = (_, ee = {}) => {
Object.entries(ee).filter((([, _]) => void 0 !== _)).forEach((([ee, ne]) => {
if (null == _[ee] || "" === _[ee]) _[ee] = ne;
}));
const ne = _.message || _.Message || "UnknownError";
_.message = ne;
delete _.Message;
return _;
}, throwDefaultError = ({output: _, parsedBody: ee, exceptionCtor: ne, errorCode: ie}) => {
const re = deserializeMetadata(_), se = re.httpStatusCode ? re.httpStatusCode + "" : void 0, oe = new ne({
name: (null == ee ? void 0 : ee.code) || (null == ee ? void 0 : ee.Code) || ie || se || "UnknownError",
$fault: "client",
$metadata: re
});
throw decorateServiceException(oe, ee);
}, withBaseException = _ => ({output: ee, parsedBody: ne, errorCode: ie}) => {
throwDefaultError({
output: ee,
parsedBody: ne,
exceptionCtor: _,
errorCode: ie
});
}, deserializeMetadata = _ => {
var ee, ne;
return {
httpStatusCode: _.statusCode,
requestId: null != (ne = null != (ee = _.headers["x-amzn-requestid"]) ? ee : _.headers["x-amzn-request-id"]) ? ne : _.headers["x-amz-request-id"],
extendedRequestId: _.headers["x-amz-id-2"],
cfId: _.headers["x-amz-cf-id"]
};
}, loadConfigsForDefaultMode = _ => {
switch (_) {
case "standard":
return {
retryMode: "standard",
connectionTimeout: 3100
};
case "in-region":
return {
retryMode: "standard",
connectionTimeout: 1100
};
case "cross-region":
return {
retryMode: "standard",
connectionTimeout: 3100
};
case "mobile":
return {
retryMode: "standard",
connectionTimeout: 3e4
};
default:
return {};
}
}, getChecksumConfiguration2 = _ => {
const ee = [];
for (const ne in AlgorithmId) {
const ie = AlgorithmId[ne];
if (void 0 !== _[ie]) ee.push({
algorithmId: () => ie,
checksumConstructor: () => _[ie]
});
}
return {
_checksumAlgorithms: ee,
addChecksumAlgorithm(_) {
this._checksumAlgorithms.push(_);
},
checksumAlgorithms() {
return this._checksumAlgorithms;
}
};
}, resolveChecksumRuntimeConfig2 = _ => {
const ee = {};
_.checksumAlgorithms().forEach((_ => {
ee[_.algorithmId()] = _.checksumConstructor();
}));
return ee;
}, getRetryConfiguration = _ => {
let ee = _.retryStrategy;
return {
setRetryStrategy(_) {
ee = _;
},
retryStrategy: () => ee
};
}, resolveRetryRuntimeConfig = _ => {
const ee = {};
ee.retryStrategy = _.retryStrategy();
return ee;
}, getDefaultExtensionConfiguration = _ => ({
...getChecksumConfiguration2(_),
...getRetryConfiguration(_)
}), resolveDefaultRuntimeConfig = _ => ({
...resolveChecksumRuntimeConfig2(_),
...resolveRetryRuntimeConfig(_)
});
function extendedEncodeURIComponent(_) {
return encodeURIComponent(_).replace(/[!'()*]/g, (function(_) {
return "%" + _.charCodeAt(0).toString(16).toUpperCase();
}));
}
var getArrayIfSingleItem = _ => Array.isArray(_) ? _ : [ _ ], getValueFromTextNode = _ => {
const ee = "#text";
for (const ne in _) if (_.hasOwnProperty(ne) && void 0 !== _[ne][ee]) _[ne] = _[ne][ee]; else if ("object" == typeof _[ne] && null !== _[ne]) _[ne] = getValueFromTextNode(_[ne]);
return _;
}, StringWrapper = function() {
const _ = Object.getPrototypeOf(this).constructor, ee = new (Function.bind.apply(String, [ null, ...arguments ]));
Object.setPrototypeOf(ee, _.prototype);
return ee;
};
StringWrapper.prototype = Object.create(String.prototype, {
constructor: {
value: StringWrapper,
enumerable: false,
writable: true,
configurable: true
}
});
Object.setPrototypeOf(StringWrapper, String);
function map(_, ee, ne) {
let ie, re, se;
if ("undefined" == typeof ee && "undefined" == typeof ne) {
ie = {};
se = _;
} else {
ie = _;
if ("function" == typeof ee) {
re = ee;
se = ne;
return mapWithFilter(ie, re, se);
} else se = ee;
}
for (const _ of Object.keys(se)) if (Array.isArray(se[_])) applyInstruction(ie, null, se, _); else ie[_] = se[_];
return ie;
}
var mapWithFilter = (_, ee, ne) => map(_, Object.entries(ne).reduce(((_, [ne, ie]) => {
if (Array.isArray(ie)) _[ne] = ie; else if ("function" == typeof ie) _[ne] = [ ee, ie() ]; else _[ne] = [ ee, ie ];
return _;
}), {})), applyInstruction = (_, ee, ne, ie) => {
if (null !== ee) {
let re = ne[ie];
if ("function" == typeof re) re = [ , re ];
const [se = nonNullish, oe = pass, le = ie] = re;
if ("function" == typeof se && se(ee[le]) || "function" != typeof se && !!se) _[ie] = oe(ee[le]);
return;
}
let [re, se] = ne[ie];
if ("function" == typeof se) {
let ee;
const ne = void 0 === re && null != (ee = se()), oe = "function" == typeof re && !!re(void 0) || "function" != typeof re && !!re;
if (ne) _[ie] = ee; else if (oe) _[ie] = se();
} else {
const ee = void 0 === re && null != se, ne = "function" == typeof re && !!re(se) || "function" != typeof re && !!re;
if (ee || ne) _[ie] = se;
}
}, nonNullish = _ => null != _, pass = _ => _, resolvedPath = (_, ee, ne, ie, re, se) => {
if (null != ee && void 0 !== ee[ne]) {
const ee = ie();
if (ee.length <= 0) throw new Error("Empty value provided for input HTTP label: " + ne + ".");
_ = _.replace(re, se ? ee.split("/").map((_ => extendedEncodeURIComponent(_))).join("/") : extendedEncodeURIComponent(ee));
} else throw new Error("No value provided for input HTTP label: " + ne + ".");
return _;
}, CONTENT_LENGTH_HEADER = "content-length";
function checkContentLengthHeader() {
return (_, ee) => async ne => {
var ie;
const {request: re} = ne;
if (HttpRequest.isInstance(re)) if (!(CONTENT_LENGTH_HEADER in re.headers)) {
const _ = "Are you using a Stream of unknown length as the Body of a PutObject request? Consider using Upload instead from @aws-sdk/lib-storage.";
if ("function" == typeof (null == (ie = null == ee ? void 0 : ee.logger) ? void 0 : ie.warn) && !(ee.logger instanceof NoOpLogger)) ee.logger.warn(_); else console.warn(_);
}
return _({
...ne
});
};
}
var checkContentLengthHeaderMiddlewareOptions = {
step: "finalizeRequest",
tags: [ "CHECK_CONTENT_LENGTH_HEADER" ],
name: "getCheckContentLengthHeaderPlugin",
override: true
}, getCheckContentLengthHeaderPlugin = _ => ({
applyToStack: _ => {
_.add(checkContentLengthHeader(), checkContentLengthHeaderMiddlewareOptions);
}
}), regionRedirectEndpointMiddleware = _ => (ee, ne) => async ie => {
const re = await _.region(), se = _.region;
if (ne.__s3RegionRedirect) _.region = async () => {
_.region = se;
return ne.__s3RegionRedirect;
};
const oe = await ee(ie);
if (ne.__s3RegionRedirect) if (re !== await _.region()) throw new Error("Region was not restored following S3 region redirect.");
return oe;
}, regionRedirectEndpointMiddlewareOptions = {
tags: [ "REGION_REDIRECT", "S3" ],
name: "regionRedirectEndpointMiddleware",
override: true,
relation: "before",
toMiddleware: "endpointV2Middleware"
};
function regionRedirectMiddleware(_) {
return (ee, ne) => async ie => {
var re, se;
try {
return await ee(ie);
} catch (oe) {
if (_.followRegionRedirects && 301 === (null == (re = null == oe ? void 0 : oe.$metadata) ? void 0 : re.httpStatusCode)) {
try {
const ee = oe.$response.headers["x-amz-bucket-region"];
null == (se = ne.logger) || se.debug(`Redirecting from ${await _.region()} to ${ee}`);
ne.__s3RegionRedirect = ee;
} catch (_) {
throw new Error("Region redirect failed: " + _);
}
return ee(ie);
} else throw oe;
}
};
}
var regionRedirectMiddlewareOptions = {
step: "initialize",
tags: [ "REGION_REDIRECT", "S3" ],
name: "regionRedirectMiddleware",
override: true
}, getRegionRedirectMiddlewarePlugin = _ => ({
applyToStack: ee => {
ee.add(regionRedirectMiddleware(_), regionRedirectMiddlewareOptions);
ee.addRelativeTo(regionRedirectEndpointMiddleware(_), regionRedirectEndpointMiddlewareOptions);
}
}), s3ExpiresMiddleware = _ => (_, ee) => async ne => {
var ie;
const re = await _(ne), {response: se} = re;
if (HttpResponse.isInstance(se)) if (se.headers.expires) {
se.headers.expiresstring = se.headers.expires;
try {
parseRfc7231DateTime(se.headers.expires);
} catch (_) {
null == (ie = ee.logger) || ie.warn(`AWS SDK Warning for ${ee.clientName}::${ee.commandName} response parsing (${se.headers.expires}): ${_}`);
delete se.headers.expires;
}
}
return re;
}, s3ExpiresMiddlewareOptions = {
tags: [ "S3" ],
name: "s3ExpiresMiddleware",
override: true,
relation: "after",
toMiddleware: "deserializerMiddleware"
}, getS3ExpiresMiddlewarePlugin = _ => ({
applyToStack: ee => {
ee.addRelativeTo(s3ExpiresMiddleware(_), s3ExpiresMiddlewareOptions);
}
}), S3ExpressIdentityCache = class _S3ExpressIdentityCache {
constructor(_ = {}) {
this.data = _;
this.lastPurgeTime = Date.now();
}
get(_) {
const ee = this.data[_];
if (ee) return ee;
}
set(_, ee) {
this.data[_] = ee;
return ee;
}
delete(_) {
delete this.data[_];
}
async purgeExpired() {
const _ = Date.now();
if (!(this.lastPurgeTime + _S3ExpressIdentityCache.EXPIRED_CREDENTIAL_PURGE_INTERVAL_MS > _)) for (const ee in this.data) {
const ne = this.data[ee];
if (!ne.isRefreshing) {
const ie = await ne.identity;
if (ie.expiration) if (ie.expiration.getTime() < _) delete this.data[ee];
}
}
}
};
S3ExpressIdentityCache.EXPIRED_CREDENTIAL_PURGE_INTERVAL_MS = 3e4;
var S3ExpressIdentityCacheEntry = class {
constructor(_, ee = false, ne = Date.now()) {
this._identity = _;
this.isRefreshing = ee;
this.accessed = ne;
}
get identity() {
this.accessed = Date.now();
return this._identity;
}
}, S3ExpressIdentityProviderImpl = class _S3ExpressIdentityProviderImpl {
constructor(_, ee = new S3ExpressIdentityCache) {
this.createSessionFn = _;
this.cache = ee;
}
async getS3ExpressIdentity(_, ee) {
const ne = ee.Bucket, {cache: ie} = this, re = ie.get(ne);
if (re) return re.identity.then((_ => {
var ee, se, oe, le;
if ((null != (se = null == (ee = _.expiration) ? void 0 : ee.getTime()) ? se : 0) < Date.now()) return ie.set(ne, new S3ExpressIdentityCacheEntry(this.getIdentity(ne))).identity;
if ((null != (le = null == (oe = _.expiration) ? void 0 : oe.getTime()) ? le : 0) < Date.now() + _S3ExpressIdentityProviderImpl.REFRESH_WINDOW_MS && !re.isRefreshing) {
re.isRefreshing = true;
this.getIdentity(ne).then((_ => {
ie.set(ne, new S3ExpressIdentityCacheEntry(Promise.resolve(_)));
}));
}
return _;
})); else return ie.set(ne, new S3ExpressIdentityCacheEntry(this.getIdentity(ne))).identity;
}
async getIdentity(_) {
var ee, ne;
await this.cache.purgeExpired().catch((_ => {
console.warn("Error while clearing expired entries in S3ExpressIdentityCache: \n" + _);
}));
const ie = await this.createSessionFn(_);
if (!(null == (ee = ie.Credentials) ? void 0 : ee.AccessKeyId) || !(null == (ne = ie.Credentials) ? void 0 : ne.SecretAccessKey)) throw new Error("s3#createSession response credential missing AccessKeyId or SecretAccessKey.");
return {
accessKeyId: ie.Credentials.AccessKeyId,
secretAccessKey: ie.Credentials.SecretAccessKey,
sessionToken: ie.Credentials.SessionToken,
expiration: ie.Credentials.Expiration ? new Date(ie.Credentials.Expiration) : void 0
};
}
};
S3ExpressIdentityProviderImpl.REFRESH_WINDOW_MS = 6e4;
var HEADER_VALUE_TYPE, getSmithyContext = _ => _[SMITHY_CONTEXT_KEY] || (_[SMITHY_CONTEXT_KEY] = {}), normalizeProvider = _ => {
if ("function" == typeof _) return _;
const ee = Promise.resolve(_);
return () => ee;
}, ALGORITHM_QUERY_PARAM = "X-Amz-Algorithm", CREDENTIAL_QUERY_PARAM = "X-Amz-Credential", AMZ_DATE_QUERY_PARAM = "X-Amz-Date", SIGNED_HEADERS_QUERY_PARAM = "X-Amz-SignedHeaders", EXPIRES_QUERY_PARAM = "X-Amz-Expires", SIGNATURE_QUERY_PARAM = "X-Amz-Signature", TOKEN_QUERY_PARAM = "X-Amz-Security-Token", AUTH_HEADER = "authorization", AMZ_DATE_HEADER = AMZ_DATE_QUERY_PARAM.toLowerCase(), DATE_HEADER = "date", GENERATED_HEADERS = [ AUTH_HEADER, AMZ_DATE_HEADER, DATE_HEADER ], SIGNATURE_HEADER = SIGNATURE_QUERY_PARAM.toLowerCase(), SHA256_HEADER = "x-amz-content-sha256", TOKEN_HEADER = TOKEN_QUERY_PARAM.toLowerCase(), ALWAYS_UNSIGNABLE_HEADERS = {
authorization: true,
"cache-control": true,
connection: true,
expect: true,
from: true,
"keep-alive": true,
"max-forwards": true,
pragma: true,
referer: true,
te: true,
trailer: true,
"transfer-encoding": true,
upgrade: true,
"user-agent": true,
"x-amzn-trace-id": true
}, PROXY_HEADER_PATTERN = /^proxy-/, SEC_HEADER_PATTERN = /^sec-/, ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256", EVENT_ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256-PAYLOAD", UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD", MAX_CACHE_SIZE = 50, KEY_TYPE_IDENTIFIER = "aws4_request", MAX_PRESIGNED_TTL = 604800, signingKeyCache = {}, cacheQueue = [], createScope = (_, ee, ne) => `${_}/${ee}/${ne}/${KEY_TYPE_IDENTIFIER}`, getSigningKey = async (_, ee, ne, ie, re) => {
const se = `${ne}:${ie}:${re}:${toHex(await hmac(_, ee.secretAccessKey, ee.accessKeyId))}:${ee.sessionToken}`;
if (se in signingKeyCache) return signingKeyCache[se];
cacheQueue.push(se);
for (;cacheQueue.length > MAX_CACHE_SIZE; ) delete signingKeyCache[cacheQueue.shift()];
let oe = `AWS4${ee.secretAccessKey}`;
for (const ee of [ ne, ie, re, KEY_TYPE_IDENTIFIER ]) oe = await hmac(_, oe, ee);
return signingKeyCache[se] = oe;
}, hmac = (_, ee, ne) => {
const ie = new _(ee);
ie.update(toUint8Array(ne));
return ie.digest();
}, getCanonicalHeaders = ({headers: _}, ee, ne) => {
const ie = {};
for (const re of Object.keys(_).sort()) {
if (null == _[re]) continue;
const se = re.toLowerCase();
if (se in ALWAYS_UNSIGNABLE_HEADERS || (null == ee ? void 0 : ee.has(se)) || PROXY_HEADER_PATTERN.test(se) || SEC_HEADER_PATTERN.test(se)) if (!ne || ne && !ne.has(se)) continue;
ie[se] = _[re].trim().replace(/\s+/g, " ");
}
return ie;
}, getCanonicalQuery = ({query: _ = {}}) => {
const ee = [], ne = {};
for (const ie of Object.keys(_).sort()) {
if (ie.toLowerCase() === SIGNATURE_HEADER) continue;
ee.push(ie);
const re = _[ie];
if ("string" == typeof re) ne[ie] = `${escapeUri(ie)}=${escapeUri(re)}`; else if (Array.isArray(re)) ne[ie] = re.slice(0).reduce(((_, ee) => _.concat([ `${escapeUri(ie)}=${escapeUri(ee)}` ])), []).sort().join("&");
}
return ee.map((_ => ne[_])).filter((_ => _)).join("&");
}, isArrayBuffer = _ => "function" == typeof ArrayBuffer && _ instanceof ArrayBuffer || "[object ArrayBuffer]" === Object.prototype.toString.call(_), getPayloadHash = async ({headers: _, body: ee}, ne) => {
for (const ee of Object.keys(_)) if (ee.toLowerCase() === SHA256_HEADER) return _[ee];
if (null == ee) return "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; else if ("string" == typeof ee || ArrayBuffer.isView(ee) || isArrayBuffer(ee)) {
const _ = new ne;
_.update(toUint8Array(ee));
return toHex(await _.digest());
}
return UNSIGNED_PAYLOAD;
}, HeaderFormatter = class {
format(_) {
const ee = [];
for (const ne of Object.keys(_)) {
const ie = fromUtf8(ne);
ee.push(Uint8Array.from([ ie.byteLength ]), ie, this.formatHeaderValue(_[ne]));
}
const ne = new Uint8Array(ee.reduce(((_, ee) => _ + ee.byteLength), 0));
let ie = 0;
for (const _ of ee) {
ne.set(_, ie);
ie += _.byteLength;
}
return ne;
}
formatHeaderValue(_) {
switch (_.type) {
case "boolean":
return Uint8Array.from([ _.value ? 0 : 1 ]);
case "byte":
return Uint8Array.from([ 2, _.value ]);
case "short":
const ee = new DataView(new ArrayBuffer(3));
ee.setUint8(0, 3);
ee.setInt16(1, _.value, false);
return new Uint8Array(ee.buffer);
case "integer":
const ne = new DataView(new ArrayBuffer(5));
ne.setUint8(0, 4);
ne.setInt32(1, _.value, false);
return new Uint8Array(ne.buffer);
case "long":
const ie = new Uint8Array(9);
ie[0] = 5;
ie.set(_.value.bytes, 1);
return ie;
case "binary":
const re = new DataView(new ArrayBuffer(3 + _.value.byteLength));
re.setUint8(0, 6);
re.setUint16(1, _.value.byteLength, false);
const se = new Uint8Array(re.buffer);
se.set(_.value, 3);
return se;
case "string":
const oe = fromUtf8(_.value), le = new DataView(new ArrayBuffer(3 + oe.byteLength));
le.setUint8(0, 7);
le.setUint16(1, oe.byteLength, false);
const ue = new Uint8Array(le.buffer);
ue.set(oe, 3);
return ue;
case "timestamp":
const de = new Uint8Array(9);
de[0] = 8;
de.set(Int64.fromNumber(_.value.valueOf()).bytes, 1);
return de;
case "uuid":
if (!UUID_PATTERN.test(_.value)) throw new Error(`Invalid UUID received: ${_.value}`);
const fe = new Uint8Array(17);
fe[0] = 9;
fe.set(fromHex(_.value.replace(/\-/g, "")), 1);
return fe;
}
}
};
(function(_) {
_[_["boolTrue"] = 0] = "boolTrue";
_[_["boolFalse"] = 1] = "boolFalse";
_[_["byte"] = 2] = "byte";
_[_["short"] = 3] = "short";
_[_["integer"] = 4] = "integer";
_[_["long"] = 5] = "long";
_[_["byteArray"] = 6] = "byteArray";
_[_["string"] = 7] = "string";
_[_["timestamp"] = 8] = "timestamp";
_[_["uuid"] = 9] = "uuid";
})(HEADER_VALUE_TYPE || (HEADER_VALUE_TYPE = {}));
var UUID_PATTERN = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/, Int64 = class _Int64 {
constructor(_) {
this.bytes = _;
if (8 !== _.byteLength) throw new Error("Int64 buffers must be exactly 8 bytes");
}
static fromNumber(_) {
if (_ > 0x8000000000000000 || _ < -0x8000000000000000) throw new Error(`${_} is too large (or, if negative, too small) to represent as an Int64`);
const ee = new Uint8Array(8);
for (let ne = 7, ie = Math.abs(Math.round(_)); ne > -1 && ie > 0; ne--, ie /= 256) ee[ne] = ie;
if (_ < 0) negate(ee);
return new _Int64(ee);
}
valueOf() {
const _ = this.bytes.slice(0), ee = 128 & _[0];
if (ee) negate(_);
return parseInt(toHex(_), 16) * (ee ? -1 : 1);
}
toString() {
return String(this.valueOf());
}
};
function negate(_) {
for (let ee = 0; ee < 8; ee++) _[ee] ^= 255;
for (let ee = 7; ee > -1; ee--) {
_[ee]++;
if (0 !== _[ee]) break;
}
}
var SelectorType, hasHeader = (_, ee) => {
_ = _.toLowerCase();
for (const ne of Object.keys(ee)) if (_ === ne.toLowerCase()) return true;
return false;
}, cloneRequest = ({headers: _, query: ee, ...ne}) => ({
...ne,
headers: {
..._
},
query: ee ? cloneQuery2(ee) : void 0
}), cloneQuery2 = _ => Object.keys(_).reduce(((ee, ne) => {
const ie = _[ne];
return {
...ee,
[ne]: Array.isArray(ie) ? [ ...ie ] : ie
};
}), {}), moveHeadersToQuery = (_, ee = {}) => {
var ne;
const {headers: ie, query: re = {}} = "function" == typeof _.clone ? _.clone() : cloneRequest(_);
for (const _ of Object.keys(ie)) {
const se = _.toLowerCase();
if ("x-amz-" === se.slice(0, 6) && !(null == (ne = ee.unhoistableHeaders) ? void 0 : ne.has(se))) {
re[_] = ie[_];
delete ie[_];
}
}
return {
..._,
headers: ie,
query: re
};
}, prepareRequest = _ => {
_ = "function" == typeof _.clone ? _.clone() : cloneRequest(_);
for (const ee of Object.keys(_.headers)) if (GENERATED_HEADERS.indexOf(ee.toLowerCase()) > -1) delete _.headers[ee];
return _;
}, iso8601 = _ => toDate(_).toISOString().replace(/\.\d{3}Z$/, "Z"), toDate = _ => {
if ("number" == typeof _) return new Date(1e3 * _);
if ("string" == typeof _) if (Number(_)) return new Date(1e3 * Number(_)); else return new Date(_);
return _;
}, SignatureV4 = class {
constructor({applyChecksum: _, credentials: ee, region: ne, service: ie, sha256: re, uriEscapePath: se = true}) {
this.headerFormatter = new HeaderFormatter;
this.service = ie;
this.sha256 = re;
this.uriEscapePath = se;
this.applyChecksum = "boolean" == typeof _ ? _ : true;
this.regionProvider = normalizeProvider(ne);
this.credentialProvider = normalizeProvider(ee);
}
async presign(_, ee = {}) {
const {signingDate: ne = new Date, expiresIn: ie = 3600, unsignableHeaders: re, unhoistableHeaders: se, signableHeaders: oe, signingRegion: le, signingService: ue} = ee, de = await this.credentialProvider();
this.validateResolvedCredentials(de);
const fe = null != le ? le : await this.regionProvider(), {longDate: he, shortDate: pe} = formatDate(ne);
if (ie > MAX_PRESIGNED_TTL) return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future");
const ge = createScope(pe, fe, null != ue ? ue : this.service), me = moveHeadersToQuery(prepareRequest(_), {
unhoistableHeaders: se
});
if (de.sessionToken) me.query[TOKEN_QUERY_PARAM] = de.sessionToken;
me.query[ALGORITHM_QUERY_PARAM] = ALGORITHM_IDENTIFIER;
me.query[CREDENTIAL_QUERY_PARAM] = `${de.accessKeyId}/${ge}`;
me.query[AMZ_DATE_QUERY_PARAM] = he;
me.query[EXPIRES_QUERY_PARAM] = ie.toString(10);
const ye = getCanonicalHeaders(me, re, oe);
me.query[SIGNED_HEADERS_QUERY_PARAM] = getCanonicalHeaderList(ye);
me.query[SIGNATURE_QUERY_PARAM] = await this.getSignature(he, ge, this.getSigningKey(de, fe, pe, ue), this.createCanonicalRequest(me, ye, await getPayloadHash(_, this.sha256)));
return me;
}
async sign(_, ee) {
if ("string" == typeof _) return this.signString(_, ee); else if (_.headers && _.payload) return this.signEvent(_, ee); else if (_.message) return this.signMessage(_, ee); else return this.signRequest(_, ee);
}
async signEvent({headers: _, payload: ee}, {signingDate: ne = new Date, priorSignature: ie, signingRegion: re, signingService: se}) {
const oe = null != re ? re : await this.regionProvider(), {shortDate: le, longDate: ue} = formatDate(ne), de = createScope(le, oe, null != se ? se : this.service), fe = await getPayloadHash({
headers: {},
body: ee
}, this.sha256), he = new this.sha256;
he.update(_);
const pe = toHex(await he.digest()), ge = [ EVENT_ALGORITHM_IDENTIFIER, ue, de, ie, pe, fe ].join("\n");
return this.signString(ge, {
signingDate: ne,
signingRegion: oe,
signingService: se
});
}
async signMessage(_, {signingDate: ee = new Date, signingRegion: ne, signingService: ie}) {
return this.signEvent({
headers: this.headerFormatter.format(_.message.headers),
payload: _.message.body
}, {
signingDate: ee,
signingRegion: ne,
signingService: ie,
priorSignature: _.priorSignature
}).then((ee => ({
message: _.message,
signature: ee
})));
}
async signString(_, {signingDate: ee = new Date, signingRegion: ne, signingService: ie} = {}) {
const re = await this.credentialProvider();
this.validateResolvedCredentials(re);
const se = null != ne ? ne : await this.regionProvider(), {shortDate: oe} = formatDate(ee), le = new this.sha256(await this.getSigningKey(re, se, oe, ie));
le.update(toUint8Array(_));
return toHex(await le.digest());
}
async signRequest(_, {signingDate: ee = new Date, signableHeaders: ne, unsignableHeaders: ie, signingRegion: re, signingService: se} = {}) {
const oe = await this.credentialProvider();
this.validateResolvedCredentials(oe);
const le = null != re ? re : await this.regionProvider(), ue = prepareRequest(_), {longDate: de, shortDate: fe} = formatDate(ee), he = createScope(fe, le, null != se ? se : this.service);
ue.headers[AMZ_DATE_HEADER] = de;
if (oe.sessionToken) ue.headers[TOKEN_HEADER] = oe.sessionToken;
const pe = await getPayloadHash(ue, this.sha256);
if (!hasHeader(SHA256_HEADER, ue.headers) && this.applyChecksum) ue.headers[SHA256_HEADER] = pe;
const ge = getCanonicalHeaders(ue, ie, ne), me = await this.getSignature(de, he, this.getSigningKey(oe, le, fe, se), this.createCanonicalRequest(ue, ge, pe));
ue.headers[AUTH_HEADER] = `${ALGORITHM_IDENTIFIER} Credential=${oe.accessKeyId}/${he}, SignedHeaders=${getCanonicalHeaderList(ge)}, Signature=${me}`;
return ue;
}
createCanonicalRequest(_, ee, ne) {
const ie = Object.keys(ee).sort();
return `${_.method}\n${this.getCanonicalPath(_)}\n${getCanonicalQuery(_)}\n${ie.map((_ => `${_}:${ee[_]}`)).join("\n")}\n\n${ie.join(";")}\n${ne}`;
}
async createStringToSign(_, ee, ne) {
const ie = new this.sha256;
ie.update(toUint8Array(ne));
const re = await ie.digest();
return `${ALGORITHM_IDENTIFIER}\n${_}\n${ee}\n${toHex(re)}`;
}
getCanonicalPath({path: _}) {
if (this.uriEscapePath) {
const ee = [];
for (const ne of _.split("/")) if (0 !== (null == ne ? void 0 : ne.length)) if ("." !== ne) if (".." === ne) ee.pop(); else ee.push(ne);
const ne = `${(null == _ ? void 0 : _.startsWith("/")) ? "/" : ""}${ee.join("/")}${ee.length > 0 && (null == _ ? void 0 : _.endsWith("/")) ? "/" : ""}`;
return escapeUri(ne).replace(/%2F/g, "/");
}
return _;
}
async getSignature(_, ee, ne, ie) {
const re = await this.createStringToSign(_, ee, ie), se = new this.sha256(await ne);
se.update(toUint8Array(re));
return toHex(await se.digest());
}
getSigningKey(_, ee, ne, ie) {
return getSigningKey(this.sha256, _, ne, ee, ie || this.service);
}
validateResolvedCredentials(_) {
if ("object" != typeof _ || "string" != typeof _.accessKeyId || "string" != typeof _.secretAccessKey) throw new Error("Resolved credential object is not valid");
}
}, formatDate = _ => {
const ee = iso8601(_).replace(/[\-:]/g, "");
return {
longDate: ee,
shortDate: ee.slice(0, 8)
};
}, getCanonicalHeaderList = _ => Object.keys(_).sort().join(";");
(function(_) {
_["ENV"] = "env";
_["CONFIG"] = "shared config entry";
})(SelectorType || (SelectorType = {}));
var S3_EXPRESS_BUCKET_TYPE = "Directory", S3_EXPRESS_BACKEND = "S3Express", S3_EXPRESS_AUTH_SCHEME = "sigv4-s3express", SESSION_TOKEN_QUERY_PARAM = "X-Amz-S3session-Token", SESSION_TOKEN_HEADER = SESSION_TOKEN_QUERY_PARAM.toLowerCase(), SignatureV4S3Express = class extends SignatureV4 {
async signWithCredentials(_, ee, ne) {
const ie = getCredentialsWithoutSessionToken(ee);
_.headers[SESSION_TOKEN_HEADER] = ee.sessionToken;
setSingleOverride(this, ie);
return this.signRequest(_, null != ne ? ne : {});
}
async presignWithCredentials(_, ee, ne) {
var ie;
const re = getCredentialsWithoutSessionToken(ee);
delete _.headers[SESSION_TOKEN_HEADER];
_.headers[SESSION_TOKEN_QUERY_PARAM] = ee.sessionToken;
_.query = null != (ie = _.query) ? ie : {};
_.query[SESSION_TOKEN_QUERY_PARAM] = ee.sessionToken;
setSingleOverride(this, re);
return this.presign(_, ne);
}
};
function getCredentialsWithoutSessionToken(_) {
return {
accessKeyId: _.accessKeyId,
secretAccessKey: _.secretAccessKey,
expiration: _.expiration
};
}
function setSingleOverride(_, ee) {
const ne = setTimeout((() => {
throw new Error("SignatureV4S3Express credential override was created but not called.");
}), 10), ie = _.credentialProvider;
_.credentialProvider = () => {
clearTimeout(ne);
_.credentialProvider = ie;
return Promise.resolve(ee);
};
}
var s3ExpressMiddleware = _ => (ee, ne) => async ie => {
var re, se, oe, le, ue;
if (ne.endpointV2) {
const ee = ne.endpointV2, de = (null == (oe = null == (se = null == (re = ee.properties) ? void 0 : re.authSchemes) ? void 0 : se[0]) ? void 0 : oe.name) === S3_EXPRESS_AUTH_SCHEME;
if ((null == (le = ee.properties) ? void 0 : le.backend) === S3_EXPRESS_BACKEND || (null == (ue = ee.properties) ? void 0 : ue.bucketType) === S3_EXPRESS_BUCKET_TYPE) ne.isS3ExpressBucket = true;
if (de) {
const ee = ie.input.Bucket;
if (ee) {
const re = await _.s3ExpressIdentityProvider.getS3ExpressIdentity(await _.credentials(), {
Bucket: ee
});
ne.s3ExpressIdentity = re;
if (HttpRequest.isInstance(ie.request) && re.sessionToken) ie.request.headers[SESSION_TOKEN_HEADER] = re.sessionToken;
}
}
}
return ee(ie);
}, s3ExpressMiddlewareOptions = {
name: "s3ExpressMiddleware",
step: "build",
tags: [ "S3", "S3_EXPRESS" ],
override: true
}, getS3ExpressPlugin = _ => ({
applyToStack: ee => {
ee.add(s3ExpressMiddleware(_), s3ExpressMiddlewareOptions);
}
}), resolveS3Config = (_, {session: ee}) => {
var ne, ie, re, se, oe, le;
const [ue, de] = ee;
return {
..._,
forcePathStyle: null != (ne = _.forcePathStyle) ? ne : false,
useAccelerateEndpoint: null != (ie = _.useAccelerateEndpoint) ? ie : false,
disableMultiregionAccessPoints: null != (re = _.disableMultiregionAccessPoints) ? re : false,
followRegionRedirects: null != (se = _.followRegionRedirects) ? se : false,
s3ExpressIdentityProvider: null != (oe = _.s3ExpressIdentityProvider) ? oe : new S3ExpressIdentityProviderImpl((async _ => ue().send(new de({
Bucket: _,
SessionMode: "ReadWrite"
})))),
bucketEndpoint: null != (le = _.bucketEndpoint) ? le : false
};
}, throw200ExceptionsMiddleware = _ => ee => async ne => {
const ie = await ee(ne), {response: re} = ie;
if (!HttpResponse.isInstance(re)) return ie;
const {statusCode: se, body: oe} = re;
if (se < 200 || se >= 300) return ie;
const le = await collectBody2(oe, _), ue = await collectBodyString(le, _);
if (0 === le.length) {
const _ = new Error("S3 aborted request");
_.name = "InternalError";
throw _;
}
if (ue && ue.match("")) re.statusCode = 400;
re.body = le;
return ie;
}, collectBody2 = (_ = new Uint8Array, ee) => {
if (_ instanceof Uint8Array) return Promise.resolve(_); else return ee.streamCollector(_) || Promise.resolve(new Uint8Array);
}, collectBodyString = (_, ee) => collectBody2(_, ee).then((_ => ee.utf8Encoder(_))), throw200ExceptionsMiddlewareOptions = {
relation: "after",
toMiddleware: "deserializerMiddleware",
tags: [ "THROW_200_EXCEPTIONS", "S3" ],
name: "throw200ExceptionsMiddleware",
override: true
}, getThrow200ExceptionsPlugin = _ => ({
applyToStack: ee => {
ee.addRelativeTo(throw200ExceptionsMiddleware(_), throw200ExceptionsMiddlewareOptions);
}
}), validate3 = _ => "string" == typeof _ && 0 === _.indexOf("arn:") && _.split(":").length >= 6;
function bucketEndpointMiddleware(_) {
return (ee, ne) => async ie => {
var re, se, oe, le;
if (_.bucketEndpoint) {
const _ = ne.endpointV2;
if (_) {
const ee = ie.input.Bucket;
if ("string" == typeof ee) try {
const ne = new URL(ee);
_.url = ne;
} catch (_) {
const ie = `@aws-sdk/middleware-sdk-s3: bucketEndpoint=true was set but Bucket=${ee} could not be parsed as URL.`;
if ("NoOpLogger" === (null == (se = null == (re = ne.logger) ? void 0 : re.constructor) ? void 0 : se.name)) console.warn(ie); else null == (le = null == (oe = ne.logger) ? void 0 : oe.warn) || le.call(oe, ie);
throw _;
}
}
}
return ee(ie);
};
}
var bucketEndpointMiddlewareOptions = {
name: "bucketEndpointMiddleware",
override: true,
relation: "after",
toMiddleware: "endpointV2Middleware"
};
function validateBucketNameMiddleware({bucketEndpoint: _}) {
return ee => async ne => {
const {input: {Bucket: ie}} = ne;
if (!_ && "string" == typeof ie && !validate3(ie) && ie.indexOf("/") >= 0) {
const _ = new Error(`Bucket name shouldn't contain '/', received '${ie}'`);
_.name = "InvalidBucketName";
throw _;
}
return ee({
...ne
});
};
}
var validateBucketNameMiddlewareOptions = {
step: "initialize",
tags: [ "VALIDATE_BUCKET_NAME" ],
name: "validateBucketNameMiddleware",
override: true
}, getValidateBucketNamePlugin = _ => ({
applyToStack: ee => {
ee.add(validateBucketNameMiddleware(_), validateBucketNameMiddlewareOptions);
ee.addRelativeTo(bucketEndpointMiddleware(_), bucketEndpointMiddlewareOptions);
}
}), memoize = (_, ee, ne) => {
let ie, re, se, oe = false;
const coalesceProvider = async () => {
if (!re) re = _();
try {
ie = await re;
se = true;
oe = false;
} finally {
re = void 0;
}
return ie;
};
if (void 0 === ee) return async _ => {
if (!se || (null == _ ? void 0 : _.forceRefresh)) ie = await coalesceProvider();
return ie;
}; else return async _ => {
if (!se || (null == _ ? void 0 : _.forceRefresh)) ie = await coalesceProvider();
if (oe) return ie;
if (ne && !ne(ie)) {
oe = true;
return ie;
}
if (ee(ie)) {
await coalesceProvider();
return ie;
}
return ie;
};
}, CREDENTIAL_EXPIRE_WINDOW = 3e5, resolveAwsAuthConfig = _ => {
const ee = _.credentials ? normalizeCredentialProvider(_.credentials) : _.credentialDefaultProvider(Object.assign({}, _, {
parentClientConfig: _
})), {signingEscapePath: ne = true, systemClockOffset: ie = _.systemClockOffset || 0, sha256: re} = _;
let se;
if (_.signer) se = normalizeProvider(_.signer); else if (_.regionInfoProvider) se = () => normalizeProvider(_.region)().then((async ee => [ await _.regionInfoProvider(ee, {
useFipsEndpoint: await _.useFipsEndpoint(),
useDualstackEndpoint: await _.useDualstackEndpoint()
}) || {}, ee ])).then((([ie, se]) => {
const {signingRegion: oe, signingService: le} = ie;
_.signingRegion = _.signingRegion || oe || se;
_.signingName = _.signingName || le || _.serviceId;
const ue = {
..._,
credentials: ee,
region: _.signingRegion,
service: _.signingName,
sha256: re,
uriEscapePath: ne
};
return new (_.signerConstructor || SignatureV4)(ue);
})); else se = async ie => {
const se = "sigv4a" === (null == (ie = Object.assign({}, {
name: "sigv4",
signingName: _.signingName || _.defaultSigningName,
signingRegion: await normalizeProvider(_.region)(),
properties: {}
}, ie)) ? void 0 : ie.name), oe = ie.signingRegion, le = ie.signingName;
let ue;
if (se) ue = _.signingRegion || oe; else {
_.signingRegion = _.signingRegion || oe;
ue = _.signingRegion;
}
_.signingName = _.signingName || le || _.serviceId;
const de = {
..._,
credentials: ee,
region: ue,
service: _.signingName,
sha256: re,
uriEscapePath: ne
};
return new (_.signerConstructor || SignatureV4)(de);
};
return {
..._,
systemClockOffset: ie,
signingEscapePath: ne,
credentials: ee,
signer: se
};
}, normalizeCredentialProvider = _ => {
if ("function" == typeof _) return memoize(_, (_ => void 0 !== _.expiration && _.expiration.getTime() - Date.now() < CREDENTIAL_EXPIRE_WINDOW), (_ => void 0 !== _.expiration)); else return normalizeProvider(_);
}, getSkewCorrectedDate = _ => new Date(Date.now() + _), isClockSkewed = (_, ee) => Math.abs(getSkewCorrectedDate(ee).getTime() - _) >= 3e5, getUpdatedSystemClockOffset = (_, ee) => {
const ne = Date.parse(_);
if (isClockSkewed(ne, ee)) return ne - Date.now(); else return ee;
}, awsAuthMiddleware = _ => (ee, ne) => async function(ie) {
var re, se, oe, le, ue, de, fe;
if (!HttpRequest.isInstance(ie.request)) return ee(ie);
let he, pe;
const ge = null == (oe = null == (se = null == (re = ne.endpointV2) ? void 0 : re.properties) ? void 0 : se.authSchemes) ? void 0 : oe[0], me = null == (de = null == (ue = null == (le = ne.endpointV2) ? void 0 : le.properties) ? void 0 : ue.authSchemes) ? void 0 : de[1];
if ("sigv4a" === (null == ge ? void 0 : ge.name) && me) {
pe = await _.signer(he = ge);
const ee = pe;
if (!(() => {
var _;
if ("function" == typeof (null == ee ? void 0 : ee.getSigv4aSigner)) {
if ("node" !== (null == (_ = null == ee ? void 0 : ee.signerOptions) ? void 0 : _.runtime)) return false;
try {
ee.getSigv4aSigner();
return true;
} catch (_) {}
}
return false;
})()) pe = await _.signer(he = me);
} else pe = await _.signer(he = ge);
let ye;
const ve = "sigv4a" === (null == he ? void 0 : he.name) ? null == (fe = null == he ? void 0 : he.signingRegionSet) ? void 0 : fe.join(",") : void 0, Se = {
signingDate: getSkewCorrectedDate(_.systemClockOffset),
signingRegion: ve || ne["signing_region"],
signingService: ne["signing_service"]
};
if (ne.s3ExpressIdentity) {
const _ = pe;
ye = await _.signWithCredentials(ie.request, ne.s3ExpressIdentity, Se);
if (ye.headers["X-Amz-Security-Token"] || ye.headers["x-amz-security-token"]) throw new Error("X-Amz-Security-Token must not be set for s3-express requests.");
} else ye = await pe.sign(ie.request, Se);
const Ee = await ee({
...ie,
request: ye
}).catch((ee => {
var ne;
const ie = null != (ne = ee.ServerTime) ? ne : getDateHeader(ee.$response);
if (ie) _.systemClockOffset = getUpdatedSystemClockOffset(ie, _.systemClockOffset);
throw ee;
})), Ce = getDateHeader(Ee.response);
if (Ce) _.systemClockOffset = getUpdatedSystemClockOffset(Ce, _.systemClockOffset);
return Ee;
}, getDateHeader = _ => {
var ee, ne, ie;
return HttpResponse.isInstance(_) ? null != (ie = null == (ee = _.headers) ? void 0 : ee.date) ? ie : null == (ne = _.headers) ? void 0 : ne.Date : void 0;
}, awsAuthMiddlewareOptions = {
name: "awsAuthMiddleware",
tags: [ "SIGNATURE", "AWSAUTH" ],
relation: "after",
toMiddleware: "retryMiddleware",
override: true
}, getAwsAuthPlugin = _ => ({
applyToStack: ee => {
ee.addRelativeTo(awsAuthMiddleware(_), awsAuthMiddlewareOptions);
}
});
function resolveUserAgentConfig(_) {
return {
..._,
customUserAgent: "string" == typeof _.customUserAgent ? [ [ _.customUserAgent ] ] : _.customUserAgent
};
}
var IP_V4_REGEX = new RegExp("^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$"), isIpAddress = _ => IP_V4_REGEX.test(_) || _.startsWith("[") && _.endsWith("]"), VALID_HOST_LABEL_REGEX = new RegExp("^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$"), isValidHostLabel = (_, ee = false) => {
if (!ee) return VALID_HOST_LABEL_REGEX.test(_);
const ne = _.split(".");
for (const _ of ne) if (!isValidHostLabel(_)) return false;
return true;
}, customEndpointFunctions = {}, debugId = "endpoints";
function toDebugString(_) {
if ("object" != typeof _ || null == _) return _;
if ("ref" in _) return `$${toDebugString(_.ref)}`;
if ("fn" in _) return `${_.fn}(${(_.argv || []).map(toDebugString).join(", ")})`; else return JSON.stringify(_, null, 2);
}
var EndpointError = class extends Error {
constructor(_) {
super(_);
this.name = "EndpointError";
}
}, booleanEquals = (_, ee) => _ === ee, getAttrPathList = _ => {
const ee = _.split("."), ne = [];
for (const ie of ee) {
const ee = ie.indexOf("[");
if (-1 !== ee) {
if (ie.indexOf("]") !== ie.length - 1) throw new EndpointError(`Path: '${_}' does not end with ']'`);
const re = ie.slice(ee + 1, -1);
if (Number.isNaN(parseInt(re))) throw new EndpointError(`Invalid array index: '${re}' in path: '${_}'`);
if (0 !== ee) ne.push(ie.slice(0, ee));
ne.push(re);
} else ne.push(ie);
}
return ne;
}, getAttr = (_, ee) => getAttrPathList(ee).reduce(((ne, ie) => {
if ("object" != typeof ne) throw new EndpointError(`Index '${ie}' in '${ee}' not found in '${JSON.stringify(_)}'`); else if (Array.isArray(ne)) return ne[parseInt(ie)];
return ne[ie];
}), _), isSet = _ => null != _, not = _ => !_, DEFAULT_PORTS = {
[EndpointURLScheme.HTTP]: 80,
[EndpointURLScheme.HTTPS]: 443
}, parseURL = _ => {
const ee = (() => {
try {
if (_ instanceof URL) return _;
if ("object" == typeof _ && "hostname" in _) {
const {hostname: ee, port: ne, protocol: ie = "", path: re = "", query: se = {}} = _, oe = new URL(`${ie}//${ee}${ne ? `:${ne}` : ""}${re}`);
oe.search = Object.entries(se).map((([_, ee]) => `${_}=${ee}`)).join("&");
return oe;
}
return new URL(_);
} catch (_) {
return null;
}
})();
if (!ee) {
console.error(`Unable to parse ${JSON.stringify(_)} as a whatwg URL.`);
return null;
}
const ne = ee.href, {host: ie, hostname: re, pathname: se, protocol: oe, search: le} = ee;
if (le) return null;
const ue = oe.slice(0, -1);
if (!Object.values(EndpointURLScheme).includes(ue)) return null;
const de = isIpAddress(re);
return {
scheme: ue,
authority: `${ie}${ne.includes(`${ie}:${DEFAULT_PORTS[ue]}`) || "string" == typeof _ && _.includes(`${ie}:${DEFAULT_PORTS[ue]}`) ? `:${DEFAULT_PORTS[ue]}` : ""}`,
path: se,
normalizedPath: se.endsWith("/") ? se : `${se}/`,
isIp: de
};
}, stringEquals = (_, ee) => _ === ee, substring = (_, ee, ne, ie) => {
if (ee >= ne || _.length < ne) return null;
if (!ie) return _.substring(ee, ne); else return _.substring(_.length - ne, _.length - ee);
}, uriEncode = _ => encodeURIComponent(_).replace(/[!*'()]/g, (_ => `%${_.charCodeAt(0).toString(16).toUpperCase()}`)), endpointFunctions = {
booleanEquals,
getAttr,
isSet,
isValidHostLabel,
not,
parseURL,
stringEquals,
substring,
uriEncode
}, evaluateTemplate = (_, ee) => {
const ne = [], ie = {
...ee.endpointParams,
...ee.referenceRecord
};
let re = 0;
for (;re < _.length; ) {
const ee = _.indexOf("{", re);
if (-1 === ee) {
ne.push(_.slice(re));
break;
}
ne.push(_.slice(re, ee));
const se = _.indexOf("}", ee);
if (-1 === se) {
ne.push(_.slice(ee));
break;
}
if ("{" === _[ee + 1] && "}" === _[se + 1]) {
ne.push(_.slice(ee + 1, se));
re = se + 2;
}
const oe = _.substring(ee + 1, se);
if (oe.includes("#")) {
const [_, ee] = oe.split("#");
ne.push(getAttr(ie[_], ee));
} else ne.push(ie[oe]);
re = se + 1;
}
return ne.join("");
}, getReferenceValue = ({ref: _}, ee) => ({
...ee.endpointParams,
...ee.referenceRecord
}[_]), evaluateExpression = (_, ee, ne) => {
if ("string" == typeof _) return evaluateTemplate(_, ne); else if (_["fn"]) return callFunction(_, ne); else if (_["ref"]) return getReferenceValue(_, ne);
throw new EndpointError(`'${ee}': ${String(_)} is not a string, function or reference.`);
}, callFunction = ({fn: _, argv: ee}, ne) => {
const ie = ee.map((_ => [ "boolean", "number" ].includes(typeof _) ? _ : evaluateExpression(_, "arg", ne))), re = _.split(".");
if (re[0] in customEndpointFunctions && null != re[1]) return customEndpointFunctions[re[0]][re[1]](...ie); else return endpointFunctions[_](...ie);
}, evaluateCondition = ({assign: _, ...ee}, ne) => {
var ie, re;
if (_ && _ in ne.referenceRecord) throw new EndpointError(`'${_}' is already defined in Reference Record.`);
const se = callFunction(ee, ne);
null == (re = null == (ie = ne.logger) ? void 0 : ie.debug) || re.call(ie, debugId, `evaluateCondition: ${toDebugString(ee)} = ${toDebugString(se)}`);
return {
result: "" === se ? true : !!se,
...null != _ && {
toAssign: {
name: _,
value: se
}
}
};
}, evaluateConditions = (_ = [], ee) => {
var ne, ie;
const re = {};
for (const se of _) {
const {result: _, toAssign: oe} = evaluateCondition(se, {
...ee,
referenceRecord: {
...ee.referenceRecord,
...re
}
});
if (!_) return {
result: _
};
if (oe) {
re[oe.name] = oe.value;
null == (ie = null == (ne = ee.logger) ? void 0 : ne.debug) || ie.call(ne, debugId, `assign: ${oe.name} := ${toDebugString(oe.value)}`);
}
}
return {
result: true,
referenceRecord: re
};
}, getEndpointHeaders = (_, ee) => Object.entries(_).reduce(((_, [ne, ie]) => ({
..._,
[ne]: ie.map((_ => {
const ie = evaluateExpression(_, "Header value entry", ee);
if ("string" != typeof ie) throw new EndpointError(`Header '${ne}' value '${ie}' is not a string`);
return ie;
}))
})), {}), getEndpointProperty = (_, ee) => {
if (Array.isArray(_)) return _.map((_ => getEndpointProperty(_, ee)));
switch (typeof _) {
case "string":
return evaluateTemplate(_, ee);
case "object":
if (null === _) throw new EndpointError(`Unexpected endpoint property: ${_}`);
return getEndpointProperties(_, ee);
case "boolean":
return _;
default:
throw new EndpointError("Unexpected endpoint property type: " + typeof _);
}
}, getEndpointProperties = (_, ee) => Object.entries(_).reduce(((_, [ne, ie]) => ({
..._,
[ne]: getEndpointProperty(ie, ee)
})), {}), getEndpointUrl = (_, ee) => {
const ne = evaluateExpression(_, "Endpoint URL", ee);
if ("string" == typeof ne) try {
return new URL(ne);
} catch (_) {
console.error(`Failed to construct URL with ${ne}`, _);
throw _;
}
throw new EndpointError("Endpoint URL must be a string, got " + typeof ne);
}, evaluateEndpointRule = (_, ee) => {
var ne, ie;
const {conditions: re, endpoint: se} = _, {result: oe, referenceRecord: le} = evaluateConditions(re, ee);
if (!oe) return;
const ue = {
...ee,
referenceRecord: {
...ee.referenceRecord,
...le
}
}, {url: de, properties: fe, headers: he} = se;
null == (ie = null == (ne = ee.logger) ? void 0 : ne.debug) || ie.call(ne, debugId, `Resolving endpoint from template: ${toDebugString(se)}`);
return {
...null != he && {
headers: getEndpointHeaders(he, ue)
},
...null != fe && {
properties: getEndpointProperties(fe, ue)
},
url: getEndpointUrl(de, ue)
};
}, evaluateErrorRule = (_, ee) => {
const {conditions: ne, error: ie} = _, {result: re, referenceRecord: se} = evaluateConditions(ne, ee);
if (re) throw new EndpointError(evaluateExpression(ie, "Error", {
...ee,
referenceRecord: {
...ee.referenceRecord,
...se
}
}));
}, evaluateTreeRule = (_, ee) => {
const {conditions: ne, rules: ie} = _, {result: re, referenceRecord: se} = evaluateConditions(ne, ee);
if (re) return evaluateRules(ie, {
...ee,
referenceRecord: {
...ee.referenceRecord,
...se
}
});
}, evaluateRules = (_, ee) => {
for (const ne of _) if ("endpoint" === ne.type) {
const _ = evaluateEndpointRule(ne, ee);
if (_) return _;
} else if ("error" === ne.type) evaluateErrorRule(ne, ee); else if ("tree" === ne.type) {
const _ = evaluateTreeRule(ne, ee);
if (_) return _;
} else throw new EndpointError(`Unknown endpoint rule: ${ne}`);
throw new EndpointError("Rules evaluation failed");
}, resolveEndpoint = (_, ee) => {
var ne, ie, re, se, oe, le;
const {endpointParams: ue, logger: de} = ee, {parameters: fe, rules: he} = _;
null == (ie = null == (ne = ee.logger) ? void 0 : ne.debug) || ie.call(ne, `${debugId} Initial EndpointParams: ${toDebugString(ue)}`);
const pe = Object.entries(fe).filter((([, _]) => null != _.default)).map((([_, ee]) => [ _, ee.default ]));
if (pe.length > 0) for (const [_, ee] of pe) ue[_] = null != (re = ue[_]) ? re : ee;
const ge = Object.entries(fe).filter((([, _]) => _.required)).map((([_]) => _));
for (const _ of ge) if (null == ue[_]) throw new EndpointError(`Missing required parameter: '${_}'`);
const me = evaluateRules(he, {
endpointParams: ue,
logger: de,
referenceRecord: {}
});
if (null == (se = ee.endpointParams) ? void 0 : se.Endpoint) try {
const _ = new URL(ee.endpointParams.Endpoint), {protocol: ne, port: ie} = _;
me.url.protocol = ne;
me.url.port = ie;
} catch (_) {}
null == (le = null == (oe = ee.logger) ? void 0 : oe.debug) || le.call(oe, `${debugId} Resolved endpoint: ${toDebugString(me)}`);
return me;
}, isVirtualHostableS3Bucket = (_, ee = false) => {
if (ee) {
for (const ee of _.split(".")) if (!isVirtualHostableS3Bucket(ee)) return false;
return true;
}
if (!isValidHostLabel(_)) return false;
if (_.length < 3 || _.length > 63) return false;
if (_ !== _.toLowerCase()) return false;
if (isIpAddress(_)) return false; else return true;
}, parseArn = _ => {
const ee = _.split(":");
if (ee.length < 6) return null;
const [ne, ie, re, se, oe, ...le] = ee;
if ("arn" !== ne || "" === ie || "" === re || "" === le[0]) return null; else return {
partition: ie,
service: re,
region: se,
accountId: oe,
resourceId: le[0].includes("/") ? le[0].split("/") : le
};
}, partitions_default = {
partitions: [ {
id: "aws",
outputs: {
dnsSuffix: "amazonaws.com",
dualStackDnsSuffix: "api.aws",
implicitGlobalRegion: "us-east-1",
name: "aws",
supportsDualStack: true,
supportsFIPS: true
},
regionRegex: "^(us|eu|ap|sa|ca|me|af|il)\\-\\w+\\-\\d+$",
regions: {
"af-south-1": {
description: "Africa (Cape Town)"
},
"ap-east-1": {
description: "Asia Pacific (Hong Kong)"
},
"ap-northeast-1": {
description: "Asia Pacific (Tokyo)"
},
"ap-northeast-2": {
description: "Asia Pacific (Seoul)"
},
"ap-northeast-3": {
description: "Asia Pacific (Osaka)"
},
"ap-south-1": {
description: "Asia Pacific (Mumbai)"
},
"ap-south-2": {
description: "Asia Pacific (Hyderabad)"
},
"ap-southeast-1": {
description: "Asia Pacific (Singapore)"
},
"ap-southeast-2": {
description: "Asia Pacific (Sydney)"
},
"ap-southeast-3": {
description: "Asia Pacific (Jakarta)"
},
"ap-southeast-4": {
description: "Asia Pacific (Melbourne)"
},
"aws-global": {
description: "AWS Standard global region"
},
"ca-central-1": {
description: "Canada (Central)"
},
"ca-west-1": {
description: "Canada West (Calgary)"
},
"eu-central-1": {
description: "Europe (Frankfurt)"
},
"eu-central-2": {
description: "Europe (Zurich)"
},
"eu-north-1": {
description: "Europe (Stockholm)"
},
"eu-south-1": {
description: "Europe (Milan)"
},
"eu-south-2": {
description: "Europe (Spain)"
},
"eu-west-1": {
description: "Europe (Ireland)"
},
"eu-west-2": {
description: "Europe (London)"
},
"eu-west-3": {
description: "Europe (Paris)"
},
"il-central-1": {
description: "Israel (Tel Aviv)"
},
"me-central-1": {
description: "Middle East (UAE)"
},
"me-south-1": {
description: "Middle East (Bahrain)"
},
"sa-east-1": {
description: "South America (Sao Paulo)"
},
"us-east-1": {
description: "US East (N. Virginia)"
},
"us-east-2": {
description: "US East (Ohio)"
},
"us-west-1": {
description: "US West (N. California)"
},
"us-west-2": {
description: "US West (Oregon)"
}
}
}, {
id: "aws-cn",
outputs: {
dnsSuffix: "amazonaws.com.cn",
dualStackDnsSuffix: "api.amazonwebservices.com.cn",
implicitGlobalRegion: "cn-northwest-1",
name: "aws-cn",
supportsDualStack: true,
supportsFIPS: true
},
regionRegex: "^cn\\-\\w+\\-\\d+$",
regions: {
"aws-cn-global": {
description: "AWS China global region"
},
"cn-north-1": {
description: "China (Beijing)"
},
"cn-northwest-1": {
description: "China (Ningxia)"
}
}
}, {
id: "aws-us-gov",
outputs: {
dnsSuffix: "amazonaws.com",
dualStackDnsSuffix: "api.aws",
implicitGlobalRegion: "us-gov-west-1",
name: "aws-us-gov",
supportsDualStack: true,
supportsFIPS: true
},
regionRegex: "^us\\-gov\\-\\w+\\-\\d+$",
regions: {
"aws-us-gov-global": {
description: "AWS GovCloud (US) global region"
},
"us-gov-east-1": {
description: "AWS GovCloud (US-East)"
},
"us-gov-west-1": {
description: "AWS GovCloud (US-West)"
}
}
}, {
id: "aws-iso",
outputs: {
dnsSuffix: "c2s.ic.gov",
dualStackDnsSuffix: "c2s.ic.gov",
implicitGlobalRegion: "us-iso-east-1",
name: "aws-iso",
supportsDualStack: false,
supportsFIPS: true
},
regionRegex: "^us\\-iso\\-\\w+\\-\\d+$",
regions: {
"aws-iso-global": {
description: "AWS ISO (US) global region"
},
"us-iso-east-1": {
description: "US ISO East"
},
"us-iso-west-1": {
description: "US ISO WEST"
}
}
}, {
id: "aws-iso-b",
outputs: {
dnsSuffix: "sc2s.sgov.gov",
dualStackDnsSuffix: "sc2s.sgov.gov",
implicitGlobalRegion: "us-isob-east-1",
name: "aws-iso-b",
supportsDualStack: false,
supportsFIPS: true
},
regionRegex: "^us\\-isob\\-\\w+\\-\\d+$",
regions: {
"aws-iso-b-global": {
description: "AWS ISOB (US) global region"
},
"us-isob-east-1": {
description: "US ISOB East (Ohio)"
}
}
}, {
id: "aws-iso-e",
outputs: {
dnsSuffix: "cloud.adc-e.uk",
dualStackDnsSuffix: "cloud.adc-e.uk",
implicitGlobalRegion: "eu-isoe-west-1",
name: "aws-iso-e",
supportsDualStack: false,
supportsFIPS: true
},
regionRegex: "^eu\\-isoe\\-\\w+\\-\\d+$",
regions: {}
}, {
id: "aws-iso-f",
outputs: {
dnsSuffix: "csp.hci.ic.gov",
dualStackDnsSuffix: "csp.hci.ic.gov",
implicitGlobalRegion: "us-isof-south-1",
name: "aws-iso-f",
supportsDualStack: false,
supportsFIPS: true
},
regionRegex: "^us\\-isof\\-\\w+\\-\\d+$",
regions: {}
} ],
version: "1.1"
}, selectedPartitionsInfo = partitions_default, selectedUserAgentPrefix = "", partition = _ => {
const {partitions: ee} = selectedPartitionsInfo;
for (const ne of ee) {
const {regions: ee, outputs: ie} = ne;
for (const [ne, re] of Object.entries(ee)) if (ne === _) return {
...ie,
...re
};
}
for (const ne of ee) {
const {regionRegex: ee, outputs: ie} = ne;
if (new RegExp(ee).test(_)) return {
...ie
};
}
const ne = ee.find((_ => "aws" === _.id));
if (!ne) throw new Error("Provided region was not found in the partition array or regex, and default partition with id 'aws' doesn't exist.");
return {
...ne.outputs
};
}, getUserAgentPrefix = () => selectedUserAgentPrefix, awsEndpointFunctions = {
isVirtualHostableS3Bucket,
parseArn,
partition
};
customEndpointFunctions.aws = awsEndpointFunctions;
var USER_AGENT = "user-agent", X_AMZ_USER_AGENT = "x-amz-user-agent", SPACE = " ", UA_NAME_SEPARATOR = "/", UA_NAME_ESCAPE_REGEX = /[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w]/g, UA_VALUE_ESCAPE_REGEX = /[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w\#]/g, UA_ESCAPE_CHAR = "-", userAgentMiddleware = _ => (ee, ne) => async ie => {
var re, se;
const {request: oe} = ie;
if (!HttpRequest.isInstance(oe)) return ee(ie);
const {headers: le} = oe, ue = (null == (re = null == ne ? void 0 : ne.userAgent) ? void 0 : re.map(escapeUserAgent)) || [], de = (await _.defaultUserAgentProvider()).map(escapeUserAgent), fe = (null == (se = null == _ ? void 0 : _.customUserAgent) ? void 0 : se.map(escapeUserAgent)) || [], he = getUserAgentPrefix(), pe = (he ? [ he ] : []).concat([ ...de, ...ue, ...fe ]).join(SPACE), ge = [ ...de.filter((_ => _.startsWith("aws-sdk-"))), ...fe ].join(SPACE);
if ("browser" !== _.runtime) {
if (ge) le[X_AMZ_USER_AGENT] = le[X_AMZ_USER_AGENT] ? `${le[USER_AGENT]} ${ge}` : ge;
le[USER_AGENT] = pe;
} else le[X_AMZ_USER_AGENT] = pe;
return ee({
...ie,
request: oe
});
}, escapeUserAgent = _ => {
var ee;
const ne = _[0].split(UA_NAME_SEPARATOR).map((_ => _.replace(UA_NAME_ESCAPE_REGEX, UA_ESCAPE_CHAR))).join(UA_NAME_SEPARATOR), ie = null == (ee = _[1]) ? void 0 : ee.replace(UA_VALUE_ESCAPE_REGEX, UA_ESCAPE_CHAR), re = ne.indexOf(UA_NAME_SEPARATOR), se = ne.substring(0, re);
let oe = ne.substring(re + 1);
if ("api" === se) oe = oe.toLowerCase();
return [ se, oe, ie ].filter((_ => _ && _.length > 0)).reduce(((_, ee, ne) => {
switch (ne) {
case 0:
return ee;
case 1:
return `${_}/${ee}`;
default:
return `${_}#${ee}`;
}
}), "");
}, getUserAgentMiddlewareOptions = {
name: "getUserAgentMiddleware",
step: "build",
priority: "low",
tags: [ "SET_USER_AGENT", "USER_AGENT" ],
override: true
}, getUserAgentPlugin = _ => ({
applyToStack: ee => {
ee.add(userAgentMiddleware(_), getUserAgentMiddlewareOptions);
}
}), DEFAULT_USE_DUALSTACK_ENDPOINT = false, DEFAULT_USE_FIPS_ENDPOINT = false, isFipsRegion = _ => "string" == typeof _ && (_.startsWith("fips-") || _.endsWith("-fips")), getRealRegion = _ => isFipsRegion(_) ? [ "fips-aws-global", "aws-fips" ].includes(_) ? "us-east-1" : _.replace(/fips-(dkr-|prod-)?|-fips/, "") : _, resolveRegionConfig = _ => {
const {region: ee, useFipsEndpoint: ne} = _;
if (!ee) throw new Error("Region is missing");
return {
..._,
region: async () => {
if ("string" == typeof ee) return getRealRegion(ee);
const _ = await ee();
return getRealRegion(_);
},
useFipsEndpoint: async () => {
const _ = "string" == typeof ee ? ee : await ee();
if (isFipsRegion(_)) return true; else return "function" != typeof ne ? Promise.resolve(!!ne) : ne();
}
};
}, resolveEventStreamSerdeConfig = _ => ({
..._,
eventStreamMarshaller: _.eventStreamSerdeProvider(_)
}), CONTENT_LENGTH_HEADER2 = "content-length";
function contentLengthMiddleware(_) {
return ee => async ne => {
const ie = ne.request;
if (HttpRequest.isInstance(ie)) {
const {body: ee, headers: ne} = ie;
if (ee && -1 === Object.keys(ne).map((_ => _.toLowerCase())).indexOf(CONTENT_LENGTH_HEADER2)) try {
const ne = _(ee);
ie.headers = {
...ie.headers,
[CONTENT_LENGTH_HEADER2]: String(ne)
};
} catch (_) {}
}
return ee({
...ne,
request: ie
});
};
}
var contentLengthMiddlewareOptions = {
step: "build",
tags: [ "SET_CONTENT_LENGTH", "CONTENT_LENGTH" ],
name: "contentLengthMiddleware",
override: true
}, getContentLengthPlugin = _ => ({
applyToStack: ee => {
ee.add(contentLengthMiddleware(_.bodyLengthChecker), contentLengthMiddlewareOptions);
}
}), resolveParamsForS3 = async _ => {
const ee = (null == _ ? void 0 : _.Bucket) || "";
if ("string" == typeof _.Bucket) _.Bucket = ee.replace(/#/g, encodeURIComponent("#")).replace(/\?/g, encodeURIComponent("?"));
if (isArnBucketName(ee)) {
if (true === _.ForcePathStyle) throw new Error("Path-style addressing cannot be used with ARN buckets");
} else if (!isDnsCompatibleBucketName(ee) || -1 !== ee.indexOf(".") && !String(_.Endpoint).startsWith("http:") || ee.toLowerCase() !== ee || ee.length < 3) _.ForcePathStyle = true;
if (_.DisableMultiRegionAccessPoints) {
_.disableMultiRegionAccessPoints = true;
_.DisableMRAP = true;
}
return _;
}, DOMAIN_PATTERN = /^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/, IP_ADDRESS_PATTERN = /(\d+\.){3}\d+/, DOTS_PATTERN = /\.\./, isDnsCompatibleBucketName = _ => DOMAIN_PATTERN.test(_) && !IP_ADDRESS_PATTERN.test(_) && !DOTS_PATTERN.test(_), isArnBucketName = _ => {
const [ee, ne, ie, , , re] = _.split(":"), se = "arn" === ee && _.split(":").length >= 6, oe = Boolean(se && ne && ie && re);
if (se && !oe) throw new Error(`Invalid ARN: ${_} was an invalid ARN.`);
return oe;
}, createConfigValueProvider = (_, ee, ne) => {
const configProvider = async () => {
var ie;
const re = null != (ie = ne[_]) ? ie : ne[ee];
if ("function" == typeof re) return re(); else return re;
};
if ("credentialScope" === _ || "CredentialScope" === ee) return async () => {
var _;
const ee = "function" == typeof ne.credentials ? await ne.credentials() : ne.credentials;
return null != (_ = null == ee ? void 0 : ee.credentialScope) ? _ : null == ee ? void 0 : ee.CredentialScope;
};
if ("endpoint" === _ || "endpoint" === ee) return async () => {
const _ = await configProvider();
if (_ && "object" == typeof _) {
if ("url" in _) return _.url.href;
if ("hostname" in _) {
const {protocol: ee, hostname: ne, port: ie, path: re} = _;
return `${ee}//${ne}${ie ? ":" + ie : ""}${re}`;
}
}
return _;
}; else return configProvider;
}, getEndpointFromConfig = async _ => {};
function parseQueryString(_) {
const ee = {};
if (_ = _.replace(/^\?/, "")) for (const ne of _.split("&")) {
let [_, ie = null] = ne.split("=");
_ = decodeURIComponent(_);
if (ie) ie = decodeURIComponent(ie);
if (!(_ in ee)) ee[_] = ie; else if (Array.isArray(ee[_])) ee[_].push(ie); else ee[_] = [ ee[_], ie ];
}
return ee;
}
var parseUrl = _ => {
if ("string" == typeof _) return parseUrl(new URL(_));
const {hostname: ee, pathname: ne, port: ie, protocol: re, search: se} = _;
let oe;
if (se) oe = parseQueryString(se);
return {
hostname: ee,
port: ie ? parseInt(ie) : void 0,
protocol: re,
path: ne,
query: oe
};
}, toEndpointV1 = _ => {
if ("object" == typeof _) if ("url" in _) return parseUrl(_.url); else return _;
return parseUrl(_);
}, getEndpointFromInstructions = async (_, ee, ne, ie) => {
if (!ne.endpoint) {
const _ = await getEndpointFromConfig(ne.serviceId || "");
if (_) ne.endpoint = () => Promise.resolve(toEndpointV1(_));
}
const re = await resolveParams(_, ee, ne);
if ("function" != typeof ne.endpointProvider) throw new Error("config.endpointProvider is not set.");
return ne.endpointProvider(re, ie);
}, resolveParams = async (_, ee, ne) => {
var ie;
const re = {}, se = (null == (ie = null == ee ? void 0 : ee.getEndpointParameterInstructions) ? void 0 : ie.call(ee)) || {};
for (const [ee, ie] of Object.entries(se)) switch (ie.type) {
case "staticContextParams":
re[ee] = ie.value;
break;
case "contextParams":
re[ee] = _[ie.name];
break;
case "clientContextParams":
case "builtInParams":
re[ee] = await createConfigValueProvider(ie.name, ee, ne)();
break;
default:
throw new Error("Unrecognized endpoint parameter instruction: " + JSON.stringify(ie));
}
if (0 === Object.keys(se).length) Object.assign(re, ne);
if ("s3" === String(ne.serviceId).toLowerCase()) await resolveParamsForS3(re);
return re;
}, endpointMiddleware = ({config: _, instructions: ee}) => (ne, ie) => async re => {
var se, oe, le;
const ue = await getEndpointFromInstructions(re.input, {
getEndpointParameterInstructions: () => ee
}, {
..._
}, ie);
ie.endpointV2 = ue;
ie.authSchemes = null == (se = ue.properties) ? void 0 : se.authSchemes;
const de = null == (oe = ie.authSchemes) ? void 0 : oe[0];
if (de) {
ie["signing_region"] = de.signingRegion;
ie["signing_service"] = de.signingName;
const _ = getSmithyContext(ie), ee = null == (le = null == _ ? void 0 : _.selectedHttpAuthScheme) ? void 0 : le.httpAuthOption;
if (ee) ee.signingProperties = Object.assign(ee.signingProperties || {}, {
signing_region: de.signingRegion,
signingRegion: de.signingRegion,
signing_service: de.signingName,
signingName: de.signingName,
signingRegionSet: de.signingRegionSet
}, de.properties);
}
return ne({
...re
});
}, deserializerMiddleware = (_, ee) => (ne, ie) => async ie => {
const {response: re} = await ne(ie);
try {
return {
response: re,
output: await ee(re, _)
};
} catch (_) {
Object.defineProperty(_, "$response", {
value: re
});
if (!("$metadata" in _)) {
const ee = "Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.";
_.message += "\n " + ee;
if ("undefined" != typeof _.$responseBodyText) if (_.$response) _.$response.body = _.$responseBodyText;
}
throw _;
}
}, serializerMiddleware = (_, ee) => (ne, ie) => async re => {
var se;
const oe = (null == (se = ie.endpointV2) ? void 0 : se.url) && _.urlParser ? async () => _.urlParser(ie.endpointV2.url) : _.endpoint;
if (!oe) throw new Error("No valid endpoint provider available.");
const le = await ee(re.input, {
..._,
endpoint: oe
});
return ne({
...re,
request: le
});
}, deserializerMiddlewareOption = {
name: "deserializerMiddleware",
step: "deserialize",
tags: [ "DESERIALIZER" ],
override: true
}, serializerMiddlewareOption = {
name: "serializerMiddleware",
step: "serialize",
tags: [ "SERIALIZER" ],
override: true
};
function getSerdePlugin(_, ee, ne) {
return {
applyToStack: ie => {
ie.add(deserializerMiddleware(_, ne), deserializerMiddlewareOption);
ie.add(serializerMiddleware(_, ee), serializerMiddlewareOption);
}
};
}
var RETRY_MODES, endpointMiddlewareOptions = {
step: "serialize",
tags: [ "ENDPOINT_PARAMETERS", "ENDPOINT_V2", "ENDPOINT" ],
name: "endpointV2Middleware",
override: true,
relation: "before",
toMiddleware: serializerMiddlewareOption.name
}, getEndpointPlugin = (_, ee) => ({
applyToStack: ne => {
ne.addRelativeTo(endpointMiddleware({
config: _,
instructions: ee
}), endpointMiddlewareOptions);
}
}), resolveEndpointConfig = _ => {
var ee, ne, ie;
const re = null != (ee = _.tls) ? ee : true, {endpoint: se} = _, oe = null != se ? async () => toEndpointV1(await normalizeProvider(se)()) : void 0, le = !!se;
return {
..._,
endpoint: oe,
tls: re,
isCustomEndpoint: le,
useDualstackEndpoint: normalizeProvider(null != (ne = _.useDualstackEndpoint) ? ne : false),
useFipsEndpoint: normalizeProvider(null != (ie = _.useFipsEndpoint) ? ie : false)
};
};
(function(_) {
_["STANDARD"] = "standard";
_["ADAPTIVE"] = "adaptive";
})(RETRY_MODES || (RETRY_MODES = {}));
var getRandomValues2, DEFAULT_MAX_ATTEMPTS = 3, DEFAULT_RETRY_MODE = RETRY_MODES.STANDARD, THROTTLING_ERROR_CODES = [ "BandwidthLimitExceeded", "EC2ThrottledException", "LimitExceededException", "PriorRequestNotComplete", "ProvisionedThroughputExceededException", "RequestLimitExceeded", "RequestThrottled", "RequestThrottledException", "SlowDown", "ThrottledException", "Throttling", "ThrottlingException", "TooManyRequestsException", "TransactionInProgressException" ], TRANSIENT_ERROR_CODES = [ "TimeoutError", "RequestTimeout", "RequestTimeoutException" ], TRANSIENT_ERROR_STATUS_CODES = [ 500, 502, 503, 504 ], NODEJS_TIMEOUT_ERROR_CODES = [ "ECONNRESET", "ECONNREFUSED", "EPIPE", "ETIMEDOUT" ], isClockSkewCorrectedError = _ => {
var ee;
return null == (ee = _.$metadata) ? void 0 : ee.clockSkewCorrected;
}, isThrottlingError = _ => {
var ee, ne;
return 429 === (null == (ee = _.$metadata) ? void 0 : ee.httpStatusCode) || THROTTLING_ERROR_CODES.includes(_.name) || true == (null == (ne = _.$retryable) ? void 0 : ne.throttling);
}, isTransientError = _ => {
var ee;
return isClockSkewCorrectedError(_) || TRANSIENT_ERROR_CODES.includes(_.name) || NODEJS_TIMEOUT_ERROR_CODES.includes((null == _ ? void 0 : _.code) || "") || TRANSIENT_ERROR_STATUS_CODES.includes((null == (ee = _.$metadata) ? void 0 : ee.httpStatusCode) || 0);
}, isServerError = _ => {
var ee;
if (void 0 !== (null == (ee = _.$metadata) ? void 0 : ee.httpStatusCode)) {
const ee = _.$metadata.httpStatusCode;
if (500 <= ee && ee <= 599 && !isTransientError(_)) return true; else return false;
}
return false;
}, DefaultRateLimiter = class {
constructor(_) {
var ee, ne, ie, re, se;
this.currentCapacity = 0;
this.enabled = false;
this.lastMaxRate = 0;
this.measuredTxRate = 0;
this.requestCount = 0;
this.lastTimestamp = 0;
this.timeWindow = 0;
this.beta = null != (ee = null == _ ? void 0 : _.beta) ? ee : .7;
this.minCapacity = null != (ne = null == _ ? void 0 : _.minCapacity) ? ne : 1;
this.minFillRate = null != (ie = null == _ ? void 0 : _.minFillRate) ? ie : .5;
this.scaleConstant = null != (re = null == _ ? void 0 : _.scaleConstant) ? re : .4;
this.smooth = null != (se = null == _ ? void 0 : _.smooth) ? se : .8;
const oe = this.getCurrentTimeInSeconds();
this.lastThrottleTime = oe;
this.lastTxRateBucket = Math.floor(this.getCurrentTimeInSeconds());
this.fillRate = this.minFillRate;
this.maxCapacity = this.minCapacity;
}
getCurrentTimeInSeconds() {
return Date.now() / 1e3;
}
async getSendToken() {
return this.acquireTokenBucket(1);
}
async acquireTokenBucket(_) {
if (this.enabled) {
this.refillTokenBucket();
if (_ > this.currentCapacity) {
const ee = (_ - this.currentCapacity) / this.fillRate * 1e3;
await new Promise((_ => setTimeout(_, ee)));
}
this.currentCapacity = this.currentCapacity - _;
}
}
refillTokenBucket() {
const _ = this.getCurrentTimeInSeconds();
if (!this.lastTimestamp) {
this.lastTimestamp = _;
return;
}
const ee = (_ - this.lastTimestamp) * this.fillRate;
this.currentCapacity = Math.min(this.maxCapacity, this.currentCapacity + ee);
this.lastTimestamp = _;
}
updateClientSendingRate(_) {
let ee;
this.updateMeasuredRate();
if (isThrottlingError(_)) {
const _ = !this.enabled ? this.measuredTxRate : Math.min(this.measuredTxRate, this.fillRate);
this.lastMaxRate = _;
this.calculateTimeWindow();
this.lastThrottleTime = this.getCurrentTimeInSeconds();
ee = this.cubicThrottle(_);
this.enableTokenBucket();
} else {
this.calculateTimeWindow();
ee = this.cubicSuccess(this.getCurrentTimeInSeconds());
}
const ne = Math.min(ee, 2 * this.measuredTxRate);
this.updateTokenBucketRate(ne);
}
calculateTimeWindow() {
this.timeWindow = this.getPrecise(Math.pow(this.lastMaxRate * (1 - this.beta) / this.scaleConstant, 1 / 3));
}
cubicThrottle(_) {
return this.getPrecise(_ * this.beta);
}
cubicSuccess(_) {
return this.getPrecise(this.scaleConstant * Math.pow(_ - this.lastThrottleTime - this.timeWindow, 3) + this.lastMaxRate);
}
enableTokenBucket() {
this.enabled = true;
}
updateTokenBucketRate(_) {
this.refillTokenBucket();
this.fillRate = Math.max(_, this.minFillRate);
this.maxCapacity = Math.max(_, this.minCapacity);
this.currentCapacity = Math.min(this.currentCapacity, this.maxCapacity);
}
updateMeasuredRate() {
const _ = this.getCurrentTimeInSeconds(), ee = Math.floor(2 * _) / 2;
this.requestCount++;
if (ee > this.lastTxRateBucket) {
const _ = this.requestCount / (ee - this.lastTxRateBucket);
this.measuredTxRate = this.getPrecise(_ * this.smooth + this.measuredTxRate * (1 - this.smooth));
this.requestCount = 0;
this.lastTxRateBucket = ee;
}
}
getPrecise(_) {
return parseFloat(_.toFixed(8));
}
}, DEFAULT_RETRY_DELAY_BASE = 100, MAXIMUM_RETRY_DELAY = 2e4, THROTTLING_RETRY_DELAY_BASE = 500, INITIAL_RETRY_TOKENS = 500, RETRY_COST = 5, TIMEOUT_RETRY_COST = 10, NO_RETRY_INCREMENT = 1, INVOCATION_ID_HEADER = "amz-sdk-invocation-id", REQUEST_HEADER = "amz-sdk-request", getDefaultRetryBackoffStrategy = () => {
let _ = DEFAULT_RETRY_DELAY_BASE;
return {
computeNextBackoffDelay: ee => Math.floor(Math.min(MAXIMUM_RETRY_DELAY, Math.random() * 2 ** ee * _)),
setDelayBase: ee => {
_ = ee;
}
};
}, createDefaultRetryToken = ({retryDelay: _, retryCount: ee, retryCost: ne}) => ({
getRetryCount: () => ee,
getRetryDelay: () => Math.min(MAXIMUM_RETRY_DELAY, _),
getRetryCost: () => ne
}), StandardRetryStrategy = class {
constructor(_) {
this.maxAttempts = _;
this.mode = RETRY_MODES.STANDARD;
this.capacity = INITIAL_RETRY_TOKENS;
this.retryBackoffStrategy = getDefaultRetryBackoffStrategy();
this.maxAttemptsProvider = "function" == typeof _ ? _ : async () => _;
}
async acquireInitialRetryToken(_) {
return createDefaultRetryToken({
retryDelay: DEFAULT_RETRY_DELAY_BASE,
retryCount: 0
});
}
async refreshRetryTokenForRetry(_, ee) {
const ne = await this.getMaxAttempts();
if (this.shouldRetry(_, ee, ne)) {
const ne = ee.errorType;
this.retryBackoffStrategy.setDelayBase("THROTTLING" === ne ? THROTTLING_RETRY_DELAY_BASE : DEFAULT_RETRY_DELAY_BASE);
const ie = this.retryBackoffStrategy.computeNextBackoffDelay(_.getRetryCount()), re = ee.retryAfterHint ? Math.max(ee.retryAfterHint.getTime() - Date.now() || 0, ie) : ie, se = this.getCapacityCost(ne);
this.capacity -= se;
return createDefaultRetryToken({
retryDelay: re,
retryCount: _.getRetryCount() + 1,
retryCost: se
});
}
throw new Error("No retry token available");
}
recordSuccess(_) {
var ee;
this.capacity = Math.max(INITIAL_RETRY_TOKENS, this.capacity + (null != (ee = _.getRetryCost()) ? ee : NO_RETRY_INCREMENT));
}
getCapacity() {
return this.capacity;
}
async getMaxAttempts() {
try {
return await this.maxAttemptsProvider();
} catch (_) {
console.warn(`Max attempts provider could not resolve. Using default of ${DEFAULT_MAX_ATTEMPTS}`);
return DEFAULT_MAX_ATTEMPTS;
}
}
shouldRetry(_, ee, ne) {
return _.getRetryCount() + 1 < ne && this.capacity >= this.getCapacityCost(ee.errorType) && this.isRetryableError(ee.errorType);
}
getCapacityCost(_) {
return "TRANSIENT" === _ ? TIMEOUT_RETRY_COST : RETRY_COST;
}
isRetryableError(_) {
return "THROTTLING" === _ || "TRANSIENT" === _;
}
}, AdaptiveRetryStrategy = class {
constructor(_, ee) {
this.maxAttemptsProvider = _;
this.mode = RETRY_MODES.ADAPTIVE;
const {rateLimiter: ne} = null != ee ? ee : {};
this.rateLimiter = null != ne ? ne : new DefaultRateLimiter;
this.standardRetryStrategy = new StandardRetryStrategy(_);
}
async acquireInitialRetryToken(_) {
await this.rateLimiter.getSendToken();
return this.standardRetryStrategy.acquireInitialRetryToken(_);
}
async refreshRetryTokenForRetry(_, ee) {
this.rateLimiter.updateClientSendingRate(ee);
return this.standardRetryStrategy.refreshRetryTokenForRetry(_, ee);
}
recordSuccess(_) {
this.rateLimiter.updateClientSendingRate({});
this.standardRetryStrategy.recordSuccess(_);
}
}, ConfiguredRetryStrategy = class extends StandardRetryStrategy {
constructor(_, ee = DEFAULT_RETRY_DELAY_BASE) {
super("function" == typeof _ ? _ : async () => _);
if ("number" == typeof ee) this.computeNextBackoffDelay = () => ee; else this.computeNextBackoffDelay = ee;
}
async refreshRetryTokenForRetry(_, ee) {
const ne = await super.refreshRetryTokenForRetry(_, ee);
ne.getRetryDelay = () => this.computeNextBackoffDelay(ne.getRetryCount());
return ne;
}
}, rnds82 = new Uint8Array(16);
function rng2() {
if (!getRandomValues2) if (!(getRandomValues2 = "undefined" != typeof crypto && crypto.getRandomValues && crypto.getRandomValues.bind(crypto))) throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
return getRandomValues2(rnds82);
}
var byteToHex2 = [];
for (let _ = 0; _ < 256; ++_) byteToHex2.push((_ + 256).toString(16).slice(1));
function unsafeStringify(_, ee = 0) {
return byteToHex2[_[ee + 0]] + byteToHex2[_[ee + 1]] + byteToHex2[_[ee + 2]] + byteToHex2[_[ee + 3]] + "-" + byteToHex2[_[ee + 4]] + byteToHex2[_[ee + 5]] + "-" + byteToHex2[_[ee + 6]] + byteToHex2[_[ee + 7]] + "-" + byteToHex2[_[ee + 8]] + byteToHex2[_[ee + 9]] + "-" + byteToHex2[_[ee + 10]] + byteToHex2[_[ee + 11]] + byteToHex2[_[ee + 12]] + byteToHex2[_[ee + 13]] + byteToHex2[_[ee + 14]] + byteToHex2[_[ee + 15]];
}
var randomUUID = "undefined" != typeof crypto && crypto.randomUUID && crypto.randomUUID.bind(crypto), native_default = {
randomUUID
};
function v42(_, ee, ne) {
if (native_default.randomUUID && !ee && !_) return native_default.randomUUID();
const ie = (_ = _ || {}).random || (_.rng || rng2)();
ie[6] = 15 & ie[6] | 64;
ie[8] = 63 & ie[8] | 128;
if (ee) {
ne = ne || 0;
for (let _ = 0; _ < 16; ++_) ee[ne + _] = ie[_];
return ee;
}
return unsafeStringify(ie);
}
var AnalyticsFilter, LifecycleRuleFilter, MetricsFilter, ReplicationRuleFilter, v4_default2 = v42, asSdkError = _ => {
if (_ instanceof Error) return _;
if (_ instanceof Object) return Object.assign(new Error, _);
if ("string" == typeof _) return new Error(_); else return new Error(`AWS SDK error wrapper for ${_}`);
}, resolveRetryConfig = _ => {
var ee;
const {retryStrategy: ne} = _, ie = normalizeProvider(null != (ee = _.maxAttempts) ? ee : DEFAULT_MAX_ATTEMPTS);
return {
..._,
maxAttempts: ie,
retryStrategy: async () => {
if (ne) return ne;
if (await normalizeProvider(_.retryMode)() === RETRY_MODES.ADAPTIVE) return new AdaptiveRetryStrategy(ie); else return new StandardRetryStrategy(ie);
}
};
}, isStreamingPayload = _ => (null == _ ? void 0 : _.body) instanceof ReadableStream, retryMiddleware = _ => (ee, ne) => async ie => {
var re;
let se = await _.retryStrategy();
const oe = await _.maxAttempts();
if (isRetryStrategyV2(se)) {
let _ = await se.acquireInitialRetryToken(ne["partition_id"]), le = new Error, ue = 0, de = 0;
const {request: fe} = ie, he = HttpRequest.isInstance(fe);
if (he) fe.headers[INVOCATION_ID_HEADER] = v4_default2();
for (;;) try {
if (he) fe.headers[REQUEST_HEADER] = `attempt=${ue + 1}; max=${oe}`;
const {response: ne, output: re} = await ee(ie);
se.recordSuccess(_);
re.$metadata.attempts = ue + 1;
re.$metadata.totalRetryDelay = de;
return {
response: ne,
output: re
};
} catch (ee) {
const ie = getRetryErrorInfo(ee);
le = asSdkError(ee);
if (he && isStreamingPayload(fe)) {
null == (re = ne.logger instanceof NoOpLogger ? console : ne.logger) || re.warn("An error was encountered in a non-retryable streaming request.");
throw le;
}
try {
_ = await se.refreshRetryTokenForRetry(_, ie);
} catch (_) {
if (!le.$metadata) le.$metadata = {};
le.$metadata.attempts = ue + 1;
le.$metadata.totalRetryDelay = de;
throw le;
}
ue = _.getRetryCount();
const oe = _.getRetryDelay();
de += oe;
await new Promise((_ => setTimeout(_, oe)));
}
} else {
if (null == se ? void 0 : se.mode) ne.userAgent = [ ...ne.userAgent || [], [ "cfg/retry-mode", se.mode ] ];
return se.retry(ee, ie);
}
}, isRetryStrategyV2 = _ => "undefined" != typeof _.acquireInitialRetryToken && "undefined" != typeof _.refreshRetryTokenForRetry && "undefined" != typeof _.recordSuccess, getRetryErrorInfo = _ => {
const ee = {
error: _,
errorType: getRetryErrorType(_)
}, ne = getRetryAfterHint(_.$response);
if (ne) ee.retryAfterHint = ne;
return ee;
}, getRetryErrorType = _ => {
if (isThrottlingError(_)) return "THROTTLING";
if (isTransientError(_)) return "TRANSIENT";
if (isServerError(_)) return "SERVER_ERROR"; else return "CLIENT_ERROR";
}, retryMiddlewareOptions = {
name: "retryMiddleware",
tags: [ "RETRY" ],
step: "finalizeRequest",
priority: "high",
override: true
}, getRetryPlugin = _ => ({
applyToStack: ee => {
ee.add(retryMiddleware(_), retryMiddlewareOptions);
}
}), getRetryAfterHint = _ => {
if (!HttpResponse.isInstance(_)) return;
const ee = Object.keys(_.headers).find((_ => "retry-after" === _.toLowerCase()));
if (!ee) return;
const ne = _.headers[ee], ie = Number(ne);
if (!Number.isNaN(ie)) return new Date(1e3 * ie); else return new Date(ne);
}, resolveClientEndpointParameters = _ => {
var ee, ne, ie, re, se, oe;
return {
..._,
useFipsEndpoint: null != (ee = _.useFipsEndpoint) ? ee : false,
useDualstackEndpoint: null != (ne = _.useDualstackEndpoint) ? ne : false,
forcePathStyle: null != (ie = _.forcePathStyle) ? ie : false,
useAccelerateEndpoint: null != (re = _.useAccelerateEndpoint) ? re : false,
useGlobalEndpoint: null != (se = _.useGlobalEndpoint) ? se : false,
disableMultiregionAccessPoints: null != (oe = _.disableMultiregionAccessPoints) ? oe : false,
defaultSigningName: "s3"
};
}, commonParams = {
ForcePathStyle: {
type: "clientContextParams",
name: "forcePathStyle"
},
UseArnRegion: {
type: "clientContextParams",
name: "useArnRegion"
},
DisableMultiRegionAccessPoints: {
type: "clientContextParams",
name: "disableMultiregionAccessPoints"
},
Accelerate: {
type: "clientContextParams",
name: "useAccelerateEndpoint"
},
DisableS3ExpressSessionAuth: {
type: "clientContextParams",
name: "disableS3ExpressSessionAuth"
},
UseGlobalEndpoint: {
type: "builtInParams",
name: "useGlobalEndpoint"
},
UseFIPS: {
type: "builtInParams",
name: "useFipsEndpoint"
},
Endpoint: {
type: "builtInParams",
name: "endpoint"
},
Region: {
type: "builtInParams",
name: "region"
},
UseDualStack: {
type: "builtInParams",
name: "useDualstackEndpoint"
}
}, S3ServiceException = class _S3ServiceException extends ServiceException {
constructor(_) {
super(_);
Object.setPrototypeOf(this, _S3ServiceException.prototype);
}
}, NoSuchUpload = class _NoSuchUpload extends S3ServiceException {
constructor(_) {
super({
name: "NoSuchUpload",
$fault: "client",
..._
});
this.name = "NoSuchUpload";
this.$fault = "client";
Object.setPrototypeOf(this, _NoSuchUpload.prototype);
}
}, ObjectNotInActiveTierError = class _ObjectNotInActiveTierError extends S3ServiceException {
constructor(_) {
super({
name: "ObjectNotInActiveTierError",
$fault: "client",
..._
});
this.name = "ObjectNotInActiveTierError";
this.$fault = "client";
Object.setPrototypeOf(this, _ObjectNotInActiveTierError.prototype);
}
}, BucketAlreadyExists = class _BucketAlreadyExists extends S3ServiceException {
constructor(_) {
super({
name: "BucketAlreadyExists",
$fault: "client",
..._
});
this.name = "BucketAlreadyExists";
this.$fault = "client";
Object.setPrototypeOf(this, _BucketAlreadyExists.prototype);
}
}, BucketAlreadyOwnedByYou = class _BucketAlreadyOwnedByYou extends S3ServiceException {
constructor(_) {
super({
name: "BucketAlreadyOwnedByYou",
$fault: "client",
..._
});
this.name = "BucketAlreadyOwnedByYou";
this.$fault = "client";
Object.setPrototypeOf(this, _BucketAlreadyOwnedByYou.prototype);
}
}, NoSuchBucket = class _NoSuchBucket extends S3ServiceException {
constructor(_) {
super({
name: "NoSuchBucket",
$fault: "client",
..._
});
this.name = "NoSuchBucket";
this.$fault = "client";
Object.setPrototypeOf(this, _NoSuchBucket.prototype);
}
};
(AnalyticsFilter || (AnalyticsFilter = {})).visit = (_, ee) => {
if (void 0 !== _.Prefix) return ee.Prefix(_.Prefix);
if (void 0 !== _.Tag) return ee.Tag(_.Tag);
if (void 0 !== _.And) return ee.And(_.And); else return ee._(_.$unknown[0], _.$unknown[1]);
};
(LifecycleRuleFilter || (LifecycleRuleFilter = {})).visit = (_, ee) => {
if (void 0 !== _.Prefix) return ee.Prefix(_.Prefix);
if (void 0 !== _.Tag) return ee.Tag(_.Tag);
if (void 0 !== _.ObjectSizeGreaterThan) return ee.ObjectSizeGreaterThan(_.ObjectSizeGreaterThan);
if (void 0 !== _.ObjectSizeLessThan) return ee.ObjectSizeLessThan(_.ObjectSizeLessThan);
if (void 0 !== _.And) return ee.And(_.And); else return ee._(_.$unknown[0], _.$unknown[1]);
};
(MetricsFilter || (MetricsFilter = {})).visit = (_, ee) => {
if (void 0 !== _.Prefix) return ee.Prefix(_.Prefix);
if (void 0 !== _.Tag) return ee.Tag(_.Tag);
if (void 0 !== _.AccessPointArn) return ee.AccessPointArn(_.AccessPointArn);
if (void 0 !== _.And) return ee.And(_.And); else return ee._(_.$unknown[0], _.$unknown[1]);
};
(ReplicationRuleFilter || (ReplicationRuleFilter = {})).visit = (_, ee) => {
if (void 0 !== _.Prefix) return ee.Prefix(_.Prefix);
if (void 0 !== _.Tag) return ee.Tag(_.Tag);
if (void 0 !== _.And) return ee.And(_.And); else return ee._(_.$unknown[0], _.$unknown[1]);
};
var InvalidObjectState = class _InvalidObjectState extends S3ServiceException {
constructor(_) {
super({
name: "InvalidObjectState",
$fault: "client",
..._
});
this.name = "InvalidObjectState";
this.$fault = "client";
Object.setPrototypeOf(this, _InvalidObjectState.prototype);
this.StorageClass = _.StorageClass;
this.AccessTier = _.AccessTier;
}
}, NoSuchKey = class _NoSuchKey extends S3ServiceException {
constructor(_) {
super({
name: "NoSuchKey",
$fault: "client",
..._
});
this.name = "NoSuchKey";
this.$fault = "client";
Object.setPrototypeOf(this, _NoSuchKey.prototype);
}
}, NotFound = class _NotFound extends S3ServiceException {
constructor(_) {
super({
name: "NotFound",
$fault: "client",
..._
});
this.name = "NotFound";
this.$fault = "client";
Object.setPrototypeOf(this, _NotFound.prototype);
}
}, CompleteMultipartUploadOutputFilterSensitiveLog = _ => ({
..._,
..._.SSEKMSKeyId && {
SSEKMSKeyId: SENSITIVE_STRING
}
}), CompleteMultipartUploadRequestFilterSensitiveLog = _ => ({
..._,
..._.SSECustomerKey && {
SSECustomerKey: SENSITIVE_STRING
}
}), CopyObjectOutputFilterSensitiveLog = _ => ({
..._,
..._.SSEKMSKeyId && {
SSEKMSKeyId: SENSITIVE_STRING
},
..._.SSEKMSEncryptionContext && {
SSEKMSEncryptionContext: SENSITIVE_STRING
}
}), CopyObjectRequestFilterSensitiveLog = _ => ({
..._,
..._.SSECustomerKey && {
SSECustomerKey: SENSITIVE_STRING
},
..._.SSEKMSKeyId && {
SSEKMSKeyId: SENSITIVE_STRING
},
..._.SSEKMSEncryptionContext && {
SSEKMSEncryptionContext: SENSITIVE_STRING
},
..._.CopySourceSSECustomerKey && {
CopySourceSSECustomerKey: SENSITIVE_STRING
}
}), CreateMultipartUploadOutputFilterSensitiveLog = _ => ({
..._,
..._.SSEKMSKeyId && {
SSEKMSKeyId: SENSITIVE_STRING
},
..._.SSEKMSEncryptionContext && {
SSEKMSEncryptionContext: SENSITIVE_STRING
}
}), CreateMultipartUploadRequestFilterSensitiveLog = _ => ({
..._,
..._.SSECustomerKey && {
SSECustomerKey: SENSITIVE_STRING
},
..._.SSEKMSKeyId && {
SSEKMSKeyId: SENSITIVE_STRING
},
..._.SSEKMSEncryptionContext && {
SSEKMSEncryptionContext: SENSITIVE_STRING
}
}), SessionCredentialsFilterSensitiveLog = _ => ({
..._,
..._.SecretAccessKey && {
SecretAccessKey: SENSITIVE_STRING
},
..._.SessionToken && {
SessionToken: SENSITIVE_STRING
}
}), CreateSessionOutputFilterSensitiveLog = _ => ({
..._,
..._.Credentials && {
Credentials: SessionCredentialsFilterSensitiveLog(_.Credentials)
}
}), ServerSideEncryptionByDefaultFilterSensitiveLog = _ => ({
..._,
..._.KMSMasterKeyID && {
KMSMasterKeyID: SENSITIVE_STRING
}
}), ServerSideEncryptionRuleFilterSensitiveLog = _ => ({
..._,
..._.ApplyServerSideEncryptionByDefault && {
ApplyServerSideEncryptionByDefault: ServerSideEncryptionByDefaultFilterSensitiveLog(_.ApplyServerSideEncryptionByDefault)
}
}), ServerSideEncryptionConfigurationFilterSensitiveLog = _ => ({
..._,
..._.Rules && {
Rules: _.Rules.map((_ => ServerSideEncryptionRuleFilterSensitiveLog(_)))
}
}), GetBucketEncryptionOutputFilterSensitiveLog = _ => ({
..._,
..._.ServerSideEncryptionConfiguration && {
ServerSideEncryptionConfiguration: ServerSideEncryptionConfigurationFilterSensitiveLog(_.ServerSideEncryptionConfiguration)
}
}), SSEKMSFilterSensitiveLog = _ => ({
..._,
..._.KeyId && {
KeyId: SENSITIVE_STRING
}
}), InventoryEncryptionFilterSensitiveLog = _ => ({
..._,
..._.SSEKMS && {
SSEKMS: SSEKMSFilterSensitiveLog(_.SSEKMS)
}
}), InventoryS3BucketDestinationFilterSensitiveLog = _ => ({
..._,
..._.Encryption && {
Encryption: InventoryEncryptionFilterSensitiveLog(_.Encryption)
}
}), InventoryDestinationFilterSensitiveLog = _ => ({
..._,
..._.S3BucketDestination && {
S3BucketDestination: InventoryS3BucketDestinationFilterSensitiveLog(_.S3BucketDestination)
}
}), InventoryConfigurationFilterSensitiveLog = _ => ({
..._,
..._.Destination && {
Destination: InventoryDestinationFilterSensitiveLog(_.Destination)
}
}), GetBucketInventoryConfigurationOutputFilterSensitiveLog = _ => ({
..._,
..._.InventoryConfiguration && {
InventoryConfiguration: InventoryConfigurationFilterSensitiveLog(_.InventoryConfiguration)
}
}), GetObjectOutputFilterSensitiveLog = _ => ({
..._,
..._.SSEKMSKeyId && {
SSEKMSKeyId: SENSITIVE_STRING
}
}), GetObjectRequestFilterSensitiveLog = _ => ({
..._,
..._.SSECustomerKey && {
SSECustomerKey: SENSITIVE_STRING
}
}), GetObjectAttributesRequestFilterSensitiveLog = _ => ({
..._,
..._.SSECustomerKey && {
SSECustomerKey: SENSITIVE_STRING
}
}), GetObjectTorrentOutputFilterSensitiveLog = _ => ({
..._
}), HeadObjectOutputFilterSensitiveLog = _ => ({
..._,
..._.SSEKMSKeyId && {
SSEKMSKeyId: SENSITIVE_STRING
}
}), HeadObjectRequestFilterSensitiveLog = _ => ({
..._,
..._.SSECustomerKey && {
SSECustomerKey: SENSITIVE_STRING
}
}), ListBucketInventoryConfigurationsOutputFilterSensitiveLog = _ => ({
..._,
..._.InventoryConfigurationList && {
InventoryConfigurationList: _.InventoryConfigurationList.map((_ => InventoryConfigurationFilterSensitiveLog(_)))
}
}), ListPartsRequestFilterSensitiveLog = _ => ({
..._,
..._.SSECustomerKey && {
SSECustomerKey: SENSITIVE_STRING
}
}), PutBucketEncryptionRequestFilterSensitiveLog = _ => ({
..._,
..._.ServerSideEncryptionConfiguration && {
ServerSideEncryptionConfiguration: ServerSideEncryptionConfigurationFilterSensitiveLog(_.ServerSideEncryptionConfiguration)
}
}), PutBucketInventoryConfigurationRequestFilterSensitiveLog = _ => ({
..._,
..._.InventoryConfiguration && {
InventoryConfiguration: InventoryConfigurationFilterSensitiveLog(_.InventoryConfiguration)
}
}), httpAuthSchemeEndpointRuleSetMiddlewareOptions = {
step: "serialize",
tags: [ "HTTP_AUTH_SCHEME" ],
name: "httpAuthSchemeMiddleware",
override: true,
relation: "before",
toMiddleware: endpointMiddlewareOptions.name
}, httpAuthSchemeMiddlewareOptions = {
step: "serialize",
tags: [ "HTTP_AUTH_SCHEME" ],
name: "httpAuthSchemeMiddleware",
override: true,
relation: "before",
toMiddleware: serializerMiddlewareOption.name
}, httpSigningMiddlewareOptions = {
step: "finalizeRequest",
tags: [ "HTTP_SIGNING" ],
name: "httpSigningMiddleware",
aliases: [ "apiKeyMiddleware", "tokenMiddleware", "awsAuthMiddleware" ],
override: true,
relation: "after",
toMiddleware: retryMiddlewareOptions.name
}, createIsIdentityExpiredFunction = _ => ee => doesIdentityRequireRefresh(ee) && ee.expiration.getTime() - Date.now() < _, EXPIRATION_MS = 3e5, isIdentityExpired = createIsIdentityExpiredFunction(EXPIRATION_MS), doesIdentityRequireRefresh = _ => void 0 !== _.expiration;
function requestBuilder(_, ee) {
return new RequestBuilder(_, ee);
}
var RequestBuilder = class {
constructor(_, ee) {
this.input = _;
this.context = ee;
this.query = {};
this.method = "";
this.headers = {};
this.path = "";
this.body = null;
this.hostname = "";
this.resolvePathStack = [];
}
async build() {
const {hostname: _, protocol: ee = "https", port: ne, path: ie} = await this.context.endpoint();
this.path = ie;
for (const _ of this.resolvePathStack) _(this.path);
return new HttpRequest({
protocol: ee,
hostname: this.hostname || _,
port: ne,
method: this.method,
path: this.path,
query: this.query,
body: this.body,
headers: this.headers
});
}
hn(_) {
this.hostname = _;
return this;
}
bp(_) {
this.resolvePathStack.push((ee => {
this.path = `${(null == ee ? void 0 : ee.endsWith("/")) ? ee.slice(0, -1) : ee || ""}` + _;
}));
return this;
}
p(_, ee, ne, ie) {
this.resolvePathStack.push((re => {
this.path = resolvedPath(re, this.input, _, ee, ne, ie);
}));
return this;
}
h(_) {
this.headers = _;
return this;
}
q(_) {
this.query = _;
return this;
}
b(_) {
this.body = _;
return this;
}
m(_) {
this.method = _;
return this;
}
}, collectBodyString2 = (_, ee) => collectBody(_, ee).then((_ => ee.utf8Encoder(_))), import_fast_xml_parser = __toESM(require_fxp()), parseXmlBody = (_, ee) => collectBodyString2(_, ee).then((_ => {
if (_.length) {
const ee = new import_fast_xml_parser.XMLParser({
attributeNamePrefix: "",
htmlEntities: true,
ignoreAttributes: false,
ignoreDeclaration: true,
parseTagValue: false,
trimValues: false,
tagValueProcessor: (_, ee) => "" === ee.trim() && ee.includes("\n") ? "" : void 0
});
ee.addEntity("#xD", "\r");
ee.addEntity("#10", "\n");
let ne;
try {
ne = ee.parse(_, true);
} catch (ee) {
if (ee && "object" == typeof ee) Object.defineProperty(ee, "$responseBodyText", {
value: _
});
throw ee;
}
const ie = "#text", re = Object.keys(ne)[0], se = ne[re];
if (se[ie]) {
se[re] = se[ie];
delete se[ie];
}
return getValueFromTextNode(se);
}
return {};
})), parseXmlErrorBody = async (_, ee) => {
var ne;
const ie = await parseXmlBody(_, ee);
if (ie.Error) ie.Error.message = null != (ne = ie.Error.message) ? ne : ie.Error.Message;
return ie;
}, loadRestXmlErrorCode = (_, ee) => {
var ne;
if (void 0 !== (null == (ne = null == ee ? void 0 : ee.Error) ? void 0 : ne.Code)) return ee.Error.Code;
if (void 0 !== (null == ee ? void 0 : ee.Code)) return ee.Code;
if (404 == _.statusCode) return "NotFound";
};
function escapeAttribute(_) {
return _.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """);
}
function escapeElement(_) {
return _.replace(/&/g, "&").replace(/"/g, """).replace(/'/g, "'").replace(//g, ">").replace(/\r/g, "
").replace(/\n/g, "
").replace(/\u0085/g, "
").replace(/\u2028/, "
");
}
var SelectObjectContentEventStream, XmlText = class {
constructor(_) {
this.value = _;
}
toString() {
return escapeElement("" + this.value);
}
}, XmlNode = class _XmlNode {
static of(_, ee, ne) {
const ie = new _XmlNode(_);
if (void 0 !== ee) ie.addChildNode(new XmlText(ee));
if (void 0 !== ne) ie.withName(ne);
return ie;
}
constructor(_, ee = []) {
this.name = _;
this.children = ee;
this.attributes = {};
}
withName(_) {
this.name = _;
return this;
}
addAttribute(_, ee) {
this.attributes[_] = ee;
return this;
}
addChildNode(_) {
this.children.push(_);
return this;
}
removeAttribute(_) {
delete this.attributes[_];
return this;
}
n(_) {
this.name = _;
return this;
}
c(_) {
this.children.push(_);
return this;
}
a(_, ee) {
if (null != ee) this.attributes[_] = ee;
return this;
}
cc(_, ee, ne = ee) {
if (null != _[ee]) {
const ie = _XmlNode.of(ee, _[ee]).withName(ne);
this.c(ie);
}
}
l(_, ee, ne, ie) {
if (null != _[ee]) ie().map((_ => {
_.withName(ne);
this.c(_);
}));
}
lc(_, ee, ne, ie) {
if (null != _[ee]) {
const _ = ie(), ee = new _XmlNode(ne);
_.map((_ => {
ee.c(_);
}));
this.c(ee);
}
}
toString() {
const _ = Boolean(this.children.length);
let ee = `<${this.name}`;
const ne = this.attributes;
for (const _ of Object.keys(ne)) {
const ie = ne[_];
if (null != ie) ee += ` ${_}="${escapeAttribute("" + ie)}"`;
}
return ee += !_ ? "/>" : `>${this.children.map((_ => _.toString())).join("")}${this.name}>`;
}
}, ObjectAlreadyInActiveTierError = class _ObjectAlreadyInActiveTierError extends S3ServiceException {
constructor(_) {
super({
name: "ObjectAlreadyInActiveTierError",
$fault: "client",
..._
});
this.name = "ObjectAlreadyInActiveTierError";
this.$fault = "client";
Object.setPrototypeOf(this, _ObjectAlreadyInActiveTierError.prototype);
}
};
(SelectObjectContentEventStream || (SelectObjectContentEventStream = {})).visit = (_, ee) => {
if (void 0 !== _.Records) return ee.Records(_.Records);
if (void 0 !== _.Stats) return ee.Stats(_.Stats);
if (void 0 !== _.Progress) return ee.Progress(_.Progress);
if (void 0 !== _.Cont) return ee.Cont(_.Cont);
if (void 0 !== _.End) return ee.End(_.End); else return ee._(_.$unknown[0], _.$unknown[1]);
};
var PutObjectOutputFilterSensitiveLog = _ => ({
..._,
..._.SSEKMSKeyId && {
SSEKMSKeyId: SENSITIVE_STRING
},
..._.SSEKMSEncryptionContext && {
SSEKMSEncryptionContext: SENSITIVE_STRING
}
}), PutObjectRequestFilterSensitiveLog = _ => ({
..._,
..._.SSECustomerKey && {
SSECustomerKey: SENSITIVE_STRING
},
..._.SSEKMSKeyId && {
SSEKMSKeyId: SENSITIVE_STRING
},
..._.SSEKMSEncryptionContext && {
SSEKMSEncryptionContext: SENSITIVE_STRING
}
}), EncryptionFilterSensitiveLog = _ => ({
..._,
..._.KMSKeyId && {
KMSKeyId: SENSITIVE_STRING
}
}), S3LocationFilterSensitiveLog = _ => ({
..._,
..._.Encryption && {
Encryption: EncryptionFilterSensitiveLog(_.Encryption)
}
}), OutputLocationFilterSensitiveLog = _ => ({
..._,
..._.S3 && {
S3: S3LocationFilterSensitiveLog(_.S3)
}
}), RestoreRequestFilterSensitiveLog = _ => ({
..._,
..._.OutputLocation && {
OutputLocation: OutputLocationFilterSensitiveLog(_.OutputLocation)
}
}), RestoreObjectRequestFilterSensitiveLog = _ => ({
..._,
..._.RestoreRequest && {
RestoreRequest: RestoreRequestFilterSensitiveLog(_.RestoreRequest)
}
}), SelectObjectContentOutputFilterSensitiveLog = _ => ({
..._,
..._.Payload && {
Payload: "STREAMING_CONTENT"
}
}), SelectObjectContentRequestFilterSensitiveLog = _ => ({
..._,
..._.SSECustomerKey && {
SSECustomerKey: SENSITIVE_STRING
}
}), UploadPartOutputFilterSensitiveLog = _ => ({
..._,
..._.SSEKMSKeyId && {
SSEKMSKeyId: SENSITIVE_STRING
}
}), UploadPartRequestFilterSensitiveLog = _ => ({
..._,
..._.SSECustomerKey && {
SSECustomerKey: SENSITIVE_STRING
}
}), UploadPartCopyOutputFilterSensitiveLog = _ => ({
..._,
..._.SSEKMSKeyId && {
SSEKMSKeyId: SENSITIVE_STRING
}
}), UploadPartCopyRequestFilterSensitiveLog = _ => ({
..._,
..._.SSECustomerKey && {
SSECustomerKey: SENSITIVE_STRING
},
..._.CopySourceSSECustomerKey && {
CopySourceSSECustomerKey: SENSITIVE_STRING
}
}), WriteGetObjectResponseRequestFilterSensitiveLog = _ => ({
..._,
..._.SSEKMSKeyId && {
SSEKMSKeyId: SENSITIVE_STRING
}
}), se_AbortMultipartUploadCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xarp]: _[_RP],
[_xaebo]: _[_EBO]
});
ne.bp("/{Key+}");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
ne.p("Key", (() => _.Key), "{Key+}", true);
const re = map({
[_xi]: [ , "AbortMultipartUpload" ],
[_uI]: [ , expectNonNull(_[_UI], "UploadId") ]
});
ne.m("DELETE").h(ie).q(re).b(void 0);
return ne.build();
}, se_CompleteMultipartUploadCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_xacc]: _[_CCRC],
[_xacc_]: _[_CCRCC],
[_xacs]: _[_CSHA],
[_xacs_]: _[_CSHAh],
[_xarp]: _[_RP],
[_xaebo]: _[_EBO],
[_xasseca]: _[_SSECA],
[_xasseck]: _[_SSECK],
[_xasseckm]: _[_SSECKMD]
});
ne.bp("/{Key+}");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
ne.p("Key", (() => _.Key), "{Key+}", true);
const re = map({
[_xi]: [ , "CompleteMultipartUpload" ],
[_uI]: [ , expectNonNull(_[_UI], "UploadId") ]
});
let se, oe;
if (void 0 !== _.MultipartUpload) {
oe = se_CompletedMultipartUpload(_.MultipartUpload, ee);
oe = oe.n("CompleteMultipartUpload");
se = _ve;
oe.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
se += oe.toString();
}
ne.m("POST").h(ie).q(re).b(se);
return ne.build();
}, se_CopyObjectCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xaa]: _[_ACL],
[_cc]: _[_CC],
[_xaca]: _[_CA],
[_cd]: _[_CD],
[_ce]: _[_CE],
[_cl]: _[_CL],
[_ct]: _[_CT],
[_xacs__]: _[_CS],
[_xacsim]: _[_CSIM],
[_xacsims]: [ () => isSerializableHeaderValue(_[_CSIMS]), () => dateToUtcString(_[_CSIMS]).toString() ],
[_xacsinm]: _[_CSINM],
[_xacsius]: [ () => isSerializableHeaderValue(_[_CSIUS]), () => dateToUtcString(_[_CSIUS]).toString() ],
[_e]: [ () => isSerializableHeaderValue(_[_E]), () => dateToUtcString(_[_E]).toString() ],
[_xagfc]: _[_GFC],
[_xagr]: _[_GR],
[_xagra]: _[_GRACP],
[_xagwa]: _[_GWACP],
[_xamd]: _[_MD],
[_xatd]: _[_TD],
[_xasse]: _[_SSE],
[_xasc]: _[_SC],
[_xawrl]: _[_WRL],
[_xasseca]: _[_SSECA],
[_xasseck]: _[_SSECK],
[_xasseckm]: _[_SSECKMD],
[_xasseakki]: _[_SSEKMSKI],
[_xassec]: _[_SSEKMSEC],
[_xassebke]: [ () => isSerializableHeaderValue(_[_BKE]), () => _[_BKE].toString() ],
[_xacssseca]: _[_CSSSECA],
[_xacssseck]: _[_CSSSECK],
[_xacssseckm]: _[_CSSSECKMD],
[_xarp]: _[_RP],
[_xat]: _[_T],
[_xaolm]: _[_OLM],
[_xaolrud]: [ () => isSerializableHeaderValue(_[_OLRUD]), () => (_[_OLRUD].toISOString().split(".")[0] + "Z").toString() ],
[_xaollh]: _[_OLLHS],
[_xaebo]: _[_EBO],
[_xasebo]: _[_ESBO],
...void 0 !== _.Metadata && Object.keys(_.Metadata).reduce(((ee, ne) => {
ee[`x-amz-meta-${ne.toLowerCase()}`] = _.Metadata[ne];
return ee;
}), {})
});
ne.bp("/{Key+}");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
ne.p("Key", (() => _.Key), "{Key+}", true);
const re = map({
[_xi]: [ , "CopyObject" ]
});
ne.m("PUT").h(ie).q(re).b(void 0);
return ne.build();
}, se_CreateBucketCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_xaa]: _[_ACL],
[_xagfc]: _[_GFC],
[_xagr]: _[_GR],
[_xagra]: _[_GRACP],
[_xagw]: _[_GW],
[_xagwa]: _[_GWACP],
[_xabole]: [ () => isSerializableHeaderValue(_[_OLEFB]), () => _[_OLEFB].toString() ],
[_xaoo]: _[_OO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
let re, se;
if (void 0 !== _.CreateBucketConfiguration) {
se = se_CreateBucketConfiguration(_.CreateBucketConfiguration, ee);
re = _ve;
se.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
re += se.toString();
}
ne.m("PUT").h(ie).b(re);
return ne.build();
}, se_CreateMultipartUploadCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xaa]: _[_ACL],
[_cc]: _[_CC],
[_cd]: _[_CD],
[_ce]: _[_CE],
[_cl]: _[_CL],
[_ct]: _[_CT],
[_e]: [ () => isSerializableHeaderValue(_[_E]), () => dateToUtcString(_[_E]).toString() ],
[_xagfc]: _[_GFC],
[_xagr]: _[_GR],
[_xagra]: _[_GRACP],
[_xagwa]: _[_GWACP],
[_xasse]: _[_SSE],
[_xasc]: _[_SC],
[_xawrl]: _[_WRL],
[_xasseca]: _[_SSECA],
[_xasseck]: _[_SSECK],
[_xasseckm]: _[_SSECKMD],
[_xasseakki]: _[_SSEKMSKI],
[_xassec]: _[_SSEKMSEC],
[_xassebke]: [ () => isSerializableHeaderValue(_[_BKE]), () => _[_BKE].toString() ],
[_xarp]: _[_RP],
[_xat]: _[_T],
[_xaolm]: _[_OLM],
[_xaolrud]: [ () => isSerializableHeaderValue(_[_OLRUD]), () => (_[_OLRUD].toISOString().split(".")[0] + "Z").toString() ],
[_xaollh]: _[_OLLHS],
[_xaebo]: _[_EBO],
[_xaca]: _[_CA],
...void 0 !== _.Metadata && Object.keys(_.Metadata).reduce(((ee, ne) => {
ee[`x-amz-meta-${ne.toLowerCase()}`] = _.Metadata[ne];
return ee;
}), {})
});
ne.bp("/{Key+}");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
ne.p("Key", (() => _.Key), "{Key+}", true);
const re = map({
[_u]: [ , "" ],
[_xi]: [ , "CreateMultipartUpload" ]
});
ne.m("POST").h(ie).q(re).b(void 0);
return ne.build();
}, se_CreateSessionCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xacsm]: _[_SM]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_s]: [ , "" ]
});
ne.m("GET").h(ie).q(re).b(void 0);
return ne.build();
}, se_DeleteBucketCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
ne.m("DELETE").h(ie).b(void 0);
return ne.build();
}, se_DeleteBucketAnalyticsConfigurationCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_a4]: [ , "" ],
[_i]: [ , expectNonNull(_[_I], "Id") ]
});
ne.m("DELETE").h(ie).q(re).b(void 0);
return ne.build();
}, se_DeleteBucketCorsCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_c]: [ , "" ]
});
ne.m("DELETE").h(ie).q(re).b(void 0);
return ne.build();
}, se_DeleteBucketEncryptionCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_en]: [ , "" ]
});
ne.m("DELETE").h(ie).q(re).b(void 0);
return ne.build();
}, se_DeleteBucketIntelligentTieringConfigurationCommand = async (_, ee) => {
const ne = requestBuilder(_, ee);
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const ie = map({
[_it]: [ , "" ],
[_i]: [ , expectNonNull(_[_I], "Id") ]
});
ne.m("DELETE").h({}).q(ie).b(void 0);
return ne.build();
}, se_DeleteBucketInventoryConfigurationCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_in]: [ , "" ],
[_i]: [ , expectNonNull(_[_I], "Id") ]
});
ne.m("DELETE").h(ie).q(re).b(void 0);
return ne.build();
}, se_DeleteBucketLifecycleCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_l]: [ , "" ]
});
ne.m("DELETE").h(ie).q(re).b(void 0);
return ne.build();
}, se_DeleteBucketMetricsConfigurationCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_m]: [ , "" ],
[_i]: [ , expectNonNull(_[_I], "Id") ]
});
ne.m("DELETE").h(ie).q(re).b(void 0);
return ne.build();
}, se_DeleteBucketOwnershipControlsCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_oC]: [ , "" ]
});
ne.m("DELETE").h(ie).q(re).b(void 0);
return ne.build();
}, se_DeleteBucketPolicyCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_p]: [ , "" ]
});
ne.m("DELETE").h(ie).q(re).b(void 0);
return ne.build();
}, se_DeleteBucketReplicationCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_r]: [ , "" ]
});
ne.m("DELETE").h(ie).q(re).b(void 0);
return ne.build();
}, se_DeleteBucketTaggingCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_t]: [ , "" ]
});
ne.m("DELETE").h(ie).q(re).b(void 0);
return ne.build();
}, se_DeleteBucketWebsiteCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_w]: [ , "" ]
});
ne.m("DELETE").h(ie).q(re).b(void 0);
return ne.build();
}, se_DeleteObjectCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xam]: _[_MFA],
[_xarp]: _[_RP],
[_xabgr]: [ () => isSerializableHeaderValue(_[_BGR]), () => _[_BGR].toString() ],
[_xaebo]: _[_EBO]
});
ne.bp("/{Key+}");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
ne.p("Key", (() => _.Key), "{Key+}", true);
const re = map({
[_xi]: [ , "DeleteObject" ],
[_vI]: [ , _[_VI] ]
});
ne.m("DELETE").h(ie).q(re).b(void 0);
return ne.build();
}, se_DeleteObjectsCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_xam]: _[_MFA],
[_xarp]: _[_RP],
[_xabgr]: [ () => isSerializableHeaderValue(_[_BGR]), () => _[_BGR].toString() ],
[_xaebo]: _[_EBO],
[_xasca]: _[_CA]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_d]: [ , "" ],
[_xi]: [ , "DeleteObjects" ]
});
let se, oe;
if (void 0 !== _.Delete) {
oe = se_Delete(_.Delete, ee);
se = _ve;
oe.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
se += oe.toString();
}
ne.m("POST").h(ie).q(re).b(se);
return ne.build();
}, se_DeleteObjectTaggingCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xaebo]: _[_EBO]
});
ne.bp("/{Key+}");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
ne.p("Key", (() => _.Key), "{Key+}", true);
const re = map({
[_t]: [ , "" ],
[_vI]: [ , _[_VI] ]
});
ne.m("DELETE").h(ie).q(re).b(void 0);
return ne.build();
}, se_DeletePublicAccessBlockCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_pAB]: [ , "" ]
});
ne.m("DELETE").h(ie).q(re).b(void 0);
return ne.build();
}, se_GetBucketAccelerateConfigurationCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xaebo]: _[_EBO],
[_xarp]: _[_RP]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_ac]: [ , "" ]
});
ne.m("GET").h(ie).q(re).b(void 0);
return ne.build();
}, se_GetBucketAclCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_acl]: [ , "" ]
});
ne.m("GET").h(ie).q(re).b(void 0);
return ne.build();
}, se_GetBucketAnalyticsConfigurationCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_a4]: [ , "" ],
[_xi]: [ , "GetBucketAnalyticsConfiguration" ],
[_i]: [ , expectNonNull(_[_I], "Id") ]
});
ne.m("GET").h(ie).q(re).b(void 0);
return ne.build();
}, se_GetBucketCorsCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_c]: [ , "" ]
});
ne.m("GET").h(ie).q(re).b(void 0);
return ne.build();
}, se_GetBucketEncryptionCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_en]: [ , "" ]
});
ne.m("GET").h(ie).q(re).b(void 0);
return ne.build();
}, se_GetBucketIntelligentTieringConfigurationCommand = async (_, ee) => {
const ne = requestBuilder(_, ee);
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const ie = map({
[_it]: [ , "" ],
[_xi]: [ , "GetBucketIntelligentTieringConfiguration" ],
[_i]: [ , expectNonNull(_[_I], "Id") ]
});
ne.m("GET").h({}).q(ie).b(void 0);
return ne.build();
}, se_GetBucketInventoryConfigurationCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_in]: [ , "" ],
[_xi]: [ , "GetBucketInventoryConfiguration" ],
[_i]: [ , expectNonNull(_[_I], "Id") ]
});
ne.m("GET").h(ie).q(re).b(void 0);
return ne.build();
}, se_GetBucketLifecycleConfigurationCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_l]: [ , "" ]
});
ne.m("GET").h(ie).q(re).b(void 0);
return ne.build();
}, se_GetBucketLocationCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_lo]: [ , "" ]
});
ne.m("GET").h(ie).q(re).b(void 0);
return ne.build();
}, se_GetBucketLoggingCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_log]: [ , "" ]
});
ne.m("GET").h(ie).q(re).b(void 0);
return ne.build();
}, se_GetBucketMetricsConfigurationCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_m]: [ , "" ],
[_xi]: [ , "GetBucketMetricsConfiguration" ],
[_i]: [ , expectNonNull(_[_I], "Id") ]
});
ne.m("GET").h(ie).q(re).b(void 0);
return ne.build();
}, se_GetBucketNotificationConfigurationCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_n]: [ , "" ]
});
ne.m("GET").h(ie).q(re).b(void 0);
return ne.build();
}, se_GetBucketOwnershipControlsCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_oC]: [ , "" ]
});
ne.m("GET").h(ie).q(re).b(void 0);
return ne.build();
}, se_GetBucketPolicyCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_p]: [ , "" ]
});
ne.m("GET").h(ie).q(re).b(void 0);
return ne.build();
}, se_GetBucketPolicyStatusCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_pS]: [ , "" ]
});
ne.m("GET").h(ie).q(re).b(void 0);
return ne.build();
}, se_GetBucketReplicationCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_r]: [ , "" ]
});
ne.m("GET").h(ie).q(re).b(void 0);
return ne.build();
}, se_GetBucketRequestPaymentCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_rP]: [ , "" ]
});
ne.m("GET").h(ie).q(re).b(void 0);
return ne.build();
}, se_GetBucketTaggingCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_t]: [ , "" ]
});
ne.m("GET").h(ie).q(re).b(void 0);
return ne.build();
}, se_GetBucketVersioningCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_v]: [ , "" ]
});
ne.m("GET").h(ie).q(re).b(void 0);
return ne.build();
}, se_GetBucketWebsiteCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_w]: [ , "" ]
});
ne.m("GET").h(ie).q(re).b(void 0);
return ne.build();
}, se_GetObjectCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_im]: _[_IM],
[_ims]: [ () => isSerializableHeaderValue(_[_IMS]), () => dateToUtcString(_[_IMS]).toString() ],
[_inm]: _[_INM],
[_ius]: [ () => isSerializableHeaderValue(_[_IUS]), () => dateToUtcString(_[_IUS]).toString() ],
[_ra]: _[_R],
[_xasseca]: _[_SSECA],
[_xasseck]: _[_SSECK],
[_xasseckm]: _[_SSECKMD],
[_xarp]: _[_RP],
[_xaebo]: _[_EBO],
[_xacm]: _[_CM]
});
ne.bp("/{Key+}");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
ne.p("Key", (() => _.Key), "{Key+}", true);
const re = map({
[_xi]: [ , "GetObject" ],
[_rcc]: [ , _[_RCC] ],
[_rcd]: [ , _[_RCD] ],
[_rce]: [ , _[_RCE] ],
[_rcl]: [ , _[_RCL] ],
[_rct]: [ , _[_RCT] ],
[_re]: [ () => void 0 !== _.ResponseExpires, () => dateToUtcString(_[_RE]).toString() ],
[_vI]: [ , _[_VI] ],
[_pN]: [ () => void 0 !== _.PartNumber, () => _[_PN].toString() ]
});
ne.m("GET").h(ie).q(re).b(void 0);
return ne.build();
}, se_GetObjectAclCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xarp]: _[_RP],
[_xaebo]: _[_EBO]
});
ne.bp("/{Key+}");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
ne.p("Key", (() => _.Key), "{Key+}", true);
const re = map({
[_acl]: [ , "" ],
[_vI]: [ , _[_VI] ]
});
ne.m("GET").h(ie).q(re).b(void 0);
return ne.build();
}, se_GetObjectAttributesCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xamp]: [ () => isSerializableHeaderValue(_[_MP]), () => _[_MP].toString() ],
[_xapnm]: _[_PNM],
[_xasseca]: _[_SSECA],
[_xasseck]: _[_SSECK],
[_xasseckm]: _[_SSECKMD],
[_xarp]: _[_RP],
[_xaebo]: _[_EBO],
[_xaoa]: [ () => isSerializableHeaderValue(_[_OA]), () => (_[_OA] || []).map((_ => _)).join(", ") ]
});
ne.bp("/{Key+}");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
ne.p("Key", (() => _.Key), "{Key+}", true);
const re = map({
[_at]: [ , "" ],
[_vI]: [ , _[_VI] ]
});
ne.m("GET").h(ie).q(re).b(void 0);
return ne.build();
}, se_GetObjectLegalHoldCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xarp]: _[_RP],
[_xaebo]: _[_EBO]
});
ne.bp("/{Key+}");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
ne.p("Key", (() => _.Key), "{Key+}", true);
const re = map({
[_lh]: [ , "" ],
[_vI]: [ , _[_VI] ]
});
ne.m("GET").h(ie).q(re).b(void 0);
return ne.build();
}, se_GetObjectLockConfigurationCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_ol]: [ , "" ]
});
ne.m("GET").h(ie).q(re).b(void 0);
return ne.build();
}, se_GetObjectRetentionCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xarp]: _[_RP],
[_xaebo]: _[_EBO]
});
ne.bp("/{Key+}");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
ne.p("Key", (() => _.Key), "{Key+}", true);
const re = map({
[_ret]: [ , "" ],
[_vI]: [ , _[_VI] ]
});
ne.m("GET").h(ie).q(re).b(void 0);
return ne.build();
}, se_GetObjectTaggingCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xaebo]: _[_EBO],
[_xarp]: _[_RP]
});
ne.bp("/{Key+}");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
ne.p("Key", (() => _.Key), "{Key+}", true);
const re = map({
[_t]: [ , "" ],
[_vI]: [ , _[_VI] ]
});
ne.m("GET").h(ie).q(re).b(void 0);
return ne.build();
}, se_GetObjectTorrentCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xarp]: _[_RP],
[_xaebo]: _[_EBO]
});
ne.bp("/{Key+}");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
ne.p("Key", (() => _.Key), "{Key+}", true);
const re = map({
[_to]: [ , "" ]
});
ne.m("GET").h(ie).q(re).b(void 0);
return ne.build();
}, se_GetPublicAccessBlockCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_pAB]: [ , "" ]
});
ne.m("GET").h(ie).q(re).b(void 0);
return ne.build();
}, se_HeadBucketCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
ne.m("HEAD").h(ie).b(void 0);
return ne.build();
}, se_HeadObjectCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_im]: _[_IM],
[_ims]: [ () => isSerializableHeaderValue(_[_IMS]), () => dateToUtcString(_[_IMS]).toString() ],
[_inm]: _[_INM],
[_ius]: [ () => isSerializableHeaderValue(_[_IUS]), () => dateToUtcString(_[_IUS]).toString() ],
[_ra]: _[_R],
[_xasseca]: _[_SSECA],
[_xasseck]: _[_SSECK],
[_xasseckm]: _[_SSECKMD],
[_xarp]: _[_RP],
[_xaebo]: _[_EBO],
[_xacm]: _[_CM]
});
ne.bp("/{Key+}");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
ne.p("Key", (() => _.Key), "{Key+}", true);
const re = map({
[_vI]: [ , _[_VI] ],
[_pN]: [ () => void 0 !== _.PartNumber, () => _[_PN].toString() ]
});
ne.m("HEAD").h(ie).q(re).b(void 0);
return ne.build();
}, se_ListBucketAnalyticsConfigurationsCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_a4]: [ , "" ],
[_xi]: [ , "ListBucketAnalyticsConfigurations" ],
[_ct_]: [ , _[_CTo] ]
});
ne.m("GET").h(ie).q(re).b(void 0);
return ne.build();
}, se_ListBucketIntelligentTieringConfigurationsCommand = async (_, ee) => {
const ne = requestBuilder(_, ee);
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const ie = map({
[_it]: [ , "" ],
[_xi]: [ , "ListBucketIntelligentTieringConfigurations" ],
[_ct_]: [ , _[_CTo] ]
});
ne.m("GET").h({}).q(ie).b(void 0);
return ne.build();
}, se_ListBucketInventoryConfigurationsCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_in]: [ , "" ],
[_xi]: [ , "ListBucketInventoryConfigurations" ],
[_ct_]: [ , _[_CTo] ]
});
ne.m("GET").h(ie).q(re).b(void 0);
return ne.build();
}, se_ListBucketMetricsConfigurationsCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_m]: [ , "" ],
[_xi]: [ , "ListBucketMetricsConfigurations" ],
[_ct_]: [ , _[_CTo] ]
});
ne.m("GET").h(ie).q(re).b(void 0);
return ne.build();
}, se_ListBucketsCommand = async (_, ee) => {
const ne = requestBuilder(_, ee);
ne.bp("/");
const ie = map({
[_xi]: [ , "ListBuckets" ]
});
let re;
re = "";
ne.m("GET").h({
"content-type": "application/xml"
}).q(ie).b("");
return ne.build();
}, se_ListDirectoryBucketsCommand = async (_, ee) => {
const ne = requestBuilder(_, ee);
ne.bp("/");
const ie = map({
[_xi]: [ , "ListDirectoryBuckets" ],
[_ct_]: [ , _[_CTo] ],
[_mdb]: [ () => void 0 !== _.MaxDirectoryBuckets, () => _[_MDB].toString() ]
});
ne.m("GET").h({}).q(ie).b(void 0);
return ne.build();
}, se_ListMultipartUploadsCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xaebo]: _[_EBO],
[_xarp]: _[_RP]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_u]: [ , "" ],
[_de]: [ , _[_D] ],
[_et]: [ , _[_ET] ],
[_km]: [ , _[_KM] ],
[_mu]: [ () => void 0 !== _.MaxUploads, () => _[_MU].toString() ],
[_pr]: [ , _[_P] ],
[_uim]: [ , _[_UIM] ]
});
ne.m("GET").h(ie).q(re).b(void 0);
return ne.build();
}, se_ListObjectsCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xarp]: _[_RP],
[_xaebo]: _[_EBO],
[_xaooa]: [ () => isSerializableHeaderValue(_[_OOA]), () => (_[_OOA] || []).map((_ => _)).join(", ") ]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_de]: [ , _[_D] ],
[_et]: [ , _[_ET] ],
[_ma]: [ , _[_M] ],
[_mk]: [ () => void 0 !== _.MaxKeys, () => _[_MK].toString() ],
[_pr]: [ , _[_P] ]
});
ne.m("GET").h(ie).q(re).b(void 0);
return ne.build();
}, se_ListObjectsV2Command = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xarp]: _[_RP],
[_xaebo]: _[_EBO],
[_xaooa]: [ () => isSerializableHeaderValue(_[_OOA]), () => (_[_OOA] || []).map((_ => _)).join(", ") ]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_lt]: [ , "2" ],
[_de]: [ , _[_D] ],
[_et]: [ , _[_ET] ],
[_mk]: [ () => void 0 !== _.MaxKeys, () => _[_MK].toString() ],
[_pr]: [ , _[_P] ],
[_ct_]: [ , _[_CTo] ],
[_fo]: [ () => void 0 !== _.FetchOwner, () => _[_FO].toString() ],
[_sa]: [ , _[_SA] ]
});
ne.m("GET").h(ie).q(re).b(void 0);
return ne.build();
}, se_ListObjectVersionsCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xaebo]: _[_EBO],
[_xarp]: _[_RP],
[_xaooa]: [ () => isSerializableHeaderValue(_[_OOA]), () => (_[_OOA] || []).map((_ => _)).join(", ") ]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_ver]: [ , "" ],
[_de]: [ , _[_D] ],
[_et]: [ , _[_ET] ],
[_km]: [ , _[_KM] ],
[_mk]: [ () => void 0 !== _.MaxKeys, () => _[_MK].toString() ],
[_pr]: [ , _[_P] ],
[_vim]: [ , _[_VIM] ]
});
ne.m("GET").h(ie).q(re).b(void 0);
return ne.build();
}, se_ListPartsCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xarp]: _[_RP],
[_xaebo]: _[_EBO],
[_xasseca]: _[_SSECA],
[_xasseck]: _[_SSECK],
[_xasseckm]: _[_SSECKMD]
});
ne.bp("/{Key+}");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
ne.p("Key", (() => _.Key), "{Key+}", true);
const re = map({
[_xi]: [ , "ListParts" ],
[_mp]: [ () => void 0 !== _.MaxParts, () => _[_MP].toString() ],
[_pnm]: [ , _[_PNM] ],
[_uI]: [ , expectNonNull(_[_UI], "UploadId") ]
});
ne.m("GET").h(ie).q(re).b(void 0);
return ne.build();
}, se_PutBucketAccelerateConfigurationCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_xaebo]: _[_EBO],
[_xasca]: _[_CA]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_ac]: [ , "" ]
});
let se, oe;
if (void 0 !== _.AccelerateConfiguration) {
oe = se_AccelerateConfiguration(_.AccelerateConfiguration, ee);
se = _ve;
oe.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
se += oe.toString();
}
ne.m("PUT").h(ie).q(re).b(se);
return ne.build();
}, se_PutBucketAclCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_xaa]: _[_ACL],
[_cm]: _[_CMD],
[_xasca]: _[_CA],
[_xagfc]: _[_GFC],
[_xagr]: _[_GR],
[_xagra]: _[_GRACP],
[_xagw]: _[_GW],
[_xagwa]: _[_GWACP],
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_acl]: [ , "" ]
});
let se, oe;
if (void 0 !== _.AccessControlPolicy) {
oe = se_AccessControlPolicy(_.AccessControlPolicy, ee);
se = _ve;
oe.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
se += oe.toString();
}
ne.m("PUT").h(ie).q(re).b(se);
return ne.build();
}, se_PutBucketAnalyticsConfigurationCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_a4]: [ , "" ],
[_i]: [ , expectNonNull(_[_I], "Id") ]
});
let se, oe;
if (void 0 !== _.AnalyticsConfiguration) {
oe = se_AnalyticsConfiguration(_.AnalyticsConfiguration, ee);
se = _ve;
oe.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
se += oe.toString();
}
ne.m("PUT").h(ie).q(re).b(se);
return ne.build();
}, se_PutBucketCorsCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_cm]: _[_CMD],
[_xasca]: _[_CA],
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_c]: [ , "" ]
});
let se, oe;
if (void 0 !== _.CORSConfiguration) {
oe = se_CORSConfiguration(_.CORSConfiguration, ee);
se = _ve;
oe.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
se += oe.toString();
}
ne.m("PUT").h(ie).q(re).b(se);
return ne.build();
}, se_PutBucketEncryptionCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_cm]: _[_CMD],
[_xasca]: _[_CA],
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_en]: [ , "" ]
});
let se, oe;
if (void 0 !== _.ServerSideEncryptionConfiguration) {
oe = se_ServerSideEncryptionConfiguration(_.ServerSideEncryptionConfiguration, ee);
se = _ve;
oe.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
se += oe.toString();
}
ne.m("PUT").h(ie).q(re).b(se);
return ne.build();
}, se_PutBucketIntelligentTieringConfigurationCommand = async (_, ee) => {
const ne = requestBuilder(_, ee);
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const ie = map({
[_it]: [ , "" ],
[_i]: [ , expectNonNull(_[_I], "Id") ]
});
let re, se;
if (void 0 !== _.IntelligentTieringConfiguration) {
se = se_IntelligentTieringConfiguration(_.IntelligentTieringConfiguration, ee);
re = _ve;
se.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
re += se.toString();
}
ne.m("PUT").h({
"content-type": "application/xml"
}).q(ie).b(re);
return ne.build();
}, se_PutBucketInventoryConfigurationCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_in]: [ , "" ],
[_i]: [ , expectNonNull(_[_I], "Id") ]
});
let se, oe;
if (void 0 !== _.InventoryConfiguration) {
oe = se_InventoryConfiguration(_.InventoryConfiguration, ee);
se = _ve;
oe.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
se += oe.toString();
}
ne.m("PUT").h(ie).q(re).b(se);
return ne.build();
}, se_PutBucketLifecycleConfigurationCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_xasca]: _[_CA],
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_l]: [ , "" ]
});
let se, oe;
if (void 0 !== _.LifecycleConfiguration) {
oe = se_BucketLifecycleConfiguration(_.LifecycleConfiguration, ee);
oe = oe.n("LifecycleConfiguration");
se = _ve;
oe.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
se += oe.toString();
}
ne.m("PUT").h(ie).q(re).b(se);
return ne.build();
}, se_PutBucketLoggingCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_cm]: _[_CMD],
[_xasca]: _[_CA],
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_log]: [ , "" ]
});
let se, oe;
if (void 0 !== _.BucketLoggingStatus) {
oe = se_BucketLoggingStatus(_.BucketLoggingStatus, ee);
se = _ve;
oe.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
se += oe.toString();
}
ne.m("PUT").h(ie).q(re).b(se);
return ne.build();
}, se_PutBucketMetricsConfigurationCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_m]: [ , "" ],
[_i]: [ , expectNonNull(_[_I], "Id") ]
});
let se, oe;
if (void 0 !== _.MetricsConfiguration) {
oe = se_MetricsConfiguration(_.MetricsConfiguration, ee);
se = _ve;
oe.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
se += oe.toString();
}
ne.m("PUT").h(ie).q(re).b(se);
return ne.build();
}, se_PutBucketNotificationConfigurationCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_xaebo]: _[_EBO],
[_xasdv]: [ () => isSerializableHeaderValue(_[_SDV]), () => _[_SDV].toString() ]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_n]: [ , "" ]
});
let se, oe;
if (void 0 !== _.NotificationConfiguration) {
oe = se_NotificationConfiguration(_.NotificationConfiguration, ee);
se = _ve;
oe.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
se += oe.toString();
}
ne.m("PUT").h(ie).q(re).b(se);
return ne.build();
}, se_PutBucketOwnershipControlsCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_cm]: _[_CMD],
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_oC]: [ , "" ]
});
let se, oe;
if (void 0 !== _.OwnershipControls) {
oe = se_OwnershipControls(_.OwnershipControls, ee);
se = _ve;
oe.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
se += oe.toString();
}
ne.m("PUT").h(ie).q(re).b(se);
return ne.build();
}, se_PutBucketPolicyCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
"content-type": "text/plain",
[_cm]: _[_CMD],
[_xasca]: _[_CA],
[_xacrsba]: [ () => isSerializableHeaderValue(_[_CRSBA]), () => _[_CRSBA].toString() ],
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_p]: [ , "" ]
});
let se, oe;
if (void 0 !== _.Policy) {
oe = _.Policy;
se = oe;
}
ne.m("PUT").h(ie).q(re).b(se);
return ne.build();
}, se_PutBucketReplicationCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_cm]: _[_CMD],
[_xasca]: _[_CA],
[_xabolt]: _[_To],
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_r]: [ , "" ]
});
let se, oe;
if (void 0 !== _.ReplicationConfiguration) {
oe = se_ReplicationConfiguration(_.ReplicationConfiguration, ee);
se = _ve;
oe.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
se += oe.toString();
}
ne.m("PUT").h(ie).q(re).b(se);
return ne.build();
}, se_PutBucketRequestPaymentCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_cm]: _[_CMD],
[_xasca]: _[_CA],
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_rP]: [ , "" ]
});
let se, oe;
if (void 0 !== _.RequestPaymentConfiguration) {
oe = se_RequestPaymentConfiguration(_.RequestPaymentConfiguration, ee);
se = _ve;
oe.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
se += oe.toString();
}
ne.m("PUT").h(ie).q(re).b(se);
return ne.build();
}, se_PutBucketTaggingCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_cm]: _[_CMD],
[_xasca]: _[_CA],
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_t]: [ , "" ]
});
let se, oe;
if (void 0 !== _.Tagging) {
oe = se_Tagging(_.Tagging, ee);
se = _ve;
oe.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
se += oe.toString();
}
ne.m("PUT").h(ie).q(re).b(se);
return ne.build();
}, se_PutBucketVersioningCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_cm]: _[_CMD],
[_xasca]: _[_CA],
[_xam]: _[_MFA],
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_v]: [ , "" ]
});
let se, oe;
if (void 0 !== _.VersioningConfiguration) {
oe = se_VersioningConfiguration(_.VersioningConfiguration, ee);
se = _ve;
oe.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
se += oe.toString();
}
ne.m("PUT").h(ie).q(re).b(se);
return ne.build();
}, se_PutBucketWebsiteCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_cm]: _[_CMD],
[_xasca]: _[_CA],
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_w]: [ , "" ]
});
let se, oe;
if (void 0 !== _.WebsiteConfiguration) {
oe = se_WebsiteConfiguration(_.WebsiteConfiguration, ee);
se = _ve;
oe.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
se += oe.toString();
}
ne.m("PUT").h(ie).q(re).b(se);
return ne.build();
}, se_PutObjectCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_ct]: _[_CT] || "application/octet-stream",
[_xaa]: _[_ACL],
[_cc]: _[_CC],
[_cd]: _[_CD],
[_ce]: _[_CE],
[_cl]: _[_CL],
[_cl_]: [ () => isSerializableHeaderValue(_[_CLo]), () => _[_CLo].toString() ],
[_cm]: _[_CMD],
[_xasca]: _[_CA],
[_xacc]: _[_CCRC],
[_xacc_]: _[_CCRCC],
[_xacs]: _[_CSHA],
[_xacs_]: _[_CSHAh],
[_e]: [ () => isSerializableHeaderValue(_[_E]), () => dateToUtcString(_[_E]).toString() ],
[_xagfc]: _[_GFC],
[_xagr]: _[_GR],
[_xagra]: _[_GRACP],
[_xagwa]: _[_GWACP],
[_xasse]: _[_SSE],
[_xasc]: _[_SC],
[_xawrl]: _[_WRL],
[_xasseca]: _[_SSECA],
[_xasseck]: _[_SSECK],
[_xasseckm]: _[_SSECKMD],
[_xasseakki]: _[_SSEKMSKI],
[_xassec]: _[_SSEKMSEC],
[_xassebke]: [ () => isSerializableHeaderValue(_[_BKE]), () => _[_BKE].toString() ],
[_xarp]: _[_RP],
[_xat]: _[_T],
[_xaolm]: _[_OLM],
[_xaolrud]: [ () => isSerializableHeaderValue(_[_OLRUD]), () => (_[_OLRUD].toISOString().split(".")[0] + "Z").toString() ],
[_xaollh]: _[_OLLHS],
[_xaebo]: _[_EBO],
...void 0 !== _.Metadata && Object.keys(_.Metadata).reduce(((ee, ne) => {
ee[`x-amz-meta-${ne.toLowerCase()}`] = _.Metadata[ne];
return ee;
}), {})
});
ne.bp("/{Key+}");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
ne.p("Key", (() => _.Key), "{Key+}", true);
const re = map({
[_xi]: [ , "PutObject" ]
});
let se, oe;
if (void 0 !== _.Body) {
oe = _.Body;
se = oe;
}
ne.m("PUT").h(ie).q(re).b(se);
return ne.build();
}, se_PutObjectAclCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_xaa]: _[_ACL],
[_cm]: _[_CMD],
[_xasca]: _[_CA],
[_xagfc]: _[_GFC],
[_xagr]: _[_GR],
[_xagra]: _[_GRACP],
[_xagw]: _[_GW],
[_xagwa]: _[_GWACP],
[_xarp]: _[_RP],
[_xaebo]: _[_EBO]
});
ne.bp("/{Key+}");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
ne.p("Key", (() => _.Key), "{Key+}", true);
const re = map({
[_acl]: [ , "" ],
[_vI]: [ , _[_VI] ]
});
let se, oe;
if (void 0 !== _.AccessControlPolicy) {
oe = se_AccessControlPolicy(_.AccessControlPolicy, ee);
se = _ve;
oe.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
se += oe.toString();
}
ne.m("PUT").h(ie).q(re).b(se);
return ne.build();
}, se_PutObjectLegalHoldCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_xarp]: _[_RP],
[_cm]: _[_CMD],
[_xasca]: _[_CA],
[_xaebo]: _[_EBO]
});
ne.bp("/{Key+}");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
ne.p("Key", (() => _.Key), "{Key+}", true);
const re = map({
[_lh]: [ , "" ],
[_vI]: [ , _[_VI] ]
});
let se, oe;
if (void 0 !== _.LegalHold) {
oe = se_ObjectLockLegalHold(_.LegalHold, ee);
oe = oe.n("LegalHold");
se = _ve;
oe.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
se += oe.toString();
}
ne.m("PUT").h(ie).q(re).b(se);
return ne.build();
}, se_PutObjectLockConfigurationCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_xarp]: _[_RP],
[_xabolt]: _[_To],
[_cm]: _[_CMD],
[_xasca]: _[_CA],
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_ol]: [ , "" ]
});
let se, oe;
if (void 0 !== _.ObjectLockConfiguration) {
oe = se_ObjectLockConfiguration(_.ObjectLockConfiguration, ee);
se = _ve;
oe.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
se += oe.toString();
}
ne.m("PUT").h(ie).q(re).b(se);
return ne.build();
}, se_PutObjectRetentionCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_xarp]: _[_RP],
[_xabgr]: [ () => isSerializableHeaderValue(_[_BGR]), () => _[_BGR].toString() ],
[_cm]: _[_CMD],
[_xasca]: _[_CA],
[_xaebo]: _[_EBO]
});
ne.bp("/{Key+}");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
ne.p("Key", (() => _.Key), "{Key+}", true);
const re = map({
[_ret]: [ , "" ],
[_vI]: [ , _[_VI] ]
});
let se, oe;
if (void 0 !== _.Retention) {
oe = se_ObjectLockRetention(_.Retention, ee);
oe = oe.n("Retention");
se = _ve;
oe.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
se += oe.toString();
}
ne.m("PUT").h(ie).q(re).b(se);
return ne.build();
}, se_PutObjectTaggingCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_cm]: _[_CMD],
[_xasca]: _[_CA],
[_xaebo]: _[_EBO],
[_xarp]: _[_RP]
});
ne.bp("/{Key+}");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
ne.p("Key", (() => _.Key), "{Key+}", true);
const re = map({
[_t]: [ , "" ],
[_vI]: [ , _[_VI] ]
});
let se, oe;
if (void 0 !== _.Tagging) {
oe = se_Tagging(_.Tagging, ee);
se = _ve;
oe.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
se += oe.toString();
}
ne.m("PUT").h(ie).q(re).b(se);
return ne.build();
}, se_PutPublicAccessBlockCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_cm]: _[_CMD],
[_xasca]: _[_CA],
[_xaebo]: _[_EBO]
});
ne.bp("/");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
const re = map({
[_pAB]: [ , "" ]
});
let se, oe;
if (void 0 !== _.PublicAccessBlockConfiguration) {
oe = se_PublicAccessBlockConfiguration(_.PublicAccessBlockConfiguration, ee);
se = _ve;
oe.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
se += oe.toString();
}
ne.m("PUT").h(ie).q(re).b(se);
return ne.build();
}, se_RestoreObjectCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_xarp]: _[_RP],
[_xasca]: _[_CA],
[_xaebo]: _[_EBO]
});
ne.bp("/{Key+}");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
ne.p("Key", (() => _.Key), "{Key+}", true);
const re = map({
[_res]: [ , "" ],
[_xi]: [ , "RestoreObject" ],
[_vI]: [ , _[_VI] ]
});
let se, oe;
if (void 0 !== _.RestoreRequest) {
oe = se_RestoreRequest(_.RestoreRequest, ee);
se = _ve;
oe.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
se += oe.toString();
}
ne.m("POST").h(ie).q(re).b(se);
return ne.build();
}, se_SelectObjectContentCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
"content-type": "application/xml",
[_xasseca]: _[_SSECA],
[_xasseck]: _[_SSECK],
[_xasseckm]: _[_SSECKMD],
[_xaebo]: _[_EBO]
});
ne.bp("/{Key+}");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
ne.p("Key", (() => _.Key), "{Key+}", true);
const re = map({
[_se]: [ , "" ],
[_st]: [ , "2" ],
[_xi]: [ , "SelectObjectContent" ]
});
let se;
se = _ve;
const oe = new XmlNode(_SOCR);
oe.a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/");
oe.cc(_, _Ex);
oe.cc(_, _ETx);
if (null != _[_IS]) oe.c(se_InputSerialization(_[_IS], ee).n(_IS));
if (null != _[_OS]) oe.c(se_OutputSerialization(_[_OS], ee).n(_OS));
if (null != _[_RPe]) oe.c(se_RequestProgress(_[_RPe], ee).n(_RPe));
if (null != _[_SR]) oe.c(se_ScanRange(_[_SR], ee).n(_SR));
se += oe.toString();
ne.m("POST").h(ie).q(re).b(se);
return ne.build();
}, se_UploadPartCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
"content-type": "application/octet-stream",
[_cl_]: [ () => isSerializableHeaderValue(_[_CLo]), () => _[_CLo].toString() ],
[_cm]: _[_CMD],
[_xasca]: _[_CA],
[_xacc]: _[_CCRC],
[_xacc_]: _[_CCRCC],
[_xacs]: _[_CSHA],
[_xacs_]: _[_CSHAh],
[_xasseca]: _[_SSECA],
[_xasseck]: _[_SSECK],
[_xasseckm]: _[_SSECKMD],
[_xarp]: _[_RP],
[_xaebo]: _[_EBO]
});
ne.bp("/{Key+}");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
ne.p("Key", (() => _.Key), "{Key+}", true);
const re = map({
[_xi]: [ , "UploadPart" ],
[_pN]: [ null != expectNonNull(_.PartNumber, "PartNumber"), () => _[_PN].toString() ],
[_uI]: [ , expectNonNull(_[_UI], "UploadId") ]
});
let se, oe;
if (void 0 !== _.Body) {
oe = _.Body;
se = oe;
}
ne.m("PUT").h(ie).q(re).b(se);
return ne.build();
}, se_UploadPartCopyCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
[_xacs__]: _[_CS],
[_xacsim]: _[_CSIM],
[_xacsims]: [ () => isSerializableHeaderValue(_[_CSIMS]), () => dateToUtcString(_[_CSIMS]).toString() ],
[_xacsinm]: _[_CSINM],
[_xacsius]: [ () => isSerializableHeaderValue(_[_CSIUS]), () => dateToUtcString(_[_CSIUS]).toString() ],
[_xacsr]: _[_CSR],
[_xasseca]: _[_SSECA],
[_xasseck]: _[_SSECK],
[_xasseckm]: _[_SSECKMD],
[_xacssseca]: _[_CSSSECA],
[_xacssseck]: _[_CSSSECK],
[_xacssseckm]: _[_CSSSECKMD],
[_xarp]: _[_RP],
[_xaebo]: _[_EBO],
[_xasebo]: _[_ESBO]
});
ne.bp("/{Key+}");
ne.p("Bucket", (() => _.Bucket), "{Bucket}", false);
ne.p("Key", (() => _.Key), "{Key+}", true);
const re = map({
[_xi]: [ , "UploadPartCopy" ],
[_pN]: [ null != expectNonNull(_.PartNumber, "PartNumber"), () => _[_PN].toString() ],
[_uI]: [ , expectNonNull(_[_UI], "UploadId") ]
});
ne.m("PUT").h(ie).q(re).b(void 0);
return ne.build();
}, se_WriteGetObjectResponseCommand = async (_, ee) => {
const ne = requestBuilder(_, ee), ie = map({}, isSerializableHeaderValue, {
"x-amz-content-sha256": "UNSIGNED-PAYLOAD",
"content-type": "application/octet-stream",
[_xarr]: _[_RR],
[_xart]: _[_RT],
[_xafs]: [ () => isSerializableHeaderValue(_[_SCt]), () => _[_SCt].toString() ],
[_xafec]: _[_EC],
[_xafem]: _[_EM],
[_xafhar]: _[_AR],
[_xafhcc]: _[_CC],
[_xafhcd]: _[_CD],
[_xafhce]: _[_CE],
[_xafhcl]: _[_CL],
[_cl_]: [ () => isSerializableHeaderValue(_[_CLo]), () => _[_CLo].toString() ],
[_xafhcr]: _[_CR],
[_xafhct]: _[_CT],
[_xafhxacc]: _[_CCRC],
[_xafhxacc_]: _[_CCRCC],
[_xafhxacs]: _[_CSHA],
[_xafhxacs_]: _[_CSHAh],
[_xafhxadm]: [ () => isSerializableHeaderValue(_[_DM]), () => _[_DM].toString() ],
[_xafhe]: _[_ETa],
[_xafhe_]: [ () => isSerializableHeaderValue(_[_E]), () => dateToUtcString(_[_E]).toString() ],
[_xafhxae]: _[_Exp],
[_xafhlm]: [ () => isSerializableHeaderValue(_[_LM]), () => dateToUtcString(_[_LM]).toString() ],
[_xafhxamm]: [ () => isSerializableHeaderValue(_[_MM]), () => _[_MM].toString() ],
[_xafhxaolm]: _[_OLM],
[_xafhxaollh]: _[_OLLHS],
[_xafhxaolrud]: [ () => isSerializableHeaderValue(_[_OLRUD]), () => (_[_OLRUD].toISOString().split(".")[0] + "Z").toString() ],
[_xafhxampc]: [ () => isSerializableHeaderValue(_[_PC]), () => _[_PC].toString() ],
[_xafhxars]: _[_RS],
[_xafhxarc]: _[_RC],
[_xafhxar]: _[_Re],
[_xafhxasse]: _[_SSE],
[_xafhxasseca]: _[_SSECA],
[_xafhxasseakki]: _[_SSEKMSKI],
[_xafhxasseckm]: _[_SSECKMD],
[_xafhxasc]: _[_SC],
[_xafhxatc]: [ () => isSerializableHeaderValue(_[_TC]), () => _[_TC].toString() ],
[_xafhxavi]: _[_VI],
[_xafhxassebke]: [ () => isSerializableHeaderValue(_[_BKE]), () => _[_BKE].toString() ],
...void 0 !== _.Metadata && Object.keys(_.Metadata).reduce(((ee, ne) => {
ee[`x-amz-meta-${ne.toLowerCase()}`] = _.Metadata[ne];
return ee;
}), {})
});
ne.bp("/WriteGetObjectResponse");
const re = map({
[_xi]: [ , "WriteGetObjectResponse" ]
});
let se, oe;
if (void 0 !== _.Body) {
oe = _.Body;
se = oe;
}
let {hostname: le} = await ee.endpoint();
if (true !== ee.disableHostPrefix) {
le = "{RequestRoute}." + le;
if (void 0 === _.RequestRoute) throw new Error("Empty value provided for input host prefix: RequestRoute.");
le = le.replace("{RequestRoute}", _.RequestRoute);
if (!isValidHostname(le)) throw new Error("ValidationError: prefixed hostname must be hostname compatible.");
}
ne.hn(le);
ne.m("POST").h(ie).q(re).b(se);
return ne.build();
}, de_AbortMultipartUploadCommand = async (_, ee) => {
if (204 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_),
[_RC]: [ , _.headers[_xarc] ]
});
await collectBody(_.body, ee);
return ne;
}, de_CompleteMultipartUploadCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_),
[_Exp]: [ , _.headers[_xae] ],
[_SSE]: [ , _.headers[_xasse] ],
[_VI]: [ , _.headers[_xavi] ],
[_SSEKMSKI]: [ , _.headers[_xasseakki] ],
[_BKE]: [ () => void 0 !== _.headers[_xassebke], () => parseBoolean(_.headers[_xassebke]) ],
[_RC]: [ , _.headers[_xarc] ]
}), ie = expectNonNull(expectObject(await parseXmlBody(_.body, ee)), "body");
if (null != ie[_B]) ne[_B] = expectString(ie[_B]);
if (null != ie[_CCRC]) ne[_CCRC] = expectString(ie[_CCRC]);
if (null != ie[_CCRCC]) ne[_CCRCC] = expectString(ie[_CCRCC]);
if (null != ie[_CSHA]) ne[_CSHA] = expectString(ie[_CSHA]);
if (null != ie[_CSHAh]) ne[_CSHAh] = expectString(ie[_CSHAh]);
if (null != ie[_ETa]) ne[_ETa] = expectString(ie[_ETa]);
if (null != ie[_K]) ne[_K] = expectString(ie[_K]);
if (null != ie[_L]) ne[_L] = expectString(ie[_L]);
return ne;
}, de_CopyObjectCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_),
[_Exp]: [ , _.headers[_xae] ],
[_CSVI]: [ , _.headers[_xacsvi] ],
[_VI]: [ , _.headers[_xavi] ],
[_SSE]: [ , _.headers[_xasse] ],
[_SSECA]: [ , _.headers[_xasseca] ],
[_SSECKMD]: [ , _.headers[_xasseckm] ],
[_SSEKMSKI]: [ , _.headers[_xasseakki] ],
[_SSEKMSEC]: [ , _.headers[_xassec] ],
[_BKE]: [ () => void 0 !== _.headers[_xassebke], () => parseBoolean(_.headers[_xassebke]) ],
[_RC]: [ , _.headers[_xarc] ]
}), ie = expectObject(await parseXmlBody(_.body, ee));
ne.CopyObjectResult = de_CopyObjectResult(ie, ee);
return ne;
}, de_CreateBucketCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_),
[_L]: [ , _.headers[_lo] ]
});
await collectBody(_.body, ee);
return ne;
}, de_CreateMultipartUploadCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_),
[_AD]: [ () => void 0 !== _.headers[_xaad], () => expectNonNull(parseRfc7231DateTime(_.headers[_xaad])) ],
[_ARI]: [ , _.headers[_xaari] ],
[_SSE]: [ , _.headers[_xasse] ],
[_SSECA]: [ , _.headers[_xasseca] ],
[_SSECKMD]: [ , _.headers[_xasseckm] ],
[_SSEKMSKI]: [ , _.headers[_xasseakki] ],
[_SSEKMSEC]: [ , _.headers[_xassec] ],
[_BKE]: [ () => void 0 !== _.headers[_xassebke], () => parseBoolean(_.headers[_xassebke]) ],
[_RC]: [ , _.headers[_xarc] ],
[_CA]: [ , _.headers[_xaca] ]
}), ie = expectNonNull(expectObject(await parseXmlBody(_.body, ee)), "body");
if (null != ie[_B]) ne[_B] = expectString(ie[_B]);
if (null != ie[_K]) ne[_K] = expectString(ie[_K]);
if (null != ie[_UI]) ne[_UI] = expectString(ie[_UI]);
return ne;
}, de_CreateSessionCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
}), ie = expectNonNull(expectObject(await parseXmlBody(_.body, ee)), "body");
if (null != ie[_C]) ne[_C] = de_SessionCredentials(ie[_C], ee);
return ne;
}, de_DeleteBucketCommand = async (_, ee) => {
if (204 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
});
await collectBody(_.body, ee);
return ne;
}, de_DeleteBucketAnalyticsConfigurationCommand = async (_, ee) => {
if (204 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
});
await collectBody(_.body, ee);
return ne;
}, de_DeleteBucketCorsCommand = async (_, ee) => {
if (204 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
});
await collectBody(_.body, ee);
return ne;
}, de_DeleteBucketEncryptionCommand = async (_, ee) => {
if (204 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
});
await collectBody(_.body, ee);
return ne;
}, de_DeleteBucketIntelligentTieringConfigurationCommand = async (_, ee) => {
if (204 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
});
await collectBody(_.body, ee);
return ne;
}, de_DeleteBucketInventoryConfigurationCommand = async (_, ee) => {
if (204 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
});
await collectBody(_.body, ee);
return ne;
}, de_DeleteBucketLifecycleCommand = async (_, ee) => {
if (204 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
});
await collectBody(_.body, ee);
return ne;
}, de_DeleteBucketMetricsConfigurationCommand = async (_, ee) => {
if (204 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
});
await collectBody(_.body, ee);
return ne;
}, de_DeleteBucketOwnershipControlsCommand = async (_, ee) => {
if (204 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
});
await collectBody(_.body, ee);
return ne;
}, de_DeleteBucketPolicyCommand = async (_, ee) => {
if (204 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
});
await collectBody(_.body, ee);
return ne;
}, de_DeleteBucketReplicationCommand = async (_, ee) => {
if (204 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
});
await collectBody(_.body, ee);
return ne;
}, de_DeleteBucketTaggingCommand = async (_, ee) => {
if (204 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
});
await collectBody(_.body, ee);
return ne;
}, de_DeleteBucketWebsiteCommand = async (_, ee) => {
if (204 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
});
await collectBody(_.body, ee);
return ne;
}, de_DeleteObjectCommand = async (_, ee) => {
if (204 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_),
[_DM]: [ () => void 0 !== _.headers[_xadm], () => parseBoolean(_.headers[_xadm]) ],
[_VI]: [ , _.headers[_xavi] ],
[_RC]: [ , _.headers[_xarc] ]
});
await collectBody(_.body, ee);
return ne;
}, de_DeleteObjectsCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_),
[_RC]: [ , _.headers[_xarc] ]
}), ie = expectNonNull(expectObject(await parseXmlBody(_.body, ee)), "body");
if ("" === ie.Deleted) ne[_De] = []; else if (null != ie[_De]) ne[_De] = de_DeletedObjects(getArrayIfSingleItem(ie[_De]), ee);
if ("" === ie.Error) ne[_Err] = []; else if (null != ie[_Er]) ne[_Err] = de_Errors(getArrayIfSingleItem(ie[_Er]), ee);
return ne;
}, de_DeleteObjectTaggingCommand = async (_, ee) => {
if (204 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_),
[_VI]: [ , _.headers[_xavi] ]
});
await collectBody(_.body, ee);
return ne;
}, de_DeletePublicAccessBlockCommand = async (_, ee) => {
if (204 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
});
await collectBody(_.body, ee);
return ne;
}, de_GetBucketAccelerateConfigurationCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_),
[_RC]: [ , _.headers[_xarc] ]
}), ie = expectNonNull(expectObject(await parseXmlBody(_.body, ee)), "body");
if (null != ie[_S]) ne[_S] = expectString(ie[_S]);
return ne;
}, de_GetBucketAclCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
}), ie = expectNonNull(expectObject(await parseXmlBody(_.body, ee)), "body");
if ("" === ie.AccessControlList) ne[_Gr] = []; else if (null != ie[_ACLc] && null != ie[_ACLc][_G]) ne[_Gr] = de_Grants(getArrayIfSingleItem(ie[_ACLc][_G]), ee);
if (null != ie[_O]) ne[_O] = de_Owner(ie[_O], ee);
return ne;
}, de_GetBucketAnalyticsConfigurationCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
}), ie = expectObject(await parseXmlBody(_.body, ee));
ne.AnalyticsConfiguration = de_AnalyticsConfiguration(ie, ee);
return ne;
}, de_GetBucketCorsCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
}), ie = expectNonNull(expectObject(await parseXmlBody(_.body, ee)), "body");
if ("" === ie.CORSRule) ne[_CORSRu] = []; else if (null != ie[_CORSR]) ne[_CORSRu] = de_CORSRules(getArrayIfSingleItem(ie[_CORSR]), ee);
return ne;
}, de_GetBucketEncryptionCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
}), ie = expectObject(await parseXmlBody(_.body, ee));
ne.ServerSideEncryptionConfiguration = de_ServerSideEncryptionConfiguration(ie, ee);
return ne;
}, de_GetBucketIntelligentTieringConfigurationCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
}), ie = expectObject(await parseXmlBody(_.body, ee));
ne.IntelligentTieringConfiguration = de_IntelligentTieringConfiguration(ie, ee);
return ne;
}, de_GetBucketInventoryConfigurationCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
}), ie = expectObject(await parseXmlBody(_.body, ee));
ne.InventoryConfiguration = de_InventoryConfiguration(ie, ee);
return ne;
}, de_GetBucketLifecycleConfigurationCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
}), ie = expectNonNull(expectObject(await parseXmlBody(_.body, ee)), "body");
if ("" === ie.Rule) ne[_Rul] = []; else if (null != ie[_Ru]) ne[_Rul] = de_LifecycleRules(getArrayIfSingleItem(ie[_Ru]), ee);
return ne;
}, de_GetBucketLocationCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
}), ie = expectNonNull(expectObject(await parseXmlBody(_.body, ee)), "body");
if (null != ie[_LC]) ne[_LC] = expectString(ie[_LC]);
return ne;
}, de_GetBucketLoggingCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
}), ie = expectNonNull(expectObject(await parseXmlBody(_.body, ee)), "body");
if (null != ie[_LE]) ne[_LE] = de_LoggingEnabled(ie[_LE], ee);
return ne;
}, de_GetBucketMetricsConfigurationCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
}), ie = expectObject(await parseXmlBody(_.body, ee));
ne.MetricsConfiguration = de_MetricsConfiguration(ie, ee);
return ne;
}, de_GetBucketNotificationConfigurationCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
}), ie = expectNonNull(expectObject(await parseXmlBody(_.body, ee)), "body");
if (null != ie[_EBC]) ne[_EBC] = de_EventBridgeConfiguration(ie[_EBC], ee);
if ("" === ie.CloudFunctionConfiguration) ne[_LFC] = []; else if (null != ie[_CFC]) ne[_LFC] = de_LambdaFunctionConfigurationList(getArrayIfSingleItem(ie[_CFC]), ee);
if ("" === ie.QueueConfiguration) ne[_QCu] = []; else if (null != ie[_QC]) ne[_QCu] = de_QueueConfigurationList(getArrayIfSingleItem(ie[_QC]), ee);
if ("" === ie.TopicConfiguration) ne[_TCop] = []; else if (null != ie[_TCo]) ne[_TCop] = de_TopicConfigurationList(getArrayIfSingleItem(ie[_TCo]), ee);
return ne;
}, de_GetBucketOwnershipControlsCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
}), ie = expectObject(await parseXmlBody(_.body, ee));
ne.OwnershipControls = de_OwnershipControls(ie, ee);
return ne;
}, de_GetBucketPolicyCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
}), ie = await collectBodyString3(_.body, ee);
ne.Policy = expectString(ie);
return ne;
}, de_GetBucketPolicyStatusCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
}), ie = expectObject(await parseXmlBody(_.body, ee));
ne.PolicyStatus = de_PolicyStatus(ie, ee);
return ne;
}, de_GetBucketReplicationCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
}), ie = expectObject(await parseXmlBody(_.body, ee));
ne.ReplicationConfiguration = de_ReplicationConfiguration(ie, ee);
return ne;
}, de_GetBucketRequestPaymentCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
}), ie = expectNonNull(expectObject(await parseXmlBody(_.body, ee)), "body");
if (null != ie[_Pa]) ne[_Pa] = expectString(ie[_Pa]);
return ne;
}, de_GetBucketTaggingCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
}), ie = expectNonNull(expectObject(await parseXmlBody(_.body, ee)), "body");
if ("" === ie.TagSet) ne[_TS] = []; else if (null != ie[_TS] && null != ie[_TS][_Ta]) ne[_TS] = de_TagSet(getArrayIfSingleItem(ie[_TS][_Ta]), ee);
return ne;
}, de_GetBucketVersioningCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
}), ie = expectNonNull(expectObject(await parseXmlBody(_.body, ee)), "body");
if (null != ie[_MDf]) ne[_MFAD] = expectString(ie[_MDf]);
if (null != ie[_S]) ne[_S] = expectString(ie[_S]);
return ne;
}, de_GetBucketWebsiteCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
}), ie = expectNonNull(expectObject(await parseXmlBody(_.body, ee)), "body");
if (null != ie[_ED]) ne[_ED] = de_ErrorDocument(ie[_ED], ee);
if (null != ie[_ID]) ne[_ID] = de_IndexDocument(ie[_ID], ee);
if (null != ie[_RART]) ne[_RART] = de_RedirectAllRequestsTo(ie[_RART], ee);
if ("" === ie.RoutingRules) ne[_RRo] = []; else if (null != ie[_RRo] && null != ie[_RRo][_RRou]) ne[_RRo] = de_RoutingRules(getArrayIfSingleItem(ie[_RRo][_RRou]), ee);
return ne;
}, de_GetObjectCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_),
[_DM]: [ () => void 0 !== _.headers[_xadm], () => parseBoolean(_.headers[_xadm]) ],
[_AR]: [ , _.headers[_ar] ],
[_Exp]: [ , _.headers[_xae] ],
[_Re]: [ , _.headers[_xar] ],
[_LM]: [ () => void 0 !== _.headers[_lm], () => expectNonNull(parseRfc7231DateTime(_.headers[_lm])) ],
[_CLo]: [ () => void 0 !== _.headers[_cl_], () => strictParseLong(_.headers[_cl_]) ],
[_ETa]: [ , _.headers[_eta] ],
[_CCRC]: [ , _.headers[_xacc] ],
[_CCRCC]: [ , _.headers[_xacc_] ],
[_CSHA]: [ , _.headers[_xacs] ],
[_CSHAh]: [ , _.headers[_xacs_] ],
[_MM]: [ () => void 0 !== _.headers[_xamm], () => strictParseInt32(_.headers[_xamm]) ],
[_VI]: [ , _.headers[_xavi] ],
[_CC]: [ , _.headers[_cc] ],
[_CD]: [ , _.headers[_cd] ],
[_CE]: [ , _.headers[_ce] ],
[_CL]: [ , _.headers[_cl] ],
[_CR]: [ , _.headers[_cr] ],
[_CT]: [ , _.headers[_ct] ],
[_E]: [ () => void 0 !== _.headers[_e], () => expectNonNull(parseRfc7231DateTime(_.headers[_e])) ],
[_ES]: [ , _.headers[_ex] ],
[_WRL]: [ , _.headers[_xawrl] ],
[_SSE]: [ , _.headers[_xasse] ],
[_SSECA]: [ , _.headers[_xasseca] ],
[_SSECKMD]: [ , _.headers[_xasseckm] ],
[_SSEKMSKI]: [ , _.headers[_xasseakki] ],
[_BKE]: [ () => void 0 !== _.headers[_xassebke], () => parseBoolean(_.headers[_xassebke]) ],
[_SC]: [ , _.headers[_xasc] ],
[_RC]: [ , _.headers[_xarc] ],
[_RS]: [ , _.headers[_xars] ],
[_PC]: [ () => void 0 !== _.headers[_xampc], () => strictParseInt32(_.headers[_xampc]) ],
[_TC]: [ () => void 0 !== _.headers[_xatc], () => strictParseInt32(_.headers[_xatc]) ],
[_OLM]: [ , _.headers[_xaolm] ],
[_OLRUD]: [ () => void 0 !== _.headers[_xaolrud], () => expectNonNull(parseRfc3339DateTimeWithOffset(_.headers[_xaolrud])) ],
[_OLLHS]: [ , _.headers[_xaollh] ],
Metadata: [ , Object.keys(_.headers).filter((_ => _.startsWith("x-amz-meta-"))).reduce(((ee, ne) => {
ee[ne.substring(11)] = _.headers[ne];
return ee;
}), {}) ]
}), ie = _.body;
ee.sdkStreamMixin(ie);
ne.Body = ie;
return ne;
}, de_GetObjectAclCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_),
[_RC]: [ , _.headers[_xarc] ]
}), ie = expectNonNull(expectObject(await parseXmlBody(_.body, ee)), "body");
if ("" === ie.AccessControlList) ne[_Gr] = []; else if (null != ie[_ACLc] && null != ie[_ACLc][_G]) ne[_Gr] = de_Grants(getArrayIfSingleItem(ie[_ACLc][_G]), ee);
if (null != ie[_O]) ne[_O] = de_Owner(ie[_O], ee);
return ne;
}, de_GetObjectAttributesCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_),
[_DM]: [ () => void 0 !== _.headers[_xadm], () => parseBoolean(_.headers[_xadm]) ],
[_LM]: [ () => void 0 !== _.headers[_lm], () => expectNonNull(parseRfc7231DateTime(_.headers[_lm])) ],
[_VI]: [ , _.headers[_xavi] ],
[_RC]: [ , _.headers[_xarc] ]
}), ie = expectNonNull(expectObject(await parseXmlBody(_.body, ee)), "body");
if (null != ie[_Ch]) ne[_Ch] = de_Checksum(ie[_Ch], ee);
if (null != ie[_ETa]) ne[_ETa] = expectString(ie[_ETa]);
if (null != ie[_OP]) ne[_OP] = de_GetObjectAttributesParts(ie[_OP], ee);
if (null != ie[_OSb]) ne[_OSb] = strictParseLong(ie[_OSb]);
if (null != ie[_SC]) ne[_SC] = expectString(ie[_SC]);
return ne;
}, de_GetObjectLegalHoldCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
}), ie = expectObject(await parseXmlBody(_.body, ee));
ne.LegalHold = de_ObjectLockLegalHold(ie, ee);
return ne;
}, de_GetObjectLockConfigurationCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
}), ie = expectObject(await parseXmlBody(_.body, ee));
ne.ObjectLockConfiguration = de_ObjectLockConfiguration(ie, ee);
return ne;
}, de_GetObjectRetentionCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
}), ie = expectObject(await parseXmlBody(_.body, ee));
ne.Retention = de_ObjectLockRetention(ie, ee);
return ne;
}, de_GetObjectTaggingCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_),
[_VI]: [ , _.headers[_xavi] ]
}), ie = expectNonNull(expectObject(await parseXmlBody(_.body, ee)), "body");
if ("" === ie.TagSet) ne[_TS] = []; else if (null != ie[_TS] && null != ie[_TS][_Ta]) ne[_TS] = de_TagSet(getArrayIfSingleItem(ie[_TS][_Ta]), ee);
return ne;
}, de_GetObjectTorrentCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_),
[_RC]: [ , _.headers[_xarc] ]
}), ie = _.body;
ee.sdkStreamMixin(ie);
ne.Body = ie;
return ne;
}, de_GetPublicAccessBlockCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
}), ie = expectObject(await parseXmlBody(_.body, ee));
ne.PublicAccessBlockConfiguration = de_PublicAccessBlockConfiguration(ie, ee);
return ne;
}, de_HeadBucketCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_),
[_BLT]: [ , _.headers[_xablt] ],
[_BLN]: [ , _.headers[_xabln] ],
[_BR]: [ , _.headers[_xabr] ],
[_APA]: [ () => void 0 !== _.headers[_xaapa], () => parseBoolean(_.headers[_xaapa]) ]
});
await collectBody(_.body, ee);
return ne;
}, de_HeadObjectCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_),
[_DM]: [ () => void 0 !== _.headers[_xadm], () => parseBoolean(_.headers[_xadm]) ],
[_AR]: [ , _.headers[_ar] ],
[_Exp]: [ , _.headers[_xae] ],
[_Re]: [ , _.headers[_xar] ],
[_AS]: [ , _.headers[_xaas] ],
[_LM]: [ () => void 0 !== _.headers[_lm], () => expectNonNull(parseRfc7231DateTime(_.headers[_lm])) ],
[_CLo]: [ () => void 0 !== _.headers[_cl_], () => strictParseLong(_.headers[_cl_]) ],
[_CCRC]: [ , _.headers[_xacc] ],
[_CCRCC]: [ , _.headers[_xacc_] ],
[_CSHA]: [ , _.headers[_xacs] ],
[_CSHAh]: [ , _.headers[_xacs_] ],
[_ETa]: [ , _.headers[_eta] ],
[_MM]: [ () => void 0 !== _.headers[_xamm], () => strictParseInt32(_.headers[_xamm]) ],
[_VI]: [ , _.headers[_xavi] ],
[_CC]: [ , _.headers[_cc] ],
[_CD]: [ , _.headers[_cd] ],
[_CE]: [ , _.headers[_ce] ],
[_CL]: [ , _.headers[_cl] ],
[_CT]: [ , _.headers[_ct] ],
[_E]: [ () => void 0 !== _.headers[_e], () => expectNonNull(parseRfc7231DateTime(_.headers[_e])) ],
[_ES]: [ , _.headers[_ex] ],
[_WRL]: [ , _.headers[_xawrl] ],
[_SSE]: [ , _.headers[_xasse] ],
[_SSECA]: [ , _.headers[_xasseca] ],
[_SSECKMD]: [ , _.headers[_xasseckm] ],
[_SSEKMSKI]: [ , _.headers[_xasseakki] ],
[_BKE]: [ () => void 0 !== _.headers[_xassebke], () => parseBoolean(_.headers[_xassebke]) ],
[_SC]: [ , _.headers[_xasc] ],
[_RC]: [ , _.headers[_xarc] ],
[_RS]: [ , _.headers[_xars] ],
[_PC]: [ () => void 0 !== _.headers[_xampc], () => strictParseInt32(_.headers[_xampc]) ],
[_OLM]: [ , _.headers[_xaolm] ],
[_OLRUD]: [ () => void 0 !== _.headers[_xaolrud], () => expectNonNull(parseRfc3339DateTimeWithOffset(_.headers[_xaolrud])) ],
[_OLLHS]: [ , _.headers[_xaollh] ],
Metadata: [ , Object.keys(_.headers).filter((_ => _.startsWith("x-amz-meta-"))).reduce(((ee, ne) => {
ee[ne.substring(11)] = _.headers[ne];
return ee;
}), {}) ]
});
await collectBody(_.body, ee);
return ne;
}, de_ListBucketAnalyticsConfigurationsCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
}), ie = expectNonNull(expectObject(await parseXmlBody(_.body, ee)), "body");
if ("" === ie.AnalyticsConfiguration) ne[_ACLn] = []; else if (null != ie[_AC]) ne[_ACLn] = de_AnalyticsConfigurationList(getArrayIfSingleItem(ie[_AC]), ee);
if (null != ie[_CTo]) ne[_CTo] = expectString(ie[_CTo]);
if (null != ie[_IT]) ne[_IT] = parseBoolean(ie[_IT]);
if (null != ie[_NCT]) ne[_NCT] = expectString(ie[_NCT]);
return ne;
}, de_ListBucketIntelligentTieringConfigurationsCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
}), ie = expectNonNull(expectObject(await parseXmlBody(_.body, ee)), "body");
if (null != ie[_CTo]) ne[_CTo] = expectString(ie[_CTo]);
if ("" === ie.IntelligentTieringConfiguration) ne[_ITCL] = []; else if (null != ie[_ITC]) ne[_ITCL] = de_IntelligentTieringConfigurationList(getArrayIfSingleItem(ie[_ITC]), ee);
if (null != ie[_IT]) ne[_IT] = parseBoolean(ie[_IT]);
if (null != ie[_NCT]) ne[_NCT] = expectString(ie[_NCT]);
return ne;
}, de_ListBucketInventoryConfigurationsCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
}), ie = expectNonNull(expectObject(await parseXmlBody(_.body, ee)), "body");
if (null != ie[_CTo]) ne[_CTo] = expectString(ie[_CTo]);
if ("" === ie.InventoryConfiguration) ne[_ICL] = []; else if (null != ie[_IC]) ne[_ICL] = de_InventoryConfigurationList(getArrayIfSingleItem(ie[_IC]), ee);
if (null != ie[_IT]) ne[_IT] = parseBoolean(ie[_IT]);
if (null != ie[_NCT]) ne[_NCT] = expectString(ie[_NCT]);
return ne;
}, de_ListBucketMetricsConfigurationsCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
}), ie = expectNonNull(expectObject(await parseXmlBody(_.body, ee)), "body");
if (null != ie[_CTo]) ne[_CTo] = expectString(ie[_CTo]);
if (null != ie[_IT]) ne[_IT] = parseBoolean(ie[_IT]);
if ("" === ie.MetricsConfiguration) ne[_MCL] = []; else if (null != ie[_MC]) ne[_MCL] = de_MetricsConfigurationList(getArrayIfSingleItem(ie[_MC]), ee);
if (null != ie[_NCT]) ne[_NCT] = expectString(ie[_NCT]);
return ne;
}, de_ListBucketsCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
}), ie = expectNonNull(expectObject(await parseXmlBody(_.body, ee)), "body");
if ("" === ie.Buckets) ne[_Bu] = []; else if (null != ie[_Bu] && null != ie[_Bu][_B]) ne[_Bu] = de_Buckets(getArrayIfSingleItem(ie[_Bu][_B]), ee);
if (null != ie[_O]) ne[_O] = de_Owner(ie[_O], ee);
return ne;
}, de_ListDirectoryBucketsCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
}), ie = expectNonNull(expectObject(await parseXmlBody(_.body, ee)), "body");
if ("" === ie.Buckets) ne[_Bu] = []; else if (null != ie[_Bu] && null != ie[_Bu][_B]) ne[_Bu] = de_Buckets(getArrayIfSingleItem(ie[_Bu][_B]), ee);
if (null != ie[_CTo]) ne[_CTo] = expectString(ie[_CTo]);
return ne;
}, de_ListMultipartUploadsCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_),
[_RC]: [ , _.headers[_xarc] ]
}), ie = expectNonNull(expectObject(await parseXmlBody(_.body, ee)), "body");
if (null != ie[_B]) ne[_B] = expectString(ie[_B]);
if ("" === ie.CommonPrefixes) ne[_CP] = []; else if (null != ie[_CP]) ne[_CP] = de_CommonPrefixList(getArrayIfSingleItem(ie[_CP]), ee);
if (null != ie[_D]) ne[_D] = expectString(ie[_D]);
if (null != ie[_ET]) ne[_ET] = expectString(ie[_ET]);
if (null != ie[_IT]) ne[_IT] = parseBoolean(ie[_IT]);
if (null != ie[_KM]) ne[_KM] = expectString(ie[_KM]);
if (null != ie[_MU]) ne[_MU] = strictParseInt32(ie[_MU]);
if (null != ie[_NKM]) ne[_NKM] = expectString(ie[_NKM]);
if (null != ie[_NUIM]) ne[_NUIM] = expectString(ie[_NUIM]);
if (null != ie[_P]) ne[_P] = expectString(ie[_P]);
if (null != ie[_UIM]) ne[_UIM] = expectString(ie[_UIM]);
if ("" === ie.Upload) ne[_Up] = []; else if (null != ie[_U]) ne[_Up] = de_MultipartUploadList(getArrayIfSingleItem(ie[_U]), ee);
return ne;
}, de_ListObjectsCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_),
[_RC]: [ , _.headers[_xarc] ]
}), ie = expectNonNull(expectObject(await parseXmlBody(_.body, ee)), "body");
if ("" === ie.CommonPrefixes) ne[_CP] = []; else if (null != ie[_CP]) ne[_CP] = de_CommonPrefixList(getArrayIfSingleItem(ie[_CP]), ee);
if ("" === ie.Contents) ne[_Co] = []; else if (null != ie[_Co]) ne[_Co] = de_ObjectList(getArrayIfSingleItem(ie[_Co]), ee);
if (null != ie[_D]) ne[_D] = expectString(ie[_D]);
if (null != ie[_ET]) ne[_ET] = expectString(ie[_ET]);
if (null != ie[_IT]) ne[_IT] = parseBoolean(ie[_IT]);
if (null != ie[_M]) ne[_M] = expectString(ie[_M]);
if (null != ie[_MK]) ne[_MK] = strictParseInt32(ie[_MK]);
if (null != ie[_N]) ne[_N] = expectString(ie[_N]);
if (null != ie[_NM]) ne[_NM] = expectString(ie[_NM]);
if (null != ie[_P]) ne[_P] = expectString(ie[_P]);
return ne;
}, de_ListObjectsV2Command = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_),
[_RC]: [ , _.headers[_xarc] ]
}), ie = expectNonNull(expectObject(await parseXmlBody(_.body, ee)), "body");
if ("" === ie.CommonPrefixes) ne[_CP] = []; else if (null != ie[_CP]) ne[_CP] = de_CommonPrefixList(getArrayIfSingleItem(ie[_CP]), ee);
if ("" === ie.Contents) ne[_Co] = []; else if (null != ie[_Co]) ne[_Co] = de_ObjectList(getArrayIfSingleItem(ie[_Co]), ee);
if (null != ie[_CTo]) ne[_CTo] = expectString(ie[_CTo]);
if (null != ie[_D]) ne[_D] = expectString(ie[_D]);
if (null != ie[_ET]) ne[_ET] = expectString(ie[_ET]);
if (null != ie[_IT]) ne[_IT] = parseBoolean(ie[_IT]);
if (null != ie[_KC]) ne[_KC] = strictParseInt32(ie[_KC]);
if (null != ie[_MK]) ne[_MK] = strictParseInt32(ie[_MK]);
if (null != ie[_N]) ne[_N] = expectString(ie[_N]);
if (null != ie[_NCT]) ne[_NCT] = expectString(ie[_NCT]);
if (null != ie[_P]) ne[_P] = expectString(ie[_P]);
if (null != ie[_SA]) ne[_SA] = expectString(ie[_SA]);
return ne;
}, de_ListObjectVersionsCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_),
[_RC]: [ , _.headers[_xarc] ]
}), ie = expectNonNull(expectObject(await parseXmlBody(_.body, ee)), "body");
if ("" === ie.CommonPrefixes) ne[_CP] = []; else if (null != ie[_CP]) ne[_CP] = de_CommonPrefixList(getArrayIfSingleItem(ie[_CP]), ee);
if ("" === ie.DeleteMarker) ne[_DMe] = []; else if (null != ie[_DM]) ne[_DMe] = de_DeleteMarkers(getArrayIfSingleItem(ie[_DM]), ee);
if (null != ie[_D]) ne[_D] = expectString(ie[_D]);
if (null != ie[_ET]) ne[_ET] = expectString(ie[_ET]);
if (null != ie[_IT]) ne[_IT] = parseBoolean(ie[_IT]);
if (null != ie[_KM]) ne[_KM] = expectString(ie[_KM]);
if (null != ie[_MK]) ne[_MK] = strictParseInt32(ie[_MK]);
if (null != ie[_N]) ne[_N] = expectString(ie[_N]);
if (null != ie[_NKM]) ne[_NKM] = expectString(ie[_NKM]);
if (null != ie[_NVIM]) ne[_NVIM] = expectString(ie[_NVIM]);
if (null != ie[_P]) ne[_P] = expectString(ie[_P]);
if (null != ie[_VIM]) ne[_VIM] = expectString(ie[_VIM]);
if ("" === ie.Version) ne[_Ve] = []; else if (null != ie[_V]) ne[_Ve] = de_ObjectVersionList(getArrayIfSingleItem(ie[_V]), ee);
return ne;
}, de_ListPartsCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_),
[_AD]: [ () => void 0 !== _.headers[_xaad], () => expectNonNull(parseRfc7231DateTime(_.headers[_xaad])) ],
[_ARI]: [ , _.headers[_xaari] ],
[_RC]: [ , _.headers[_xarc] ]
}), ie = expectNonNull(expectObject(await parseXmlBody(_.body, ee)), "body");
if (null != ie[_B]) ne[_B] = expectString(ie[_B]);
if (null != ie[_CA]) ne[_CA] = expectString(ie[_CA]);
if (null != ie[_In]) ne[_In] = de_Initiator(ie[_In], ee);
if (null != ie[_IT]) ne[_IT] = parseBoolean(ie[_IT]);
if (null != ie[_K]) ne[_K] = expectString(ie[_K]);
if (null != ie[_MP]) ne[_MP] = strictParseInt32(ie[_MP]);
if (null != ie[_NPNM]) ne[_NPNM] = expectString(ie[_NPNM]);
if (null != ie[_O]) ne[_O] = de_Owner(ie[_O], ee);
if (null != ie[_PNM]) ne[_PNM] = expectString(ie[_PNM]);
if ("" === ie.Part) ne[_Part] = []; else if (null != ie[_Par]) ne[_Part] = de_Parts(getArrayIfSingleItem(ie[_Par]), ee);
if (null != ie[_SC]) ne[_SC] = expectString(ie[_SC]);
if (null != ie[_UI]) ne[_UI] = expectString(ie[_UI]);
return ne;
}, de_PutBucketAccelerateConfigurationCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
});
await collectBody(_.body, ee);
return ne;
}, de_PutBucketAclCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
});
await collectBody(_.body, ee);
return ne;
}, de_PutBucketAnalyticsConfigurationCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
});
await collectBody(_.body, ee);
return ne;
}, de_PutBucketCorsCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
});
await collectBody(_.body, ee);
return ne;
}, de_PutBucketEncryptionCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
});
await collectBody(_.body, ee);
return ne;
}, de_PutBucketIntelligentTieringConfigurationCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
});
await collectBody(_.body, ee);
return ne;
}, de_PutBucketInventoryConfigurationCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
});
await collectBody(_.body, ee);
return ne;
}, de_PutBucketLifecycleConfigurationCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
});
await collectBody(_.body, ee);
return ne;
}, de_PutBucketLoggingCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
});
await collectBody(_.body, ee);
return ne;
}, de_PutBucketMetricsConfigurationCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
});
await collectBody(_.body, ee);
return ne;
}, de_PutBucketNotificationConfigurationCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
});
await collectBody(_.body, ee);
return ne;
}, de_PutBucketOwnershipControlsCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
});
await collectBody(_.body, ee);
return ne;
}, de_PutBucketPolicyCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
});
await collectBody(_.body, ee);
return ne;
}, de_PutBucketReplicationCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
});
await collectBody(_.body, ee);
return ne;
}, de_PutBucketRequestPaymentCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
});
await collectBody(_.body, ee);
return ne;
}, de_PutBucketTaggingCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
});
await collectBody(_.body, ee);
return ne;
}, de_PutBucketVersioningCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
});
await collectBody(_.body, ee);
return ne;
}, de_PutBucketWebsiteCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
});
await collectBody(_.body, ee);
return ne;
}, de_PutObjectCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_),
[_Exp]: [ , _.headers[_xae] ],
[_ETa]: [ , _.headers[_eta] ],
[_CCRC]: [ , _.headers[_xacc] ],
[_CCRCC]: [ , _.headers[_xacc_] ],
[_CSHA]: [ , _.headers[_xacs] ],
[_CSHAh]: [ , _.headers[_xacs_] ],
[_SSE]: [ , _.headers[_xasse] ],
[_VI]: [ , _.headers[_xavi] ],
[_SSECA]: [ , _.headers[_xasseca] ],
[_SSECKMD]: [ , _.headers[_xasseckm] ],
[_SSEKMSKI]: [ , _.headers[_xasseakki] ],
[_SSEKMSEC]: [ , _.headers[_xassec] ],
[_BKE]: [ () => void 0 !== _.headers[_xassebke], () => parseBoolean(_.headers[_xassebke]) ],
[_RC]: [ , _.headers[_xarc] ]
});
await collectBody(_.body, ee);
return ne;
}, de_PutObjectAclCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_),
[_RC]: [ , _.headers[_xarc] ]
});
await collectBody(_.body, ee);
return ne;
}, de_PutObjectLegalHoldCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_),
[_RC]: [ , _.headers[_xarc] ]
});
await collectBody(_.body, ee);
return ne;
}, de_PutObjectLockConfigurationCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_),
[_RC]: [ , _.headers[_xarc] ]
});
await collectBody(_.body, ee);
return ne;
}, de_PutObjectRetentionCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_),
[_RC]: [ , _.headers[_xarc] ]
});
await collectBody(_.body, ee);
return ne;
}, de_PutObjectTaggingCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_),
[_VI]: [ , _.headers[_xavi] ]
});
await collectBody(_.body, ee);
return ne;
}, de_PutPublicAccessBlockCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
});
await collectBody(_.body, ee);
return ne;
}, de_RestoreObjectCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_),
[_RC]: [ , _.headers[_xarc] ],
[_ROP]: [ , _.headers[_xarop] ]
});
await collectBody(_.body, ee);
return ne;
}, de_SelectObjectContentCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
}), ie = _.body;
ne.Payload = de_SelectObjectContentEventStream(ie, ee);
return ne;
}, de_UploadPartCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_),
[_SSE]: [ , _.headers[_xasse] ],
[_ETa]: [ , _.headers[_eta] ],
[_CCRC]: [ , _.headers[_xacc] ],
[_CCRCC]: [ , _.headers[_xacc_] ],
[_CSHA]: [ , _.headers[_xacs] ],
[_CSHAh]: [ , _.headers[_xacs_] ],
[_SSECA]: [ , _.headers[_xasseca] ],
[_SSECKMD]: [ , _.headers[_xasseckm] ],
[_SSEKMSKI]: [ , _.headers[_xasseakki] ],
[_BKE]: [ () => void 0 !== _.headers[_xassebke], () => parseBoolean(_.headers[_xassebke]) ],
[_RC]: [ , _.headers[_xarc] ]
});
await collectBody(_.body, ee);
return ne;
}, de_UploadPartCopyCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_),
[_CSVI]: [ , _.headers[_xacsvi] ],
[_SSE]: [ , _.headers[_xasse] ],
[_SSECA]: [ , _.headers[_xasseca] ],
[_SSECKMD]: [ , _.headers[_xasseckm] ],
[_SSEKMSKI]: [ , _.headers[_xasseakki] ],
[_BKE]: [ () => void 0 !== _.headers[_xassebke], () => parseBoolean(_.headers[_xassebke]) ],
[_RC]: [ , _.headers[_xarc] ]
}), ie = expectObject(await parseXmlBody(_.body, ee));
ne.CopyPartResult = de_CopyPartResult(ie, ee);
return ne;
}, de_WriteGetObjectResponseCommand = async (_, ee) => {
if (200 !== _.statusCode && _.statusCode >= 300) return de_CommandError(_, ee);
const ne = map({
$metadata: deserializeMetadata2(_)
});
await collectBody(_.body, ee);
return ne;
}, de_CommandError = async (_, ee) => {
const ne = {
..._,
body: await parseXmlErrorBody(_.body, ee)
}, ie = loadRestXmlErrorCode(_, ne.body);
switch (ie) {
case "NoSuchUpload":
case "com.amazonaws.s3#NoSuchUpload":
throw await de_NoSuchUploadRes(ne, ee);
case "ObjectNotInActiveTierError":
case "com.amazonaws.s3#ObjectNotInActiveTierError":
throw await de_ObjectNotInActiveTierErrorRes(ne, ee);
case "BucketAlreadyExists":
case "com.amazonaws.s3#BucketAlreadyExists":
throw await de_BucketAlreadyExistsRes(ne, ee);
case "BucketAlreadyOwnedByYou":
case "com.amazonaws.s3#BucketAlreadyOwnedByYou":
throw await de_BucketAlreadyOwnedByYouRes(ne, ee);
case "NoSuchBucket":
case "com.amazonaws.s3#NoSuchBucket":
throw await de_NoSuchBucketRes(ne, ee);
case "InvalidObjectState":
case "com.amazonaws.s3#InvalidObjectState":
throw await de_InvalidObjectStateRes(ne, ee);
case "NoSuchKey":
case "com.amazonaws.s3#NoSuchKey":
throw await de_NoSuchKeyRes(ne, ee);
case "NotFound":
case "com.amazonaws.s3#NotFound":
throw await de_NotFoundRes(ne, ee);
case "ObjectAlreadyInActiveTierError":
case "com.amazonaws.s3#ObjectAlreadyInActiveTierError":
throw await de_ObjectAlreadyInActiveTierErrorRes(ne, ee);
default:
const re = ne.body;
return throwDefaultError2({
output: _,
parsedBody: re,
errorCode: ie
});
}
}, throwDefaultError2 = withBaseException(S3ServiceException), de_BucketAlreadyExistsRes = async (_, ee) => {
const ne = map({}), ie = (_.body, new BucketAlreadyExists({
$metadata: deserializeMetadata2(_),
...ne
}));
return decorateServiceException(ie, _.body);
}, de_BucketAlreadyOwnedByYouRes = async (_, ee) => {
const ne = map({}), ie = (_.body, new BucketAlreadyOwnedByYou({
$metadata: deserializeMetadata2(_),
...ne
}));
return decorateServiceException(ie, _.body);
}, de_InvalidObjectStateRes = async (_, ee) => {
const ne = map({}), ie = _.body;
if (null != ie[_AT]) ne[_AT] = expectString(ie[_AT]);
if (null != ie[_SC]) ne[_SC] = expectString(ie[_SC]);
const re = new InvalidObjectState({
$metadata: deserializeMetadata2(_),
...ne
});
return decorateServiceException(re, _.body);
}, de_NoSuchBucketRes = async (_, ee) => {
const ne = map({}), ie = (_.body, new NoSuchBucket({
$metadata: deserializeMetadata2(_),
...ne
}));
return decorateServiceException(ie, _.body);
}, de_NoSuchKeyRes = async (_, ee) => {
const ne = map({}), ie = (_.body, new NoSuchKey({
$metadata: deserializeMetadata2(_),
...ne
}));
return decorateServiceException(ie, _.body);
}, de_NoSuchUploadRes = async (_, ee) => {
const ne = map({}), ie = (_.body, new NoSuchUpload({
$metadata: deserializeMetadata2(_),
...ne
}));
return decorateServiceException(ie, _.body);
}, de_NotFoundRes = async (_, ee) => {
const ne = map({}), ie = (_.body, new NotFound({
$metadata: deserializeMetadata2(_),
...ne
}));
return decorateServiceException(ie, _.body);
}, de_ObjectAlreadyInActiveTierErrorRes = async (_, ee) => {
const ne = map({}), ie = (_.body, new ObjectAlreadyInActiveTierError({
$metadata: deserializeMetadata2(_),
...ne
}));
return decorateServiceException(ie, _.body);
}, de_ObjectNotInActiveTierErrorRes = async (_, ee) => {
const ne = map({}), ie = (_.body, new ObjectNotInActiveTierError({
$metadata: deserializeMetadata2(_),
...ne
}));
return decorateServiceException(ie, _.body);
}, de_SelectObjectContentEventStream = (_, ee) => ee.eventStreamMarshaller.deserialize(_, (async ne => {
if (null != ne["Records"]) return {
Records: await de_RecordsEvent_event(ne["Records"], ee)
};
if (null != ne["Stats"]) return {
Stats: await de_StatsEvent_event(ne["Stats"], ee)
};
if (null != ne["Progress"]) return {
Progress: await de_ProgressEvent_event(ne["Progress"], ee)
};
if (null != ne["Cont"]) return {
Cont: await de_ContinuationEvent_event(ne["Cont"], ee)
};
if (null != ne["End"]) return {
End: await de_EndEvent_event(ne["End"], ee)
}; else return {
$unknown: _
};
})), de_ContinuationEvent_event = async (_, ee) => {
const ne = {}, ie = await parseXmlBody(_.body, ee);
Object.assign(ne, de_ContinuationEvent(ie, ee));
return ne;
}, de_EndEvent_event = async (_, ee) => {
const ne = {}, ie = await parseXmlBody(_.body, ee);
Object.assign(ne, de_EndEvent(ie, ee));
return ne;
}, de_ProgressEvent_event = async (_, ee) => {
const ne = {}, ie = await parseXmlBody(_.body, ee);
ne.Details = de_Progress(ie, ee);
return ne;
}, de_RecordsEvent_event = async (_, ee) => {
const ne = {};
ne.Payload = _.body;
return ne;
}, de_StatsEvent_event = async (_, ee) => {
const ne = {}, ie = await parseXmlBody(_.body, ee);
ne.Details = de_Stats(ie, ee);
return ne;
}, se_AbortIncompleteMultipartUpload = (_, ee) => {
const ne = new XmlNode(_AIMU);
if (null != _[_DAI]) ne.c(XmlNode.of(_DAI, String(_[_DAI])).n(_DAI));
return ne;
}, se_AccelerateConfiguration = (_, ee) => {
const ne = new XmlNode(_ACc);
if (null != _[_S]) ne.c(XmlNode.of(_BAS, _[_S]).n(_S));
return ne;
}, se_AccessControlPolicy = (_, ee) => {
const ne = new XmlNode(_ACP);
ne.lc(_, "Grants", "AccessControlList", (() => se_Grants(_[_Gr], ee)));
if (null != _[_O]) ne.c(se_Owner(_[_O], ee).n(_O));
return ne;
}, se_AccessControlTranslation = (_, ee) => {
const ne = new XmlNode(_ACT);
if (null != _[_O]) ne.c(XmlNode.of(_OOw, _[_O]).n(_O));
return ne;
}, se_AllowedHeaders = (_, ee) => _.filter((_ => null != _)).map((_ => XmlNode.of(_AH, _).n(_me))), se_AllowedMethods = (_, ee) => _.filter((_ => null != _)).map((_ => XmlNode.of(_AM, _).n(_me))), se_AllowedOrigins = (_, ee) => _.filter((_ => null != _)).map((_ => XmlNode.of(_AO, _).n(_me))), se_AnalyticsAndOperator = (_, ee) => {
const ne = new XmlNode(_AAO);
ne.cc(_, _P);
ne.l(_, "Tags", "Tag", (() => se_TagSet(_[_Tag], ee)));
return ne;
}, se_AnalyticsConfiguration = (_, ee) => {
const ne = new XmlNode(_AC);
if (null != _[_I]) ne.c(XmlNode.of(_AI, _[_I]).n(_I));
if (null != _[_F]) ne.c(se_AnalyticsFilter(_[_F], ee).n(_F));
if (null != _[_SCA]) ne.c(se_StorageClassAnalysis(_[_SCA], ee).n(_SCA));
return ne;
}, se_AnalyticsExportDestination = (_, ee) => {
const ne = new XmlNode(_AED);
if (null != _[_SBD]) ne.c(se_AnalyticsS3BucketDestination(_[_SBD], ee).n(_SBD));
return ne;
}, se_AnalyticsFilter = (_, ee) => {
const ne = new XmlNode(_AF);
AnalyticsFilter.visit(_, {
Prefix: ee => {
if (null != _[_P]) ne.c(XmlNode.of(_P, ee).n(_P));
},
Tag: ie => {
if (null != _[_Ta]) ne.c(se_Tag(ie, ee).n(_Ta));
},
And: ie => {
if (null != _[_A]) ne.c(se_AnalyticsAndOperator(ie, ee).n(_A));
},
_: (_, ee) => {
if (!(ee instanceof XmlNode || ee instanceof XmlText)) throw new Error("Unable to serialize unknown union members in XML.");
ne.c(new XmlNode(_).c(ee));
}
});
return ne;
}, se_AnalyticsS3BucketDestination = (_, ee) => {
const ne = new XmlNode(_ASBD);
if (null != _[_Fo]) ne.c(XmlNode.of(_ASEFF, _[_Fo]).n(_Fo));
if (null != _[_BAI]) ne.c(XmlNode.of(_AIc, _[_BAI]).n(_BAI));
if (null != _[_B]) ne.c(XmlNode.of(_BN, _[_B]).n(_B));
ne.cc(_, _P);
return ne;
}, se_BucketInfo = (_, ee) => {
const ne = new XmlNode(_BI);
ne.cc(_, _DR);
if (null != _[_Ty]) ne.c(XmlNode.of(_BT, _[_Ty]).n(_Ty));
return ne;
}, se_BucketLifecycleConfiguration = (_, ee) => {
const ne = new XmlNode(_BLC);
ne.l(_, "Rules", "Rule", (() => se_LifecycleRules(_[_Rul], ee)));
return ne;
}, se_BucketLoggingStatus = (_, ee) => {
const ne = new XmlNode(_BLS);
if (null != _[_LE]) ne.c(se_LoggingEnabled(_[_LE], ee).n(_LE));
return ne;
}, se_CompletedMultipartUpload = (_, ee) => {
const ne = new XmlNode(_CMU);
ne.l(_, "Parts", "Part", (() => se_CompletedPartList(_[_Part], ee)));
return ne;
}, se_CompletedPart = (_, ee) => {
const ne = new XmlNode(_CPo);
ne.cc(_, _ETa);
ne.cc(_, _CCRC);
ne.cc(_, _CCRCC);
ne.cc(_, _CSHA);
ne.cc(_, _CSHAh);
if (null != _[_PN]) ne.c(XmlNode.of(_PN, String(_[_PN])).n(_PN));
return ne;
}, se_CompletedPartList = (_, ee) => _.filter((_ => null != _)).map((_ => se_CompletedPart(_, ee).n(_me))), se_Condition = (_, ee) => {
const ne = new XmlNode(_Con);
ne.cc(_, _HECRE);
ne.cc(_, _KPE);
return ne;
}, se_CORSConfiguration = (_, ee) => {
const ne = new XmlNode(_CORSC);
ne.l(_, "CORSRules", "CORSRule", (() => se_CORSRules(_[_CORSRu], ee)));
return ne;
}, se_CORSRule = (_, ee) => {
const ne = new XmlNode(_CORSR);
ne.cc(_, _ID_);
ne.l(_, "AllowedHeaders", "AllowedHeader", (() => se_AllowedHeaders(_[_AHl], ee)));
ne.l(_, "AllowedMethods", "AllowedMethod", (() => se_AllowedMethods(_[_AMl], ee)));
ne.l(_, "AllowedOrigins", "AllowedOrigin", (() => se_AllowedOrigins(_[_AOl], ee)));
ne.l(_, "ExposeHeaders", "ExposeHeader", (() => se_ExposeHeaders(_[_EH], ee)));
if (null != _[_MAS]) ne.c(XmlNode.of(_MAS, String(_[_MAS])).n(_MAS));
return ne;
}, se_CORSRules = (_, ee) => _.filter((_ => null != _)).map((_ => se_CORSRule(_, ee).n(_me))), se_CreateBucketConfiguration = (_, ee) => {
const ne = new XmlNode(_CBC);
if (null != _[_LC]) ne.c(XmlNode.of(_BLCu, _[_LC]).n(_LC));
if (null != _[_L]) ne.c(se_LocationInfo(_[_L], ee).n(_L));
if (null != _[_B]) ne.c(se_BucketInfo(_[_B], ee).n(_B));
return ne;
}, se_CSVInput = (_, ee) => {
const ne = new XmlNode(_CSVIn);
ne.cc(_, _FHI);
ne.cc(_, _Com);
ne.cc(_, _QEC);
ne.cc(_, _RD);
ne.cc(_, _FD);
ne.cc(_, _QCuo);
if (null != _[_AQRD]) ne.c(XmlNode.of(_AQRD, String(_[_AQRD])).n(_AQRD));
return ne;
}, se_CSVOutput = (_, ee) => {
const ne = new XmlNode(_CSVO);
ne.cc(_, _QF);
ne.cc(_, _QEC);
ne.cc(_, _RD);
ne.cc(_, _FD);
ne.cc(_, _QCuo);
return ne;
}, se_DefaultRetention = (_, ee) => {
const ne = new XmlNode(_DRe);
if (null != _[_Mo]) ne.c(XmlNode.of(_OLRM, _[_Mo]).n(_Mo));
if (null != _[_Da]) ne.c(XmlNode.of(_Da, String(_[_Da])).n(_Da));
if (null != _[_Y]) ne.c(XmlNode.of(_Y, String(_[_Y])).n(_Y));
return ne;
}, se_Delete = (_, ee) => {
const ne = new XmlNode(_Del);
ne.l(_, "Objects", "Object", (() => se_ObjectIdentifierList(_[_Ob], ee)));
if (null != _[_Q]) ne.c(XmlNode.of(_Q, String(_[_Q])).n(_Q));
return ne;
}, se_DeleteMarkerReplication = (_, ee) => {
const ne = new XmlNode(_DMR);
if (null != _[_S]) ne.c(XmlNode.of(_DMRS, _[_S]).n(_S));
return ne;
}, se_Destination = (_, ee) => {
const ne = new XmlNode(_Des);
if (null != _[_B]) ne.c(XmlNode.of(_BN, _[_B]).n(_B));
if (null != _[_Ac]) ne.c(XmlNode.of(_AIc, _[_Ac]).n(_Ac));
ne.cc(_, _SC);
if (null != _[_ACT]) ne.c(se_AccessControlTranslation(_[_ACT], ee).n(_ACT));
if (null != _[_ECn]) ne.c(se_EncryptionConfiguration(_[_ECn], ee).n(_ECn));
if (null != _[_RTe]) ne.c(se_ReplicationTime(_[_RTe], ee).n(_RTe));
if (null != _[_Me]) ne.c(se_Metrics(_[_Me], ee).n(_Me));
return ne;
}, se_Encryption = (_, ee) => {
const ne = new XmlNode(_En);
if (null != _[_ETn]) ne.c(XmlNode.of(_SSE, _[_ETn]).n(_ETn));
if (null != _[_KMSKI]) ne.c(XmlNode.of(_SSEKMSKI, _[_KMSKI]).n(_KMSKI));
ne.cc(_, _KMSC);
return ne;
}, se_EncryptionConfiguration = (_, ee) => {
const ne = new XmlNode(_ECn);
ne.cc(_, _RKKID);
return ne;
}, se_ErrorDocument = (_, ee) => {
const ne = new XmlNode(_ED);
if (null != _[_K]) ne.c(XmlNode.of(_OK, _[_K]).n(_K));
return ne;
}, se_EventBridgeConfiguration = (_, ee) => new XmlNode(_EBC), se_EventList = (_, ee) => _.filter((_ => null != _)).map((_ => XmlNode.of(_Ev, _).n(_me))), se_ExistingObjectReplication = (_, ee) => {
const ne = new XmlNode(_EOR);
if (null != _[_S]) ne.c(XmlNode.of(_EORS, _[_S]).n(_S));
return ne;
}, se_ExposeHeaders = (_, ee) => _.filter((_ => null != _)).map((_ => XmlNode.of(_EHx, _).n(_me))), se_FilterRule = (_, ee) => {
const ne = new XmlNode(_FR);
if (null != _[_N]) ne.c(XmlNode.of(_FRN, _[_N]).n(_N));
if (null != _[_Va]) ne.c(XmlNode.of(_FRV, _[_Va]).n(_Va));
return ne;
}, se_FilterRuleList = (_, ee) => _.filter((_ => null != _)).map((_ => se_FilterRule(_, ee).n(_me))), se_GlacierJobParameters = (_, ee) => {
const ne = new XmlNode(_GJP);
ne.cc(_, _Ti);
return ne;
}, se_Grant = (_, ee) => {
const ne = new XmlNode(_G);
if (null != _[_Gra]) {
const ie = se_Grantee(_[_Gra], ee).n(_Gra);
ie.a("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
ne.c(ie);
}
ne.cc(_, _Pe);
return ne;
}, se_Grantee = (_, ee) => {
const ne = new XmlNode(_Gra);
ne.cc(_, _DN);
ne.cc(_, _EA);
ne.cc(_, _ID_);
ne.cc(_, _URI);
ne.a("xsi:type", _[_Ty]);
return ne;
}, se_Grants = (_, ee) => _.filter((_ => null != _)).map((_ => se_Grant(_, ee).n(_G))), se_IndexDocument = (_, ee) => {
const ne = new XmlNode(_ID);
ne.cc(_, _Su);
return ne;
}, se_InputSerialization = (_, ee) => {
const ne = new XmlNode(_IS);
if (null != _[_CSV]) ne.c(se_CSVInput(_[_CSV], ee).n(_CSV));
ne.cc(_, _CTom);
if (null != _[_JSON]) ne.c(se_JSONInput(_[_JSON], ee).n(_JSON));
if (null != _[_Parq]) ne.c(se_ParquetInput(_[_Parq], ee).n(_Parq));
return ne;
}, se_IntelligentTieringAndOperator = (_, ee) => {
const ne = new XmlNode(_ITAO);
ne.cc(_, _P);
ne.l(_, "Tags", "Tag", (() => se_TagSet(_[_Tag], ee)));
return ne;
}, se_IntelligentTieringConfiguration = (_, ee) => {
const ne = new XmlNode(_ITC);
if (null != _[_I]) ne.c(XmlNode.of(_ITI, _[_I]).n(_I));
if (null != _[_F]) ne.c(se_IntelligentTieringFilter(_[_F], ee).n(_F));
if (null != _[_S]) ne.c(XmlNode.of(_ITS, _[_S]).n(_S));
ne.l(_, "Tierings", "Tiering", (() => se_TieringList(_[_Tie], ee)));
return ne;
}, se_IntelligentTieringFilter = (_, ee) => {
const ne = new XmlNode(_ITF);
ne.cc(_, _P);
if (null != _[_Ta]) ne.c(se_Tag(_[_Ta], ee).n(_Ta));
if (null != _[_A]) ne.c(se_IntelligentTieringAndOperator(_[_A], ee).n(_A));
return ne;
}, se_InventoryConfiguration = (_, ee) => {
const ne = new XmlNode(_IC);
if (null != _[_Des]) ne.c(se_InventoryDestination(_[_Des], ee).n(_Des));
if (null != _[_IE]) ne.c(XmlNode.of(_IE, String(_[_IE])).n(_IE));
if (null != _[_F]) ne.c(se_InventoryFilter(_[_F], ee).n(_F));
if (null != _[_I]) ne.c(XmlNode.of(_II, _[_I]).n(_I));
if (null != _[_IOV]) ne.c(XmlNode.of(_IIOV, _[_IOV]).n(_IOV));
ne.lc(_, "OptionalFields", "OptionalFields", (() => se_InventoryOptionalFields(_[_OF], ee)));
if (null != _[_Sc]) ne.c(se_InventorySchedule(_[_Sc], ee).n(_Sc));
return ne;
}, se_InventoryDestination = (_, ee) => {
const ne = new XmlNode(_IDn);
if (null != _[_SBD]) ne.c(se_InventoryS3BucketDestination(_[_SBD], ee).n(_SBD));
return ne;
}, se_InventoryEncryption = (_, ee) => {
const ne = new XmlNode(_IEn);
if (null != _[_SSES]) ne.c(se_SSES3(_[_SSES], ee).n(_SS));
if (null != _[_SSEKMS]) ne.c(se_SSEKMS(_[_SSEKMS], ee).n(_SK));
return ne;
}, se_InventoryFilter = (_, ee) => {
const ne = new XmlNode(_IF);
ne.cc(_, _P);
return ne;
}, se_InventoryOptionalFields = (_, ee) => _.filter((_ => null != _)).map((_ => XmlNode.of(_IOF, _).n(_Fi))), se_InventoryS3BucketDestination = (_, ee) => {
const ne = new XmlNode(_ISBD);
ne.cc(_, _AIc);
if (null != _[_B]) ne.c(XmlNode.of(_BN, _[_B]).n(_B));
if (null != _[_Fo]) ne.c(XmlNode.of(_IFn, _[_Fo]).n(_Fo));
ne.cc(_, _P);
if (null != _[_En]) ne.c(se_InventoryEncryption(_[_En], ee).n(_En));
return ne;
}, se_InventorySchedule = (_, ee) => {
const ne = new XmlNode(_ISn);
if (null != _[_Fr]) ne.c(XmlNode.of(_IFnv, _[_Fr]).n(_Fr));
return ne;
}, se_JSONInput = (_, ee) => {
const ne = new XmlNode(_JSONI);
if (null != _[_Ty]) ne.c(XmlNode.of(_JSONT, _[_Ty]).n(_Ty));
return ne;
}, se_JSONOutput = (_, ee) => {
const ne = new XmlNode(_JSONO);
ne.cc(_, _RD);
return ne;
}, se_LambdaFunctionConfiguration = (_, ee) => {
const ne = new XmlNode(_LFCa);
if (null != _[_I]) ne.c(XmlNode.of(_NI, _[_I]).n(_I));
if (null != _[_LFA]) ne.c(XmlNode.of(_LFA, _[_LFA]).n(_CF));
ne.l(_, "Events", "Event", (() => se_EventList(_[_Eve], ee)));
if (null != _[_F]) ne.c(se_NotificationConfigurationFilter(_[_F], ee).n(_F));
return ne;
}, se_LambdaFunctionConfigurationList = (_, ee) => _.filter((_ => null != _)).map((_ => se_LambdaFunctionConfiguration(_, ee).n(_me))), se_LifecycleExpiration = (_, ee) => {
const ne = new XmlNode(_LEi);
if (null != _[_Dat]) ne.c(XmlNode.of(_Dat, (_[_Dat].toISOString().split(".")[0] + "Z").toString()).n(_Dat));
if (null != _[_Da]) ne.c(XmlNode.of(_Da, String(_[_Da])).n(_Da));
if (null != _[_EODM]) ne.c(XmlNode.of(_EODM, String(_[_EODM])).n(_EODM));
return ne;
}, se_LifecycleRule = (_, ee) => {
const ne = new XmlNode(_LR);
if (null != _[_Exp]) ne.c(se_LifecycleExpiration(_[_Exp], ee).n(_Exp));
ne.cc(_, _ID_);
ne.cc(_, _P);
if (null != _[_F]) ne.c(se_LifecycleRuleFilter(_[_F], ee).n(_F));
if (null != _[_S]) ne.c(XmlNode.of(_ESx, _[_S]).n(_S));
ne.l(_, "Transitions", "Transition", (() => se_TransitionList(_[_Tr], ee)));
ne.l(_, "NoncurrentVersionTransitions", "NoncurrentVersionTransition", (() => se_NoncurrentVersionTransitionList(_[_NVT], ee)));
if (null != _[_NVE]) ne.c(se_NoncurrentVersionExpiration(_[_NVE], ee).n(_NVE));
if (null != _[_AIMU]) ne.c(se_AbortIncompleteMultipartUpload(_[_AIMU], ee).n(_AIMU));
return ne;
}, se_LifecycleRuleAndOperator = (_, ee) => {
const ne = new XmlNode(_LRAO);
ne.cc(_, _P);
ne.l(_, "Tags", "Tag", (() => se_TagSet(_[_Tag], ee)));
if (null != _[_OSGT]) ne.c(XmlNode.of(_OSGTB, String(_[_OSGT])).n(_OSGT));
if (null != _[_OSLT]) ne.c(XmlNode.of(_OSLTB, String(_[_OSLT])).n(_OSLT));
return ne;
}, se_LifecycleRuleFilter = (_, ee) => {
const ne = new XmlNode(_LRF);
LifecycleRuleFilter.visit(_, {
Prefix: ee => {
if (null != _[_P]) ne.c(XmlNode.of(_P, ee).n(_P));
},
Tag: ie => {
if (null != _[_Ta]) ne.c(se_Tag(ie, ee).n(_Ta));
},
ObjectSizeGreaterThan: ee => {
if (null != _[_OSGT]) ne.c(XmlNode.of(_OSGTB, String(ee)).n(_OSGT));
},
ObjectSizeLessThan: ee => {
if (null != _[_OSLT]) ne.c(XmlNode.of(_OSLTB, String(ee)).n(_OSLT));
},
And: ie => {
if (null != _[_A]) ne.c(se_LifecycleRuleAndOperator(ie, ee).n(_A));
},
_: (_, ee) => {
if (!(ee instanceof XmlNode || ee instanceof XmlText)) throw new Error("Unable to serialize unknown union members in XML.");
ne.c(new XmlNode(_).c(ee));
}
});
return ne;
}, se_LifecycleRules = (_, ee) => _.filter((_ => null != _)).map((_ => se_LifecycleRule(_, ee).n(_me))), se_LocationInfo = (_, ee) => {
const ne = new XmlNode(_LI);
if (null != _[_Ty]) ne.c(XmlNode.of(_LT, _[_Ty]).n(_Ty));
if (null != _[_N]) ne.c(XmlNode.of(_LNAS, _[_N]).n(_N));
return ne;
}, se_LoggingEnabled = (_, ee) => {
const ne = new XmlNode(_LE);
ne.cc(_, _TB);
ne.lc(_, "TargetGrants", "TargetGrants", (() => se_TargetGrants(_[_TG], ee)));
ne.cc(_, _TP);
if (null != _[_TOKF]) ne.c(se_TargetObjectKeyFormat(_[_TOKF], ee).n(_TOKF));
return ne;
}, se_MetadataEntry = (_, ee) => {
const ne = new XmlNode(_ME);
if (null != _[_N]) ne.c(XmlNode.of(_MKe, _[_N]).n(_N));
if (null != _[_Va]) ne.c(XmlNode.of(_MV, _[_Va]).n(_Va));
return ne;
}, se_Metrics = (_, ee) => {
const ne = new XmlNode(_Me);
if (null != _[_S]) ne.c(XmlNode.of(_MS, _[_S]).n(_S));
if (null != _[_ETv]) ne.c(se_ReplicationTimeValue(_[_ETv], ee).n(_ETv));
return ne;
}, se_MetricsAndOperator = (_, ee) => {
const ne = new XmlNode(_MAO);
ne.cc(_, _P);
ne.l(_, "Tags", "Tag", (() => se_TagSet(_[_Tag], ee)));
ne.cc(_, _APAc);
return ne;
}, se_MetricsConfiguration = (_, ee) => {
const ne = new XmlNode(_MC);
if (null != _[_I]) ne.c(XmlNode.of(_MI, _[_I]).n(_I));
if (null != _[_F]) ne.c(se_MetricsFilter(_[_F], ee).n(_F));
return ne;
}, se_MetricsFilter = (_, ee) => {
const ne = new XmlNode(_MF);
MetricsFilter.visit(_, {
Prefix: ee => {
if (null != _[_P]) ne.c(XmlNode.of(_P, ee).n(_P));
},
Tag: ie => {
if (null != _[_Ta]) ne.c(se_Tag(ie, ee).n(_Ta));
},
AccessPointArn: ee => {
if (null != _[_APAc]) ne.c(XmlNode.of(_APAc, ee).n(_APAc));
},
And: ie => {
if (null != _[_A]) ne.c(se_MetricsAndOperator(ie, ee).n(_A));
},
_: (_, ee) => {
if (!(ee instanceof XmlNode || ee instanceof XmlText)) throw new Error("Unable to serialize unknown union members in XML.");
ne.c(new XmlNode(_).c(ee));
}
});
return ne;
}, se_NoncurrentVersionExpiration = (_, ee) => {
const ne = new XmlNode(_NVE);
if (null != _[_ND]) ne.c(XmlNode.of(_Da, String(_[_ND])).n(_ND));
if (null != _[_NNV]) ne.c(XmlNode.of(_VC, String(_[_NNV])).n(_NNV));
return ne;
}, se_NoncurrentVersionTransition = (_, ee) => {
const ne = new XmlNode(_NVTo);
if (null != _[_ND]) ne.c(XmlNode.of(_Da, String(_[_ND])).n(_ND));
if (null != _[_SC]) ne.c(XmlNode.of(_TSC, _[_SC]).n(_SC));
if (null != _[_NNV]) ne.c(XmlNode.of(_VC, String(_[_NNV])).n(_NNV));
return ne;
}, se_NoncurrentVersionTransitionList = (_, ee) => _.filter((_ => null != _)).map((_ => se_NoncurrentVersionTransition(_, ee).n(_me))), se_NotificationConfiguration = (_, ee) => {
const ne = new XmlNode(_NC);
ne.l(_, "TopicConfigurations", "TopicConfiguration", (() => se_TopicConfigurationList(_[_TCop], ee)));
ne.l(_, "QueueConfigurations", "QueueConfiguration", (() => se_QueueConfigurationList(_[_QCu], ee)));
ne.l(_, "LambdaFunctionConfigurations", "CloudFunctionConfiguration", (() => se_LambdaFunctionConfigurationList(_[_LFC], ee)));
if (null != _[_EBC]) ne.c(se_EventBridgeConfiguration(_[_EBC], ee).n(_EBC));
return ne;
}, se_NotificationConfigurationFilter = (_, ee) => {
const ne = new XmlNode(_NCF);
if (null != _[_K]) ne.c(se_S3KeyFilter(_[_K], ee).n(_SKe));
return ne;
}, se_ObjectIdentifier = (_, ee) => {
const ne = new XmlNode(_OI);
if (null != _[_K]) ne.c(XmlNode.of(_OK, _[_K]).n(_K));
if (null != _[_VI]) ne.c(XmlNode.of(_OVI, _[_VI]).n(_VI));
return ne;
}, se_ObjectIdentifierList = (_, ee) => _.filter((_ => null != _)).map((_ => se_ObjectIdentifier(_, ee).n(_me))), se_ObjectLockConfiguration = (_, ee) => {
const ne = new XmlNode(_OLC);
ne.cc(_, _OLE);
if (null != _[_Ru]) ne.c(se_ObjectLockRule(_[_Ru], ee).n(_Ru));
return ne;
}, se_ObjectLockLegalHold = (_, ee) => {
const ne = new XmlNode(_OLLH);
if (null != _[_S]) ne.c(XmlNode.of(_OLLHS, _[_S]).n(_S));
return ne;
}, se_ObjectLockRetention = (_, ee) => {
const ne = new XmlNode(_OLR);
if (null != _[_Mo]) ne.c(XmlNode.of(_OLRM, _[_Mo]).n(_Mo));
if (null != _[_RUD]) ne.c(XmlNode.of(_Dat, (_[_RUD].toISOString().split(".")[0] + "Z").toString()).n(_RUD));
return ne;
}, se_ObjectLockRule = (_, ee) => {
const ne = new XmlNode(_OLRb);
if (null != _[_DRe]) ne.c(se_DefaultRetention(_[_DRe], ee).n(_DRe));
return ne;
}, se_OutputLocation = (_, ee) => {
const ne = new XmlNode(_OL);
if (null != _[_S_]) ne.c(se_S3Location(_[_S_], ee).n(_S_));
return ne;
}, se_OutputSerialization = (_, ee) => {
const ne = new XmlNode(_OS);
if (null != _[_CSV]) ne.c(se_CSVOutput(_[_CSV], ee).n(_CSV));
if (null != _[_JSON]) ne.c(se_JSONOutput(_[_JSON], ee).n(_JSON));
return ne;
}, se_Owner = (_, ee) => {
const ne = new XmlNode(_O);
ne.cc(_, _DN);
ne.cc(_, _ID_);
return ne;
}, se_OwnershipControls = (_, ee) => {
const ne = new XmlNode(_OC);
ne.l(_, "Rules", "Rule", (() => se_OwnershipControlsRules(_[_Rul], ee)));
return ne;
}, se_OwnershipControlsRule = (_, ee) => {
const ne = new XmlNode(_OCR);
ne.cc(_, _OO);
return ne;
}, se_OwnershipControlsRules = (_, ee) => _.filter((_ => null != _)).map((_ => se_OwnershipControlsRule(_, ee).n(_me))), se_ParquetInput = (_, ee) => new XmlNode(_PI), se_PartitionedPrefix = (_, ee) => {
const ne = new XmlNode(_PP);
ne.cc(_, _PDS);
return ne;
}, se_PublicAccessBlockConfiguration = (_, ee) => {
const ne = new XmlNode(_PABC);
if (null != _[_BPA]) ne.c(XmlNode.of(_Se, String(_[_BPA])).n(_BPA));
if (null != _[_IPA]) ne.c(XmlNode.of(_Se, String(_[_IPA])).n(_IPA));
if (null != _[_BPP]) ne.c(XmlNode.of(_Se, String(_[_BPP])).n(_BPP));
if (null != _[_RPB]) ne.c(XmlNode.of(_Se, String(_[_RPB])).n(_RPB));
return ne;
}, se_QueueConfiguration = (_, ee) => {
const ne = new XmlNode(_QC);
if (null != _[_I]) ne.c(XmlNode.of(_NI, _[_I]).n(_I));
if (null != _[_QA]) ne.c(XmlNode.of(_QA, _[_QA]).n(_Qu));
ne.l(_, "Events", "Event", (() => se_EventList(_[_Eve], ee)));
if (null != _[_F]) ne.c(se_NotificationConfigurationFilter(_[_F], ee).n(_F));
return ne;
}, se_QueueConfigurationList = (_, ee) => _.filter((_ => null != _)).map((_ => se_QueueConfiguration(_, ee).n(_me))), se_Redirect = (_, ee) => {
const ne = new XmlNode(_Red);
ne.cc(_, _HN);
ne.cc(_, _HRC);
ne.cc(_, _Pr);
ne.cc(_, _RKPW);
ne.cc(_, _RKW);
return ne;
}, se_RedirectAllRequestsTo = (_, ee) => {
const ne = new XmlNode(_RART);
ne.cc(_, _HN);
ne.cc(_, _Pr);
return ne;
}, se_ReplicaModifications = (_, ee) => {
const ne = new XmlNode(_RM);
if (null != _[_S]) ne.c(XmlNode.of(_RMS, _[_S]).n(_S));
return ne;
}, se_ReplicationConfiguration = (_, ee) => {
const ne = new XmlNode(_RCe);
ne.cc(_, _Ro);
ne.l(_, "Rules", "Rule", (() => se_ReplicationRules(_[_Rul], ee)));
return ne;
}, se_ReplicationRule = (_, ee) => {
const ne = new XmlNode(_RRe);
ne.cc(_, _ID_);
if (null != _[_Pri]) ne.c(XmlNode.of(_Pri, String(_[_Pri])).n(_Pri));
ne.cc(_, _P);
if (null != _[_F]) ne.c(se_ReplicationRuleFilter(_[_F], ee).n(_F));
if (null != _[_S]) ne.c(XmlNode.of(_RRS, _[_S]).n(_S));
if (null != _[_SSC]) ne.c(se_SourceSelectionCriteria(_[_SSC], ee).n(_SSC));
if (null != _[_EOR]) ne.c(se_ExistingObjectReplication(_[_EOR], ee).n(_EOR));
if (null != _[_Des]) ne.c(se_Destination(_[_Des], ee).n(_Des));
if (null != _[_DMR]) ne.c(se_DeleteMarkerReplication(_[_DMR], ee).n(_DMR));
return ne;
}, se_ReplicationRuleAndOperator = (_, ee) => {
const ne = new XmlNode(_RRAO);
ne.cc(_, _P);
ne.l(_, "Tags", "Tag", (() => se_TagSet(_[_Tag], ee)));
return ne;
}, se_ReplicationRuleFilter = (_, ee) => {
const ne = new XmlNode(_RRF);
ReplicationRuleFilter.visit(_, {
Prefix: ee => {
if (null != _[_P]) ne.c(XmlNode.of(_P, ee).n(_P));
},
Tag: ie => {
if (null != _[_Ta]) ne.c(se_Tag(ie, ee).n(_Ta));
},
And: ie => {
if (null != _[_A]) ne.c(se_ReplicationRuleAndOperator(ie, ee).n(_A));
},
_: (_, ee) => {
if (!(ee instanceof XmlNode || ee instanceof XmlText)) throw new Error("Unable to serialize unknown union members in XML.");
ne.c(new XmlNode(_).c(ee));
}
});
return ne;
}, se_ReplicationRules = (_, ee) => _.filter((_ => null != _)).map((_ => se_ReplicationRule(_, ee).n(_me))), se_ReplicationTime = (_, ee) => {
const ne = new XmlNode(_RTe);
if (null != _[_S]) ne.c(XmlNode.of(_RTS, _[_S]).n(_S));
if (null != _[_Tim]) ne.c(se_ReplicationTimeValue(_[_Tim], ee).n(_Tim));
return ne;
}, se_ReplicationTimeValue = (_, ee) => {
const ne = new XmlNode(_RTV);
if (null != _[_Mi]) ne.c(XmlNode.of(_Mi, String(_[_Mi])).n(_Mi));
return ne;
}, se_RequestPaymentConfiguration = (_, ee) => {
const ne = new XmlNode(_RPC);
ne.cc(_, _Pa);
return ne;
}, se_RequestProgress = (_, ee) => {
const ne = new XmlNode(_RPe);
if (null != _[_Ena]) ne.c(XmlNode.of(_ERP, String(_[_Ena])).n(_Ena));
return ne;
}, se_RestoreRequest = (_, ee) => {
const ne = new XmlNode(_RRes);
if (null != _[_Da]) ne.c(XmlNode.of(_Da, String(_[_Da])).n(_Da));
if (null != _[_GJP]) ne.c(se_GlacierJobParameters(_[_GJP], ee).n(_GJP));
if (null != _[_Ty]) ne.c(XmlNode.of(_RRT, _[_Ty]).n(_Ty));
ne.cc(_, _Ti);
ne.cc(_, _Desc);
if (null != _[_SP]) ne.c(se_SelectParameters(_[_SP], ee).n(_SP));
if (null != _[_OL]) ne.c(se_OutputLocation(_[_OL], ee).n(_OL));
return ne;
}, se_RoutingRule = (_, ee) => {
const ne = new XmlNode(_RRou);
if (null != _[_Con]) ne.c(se_Condition(_[_Con], ee).n(_Con));
if (null != _[_Red]) ne.c(se_Redirect(_[_Red], ee).n(_Red));
return ne;
}, se_RoutingRules = (_, ee) => _.filter((_ => null != _)).map((_ => se_RoutingRule(_, ee).n(_RRou))), se_S3KeyFilter = (_, ee) => {
const ne = new XmlNode(_SKF);
ne.l(_, "FilterRules", "FilterRule", (() => se_FilterRuleList(_[_FRi], ee)));
return ne;
}, se_S3Location = (_, ee) => {
const ne = new XmlNode(_SL);
ne.cc(_, _BN);
if (null != _[_P]) ne.c(XmlNode.of(_LP, _[_P]).n(_P));
if (null != _[_En]) ne.c(se_Encryption(_[_En], ee).n(_En));
if (null != _[_CACL]) ne.c(XmlNode.of(_OCACL, _[_CACL]).n(_CACL));
ne.lc(_, "AccessControlList", "AccessControlList", (() => se_Grants(_[_ACLc], ee)));
if (null != _[_T]) ne.c(se_Tagging(_[_T], ee).n(_T));
ne.lc(_, "UserMetadata", "UserMetadata", (() => se_UserMetadata(_[_UM], ee)));
ne.cc(_, _SC);
return ne;
}, se_ScanRange = (_, ee) => {
const ne = new XmlNode(_SR);
if (null != _[_St]) ne.c(XmlNode.of(_St, String(_[_St])).n(_St));
if (null != _[_End]) ne.c(XmlNode.of(_End, String(_[_End])).n(_End));
return ne;
}, se_SelectParameters = (_, ee) => {
const ne = new XmlNode(_SP);
if (null != _[_IS]) ne.c(se_InputSerialization(_[_IS], ee).n(_IS));
ne.cc(_, _ETx);
ne.cc(_, _Ex);
if (null != _[_OS]) ne.c(se_OutputSerialization(_[_OS], ee).n(_OS));
return ne;
}, se_ServerSideEncryptionByDefault = (_, ee) => {
const ne = new XmlNode(_SSEBD);
if (null != _[_SSEA]) ne.c(XmlNode.of(_SSE, _[_SSEA]).n(_SSEA));
if (null != _[_KMSMKID]) ne.c(XmlNode.of(_SSEKMSKI, _[_KMSMKID]).n(_KMSMKID));
return ne;
}, se_ServerSideEncryptionConfiguration = (_, ee) => {
const ne = new XmlNode(_SSEC);
ne.l(_, "Rules", "Rule", (() => se_ServerSideEncryptionRules(_[_Rul], ee)));
return ne;
}, se_ServerSideEncryptionRule = (_, ee) => {
const ne = new XmlNode(_SSER);
if (null != _[_ASSEBD]) ne.c(se_ServerSideEncryptionByDefault(_[_ASSEBD], ee).n(_ASSEBD));
if (null != _[_BKE]) ne.c(XmlNode.of(_BKE, String(_[_BKE])).n(_BKE));
return ne;
}, se_ServerSideEncryptionRules = (_, ee) => _.filter((_ => null != _)).map((_ => se_ServerSideEncryptionRule(_, ee).n(_me))), se_SimplePrefix = (_, ee) => new XmlNode(_SPi), se_SourceSelectionCriteria = (_, ee) => {
const ne = new XmlNode(_SSC);
if (null != _[_SKEO]) ne.c(se_SseKmsEncryptedObjects(_[_SKEO], ee).n(_SKEO));
if (null != _[_RM]) ne.c(se_ReplicaModifications(_[_RM], ee).n(_RM));
return ne;
}, se_SSEKMS = (_, ee) => {
const ne = new XmlNode(_SK);
if (null != _[_KI]) ne.c(XmlNode.of(_SSEKMSKI, _[_KI]).n(_KI));
return ne;
}, se_SseKmsEncryptedObjects = (_, ee) => {
const ne = new XmlNode(_SKEO);
if (null != _[_S]) ne.c(XmlNode.of(_SKEOS, _[_S]).n(_S));
return ne;
}, se_SSES3 = (_, ee) => new XmlNode(_SS), se_StorageClassAnalysis = (_, ee) => {
const ne = new XmlNode(_SCA);
if (null != _[_DE]) ne.c(se_StorageClassAnalysisDataExport(_[_DE], ee).n(_DE));
return ne;
}, se_StorageClassAnalysisDataExport = (_, ee) => {
const ne = new XmlNode(_SCADE);
if (null != _[_OSV]) ne.c(XmlNode.of(_SCASV, _[_OSV]).n(_OSV));
if (null != _[_Des]) ne.c(se_AnalyticsExportDestination(_[_Des], ee).n(_Des));
return ne;
}, se_Tag = (_, ee) => {
const ne = new XmlNode(_Ta);
if (null != _[_K]) ne.c(XmlNode.of(_OK, _[_K]).n(_K));
ne.cc(_, _Va);
return ne;
}, se_Tagging = (_, ee) => {
const ne = new XmlNode(_T);
ne.lc(_, "TagSet", "TagSet", (() => se_TagSet(_[_TS], ee)));
return ne;
}, se_TagSet = (_, ee) => _.filter((_ => null != _)).map((_ => se_Tag(_, ee).n(_Ta))), se_TargetGrant = (_, ee) => {
const ne = new XmlNode(_TGa);
if (null != _[_Gra]) {
const ie = se_Grantee(_[_Gra], ee).n(_Gra);
ie.a("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
ne.c(ie);
}
if (null != _[_Pe]) ne.c(XmlNode.of(_BLP, _[_Pe]).n(_Pe));
return ne;
}, se_TargetGrants = (_, ee) => _.filter((_ => null != _)).map((_ => se_TargetGrant(_, ee).n(_G))), se_TargetObjectKeyFormat = (_, ee) => {
const ne = new XmlNode(_TOKF);
if (null != _[_SPi]) ne.c(se_SimplePrefix(_[_SPi], ee).n(_SPi));
if (null != _[_PP]) ne.c(se_PartitionedPrefix(_[_PP], ee).n(_PP));
return ne;
}, se_Tiering = (_, ee) => {
const ne = new XmlNode(_Tier);
if (null != _[_Da]) ne.c(XmlNode.of(_ITD, String(_[_Da])).n(_Da));
if (null != _[_AT]) ne.c(XmlNode.of(_ITAT, _[_AT]).n(_AT));
return ne;
}, se_TieringList = (_, ee) => _.filter((_ => null != _)).map((_ => se_Tiering(_, ee).n(_me))), se_TopicConfiguration = (_, ee) => {
const ne = new XmlNode(_TCo);
if (null != _[_I]) ne.c(XmlNode.of(_NI, _[_I]).n(_I));
if (null != _[_TA]) ne.c(XmlNode.of(_TA, _[_TA]).n(_Top));
ne.l(_, "Events", "Event", (() => se_EventList(_[_Eve], ee)));
if (null != _[_F]) ne.c(se_NotificationConfigurationFilter(_[_F], ee).n(_F));
return ne;
}, se_TopicConfigurationList = (_, ee) => _.filter((_ => null != _)).map((_ => se_TopicConfiguration(_, ee).n(_me))), se_Transition = (_, ee) => {
const ne = new XmlNode(_Tra);
if (null != _[_Dat]) ne.c(XmlNode.of(_Dat, (_[_Dat].toISOString().split(".")[0] + "Z").toString()).n(_Dat));
if (null != _[_Da]) ne.c(XmlNode.of(_Da, String(_[_Da])).n(_Da));
if (null != _[_SC]) ne.c(XmlNode.of(_TSC, _[_SC]).n(_SC));
return ne;
}, se_TransitionList = (_, ee) => _.filter((_ => null != _)).map((_ => se_Transition(_, ee).n(_me))), se_UserMetadata = (_, ee) => _.filter((_ => null != _)).map((_ => se_MetadataEntry(_, ee).n(_ME))), se_VersioningConfiguration = (_, ee) => {
const ne = new XmlNode(_VCe);
if (null != _[_MFAD]) ne.c(XmlNode.of(_MFAD, _[_MFAD]).n(_MDf));
if (null != _[_S]) ne.c(XmlNode.of(_BVS, _[_S]).n(_S));
return ne;
}, se_WebsiteConfiguration = (_, ee) => {
const ne = new XmlNode(_WC);
if (null != _[_ED]) ne.c(se_ErrorDocument(_[_ED], ee).n(_ED));
if (null != _[_ID]) ne.c(se_IndexDocument(_[_ID], ee).n(_ID));
if (null != _[_RART]) ne.c(se_RedirectAllRequestsTo(_[_RART], ee).n(_RART));
ne.lc(_, "RoutingRules", "RoutingRules", (() => se_RoutingRules(_[_RRo], ee)));
return ne;
}, de_AbortIncompleteMultipartUpload = (_, ee) => {
const ne = {};
if (null != _[_DAI]) ne[_DAI] = strictParseInt32(_[_DAI]);
return ne;
}, de_AccessControlTranslation = (_, ee) => {
const ne = {};
if (null != _[_O]) ne[_O] = expectString(_[_O]);
return ne;
}, de_AllowedHeaders = (_, ee) => (_ || []).filter((_ => null != _)).map((_ => expectString(_))), de_AllowedMethods = (_, ee) => (_ || []).filter((_ => null != _)).map((_ => expectString(_))), de_AllowedOrigins = (_, ee) => (_ || []).filter((_ => null != _)).map((_ => expectString(_))), de_AnalyticsAndOperator = (_, ee) => {
const ne = {};
if (null != _[_P]) ne[_P] = expectString(_[_P]);
if ("" === _.Tag) ne[_Tag] = []; else if (null != _[_Ta]) ne[_Tag] = de_TagSet(getArrayIfSingleItem(_[_Ta]), ee);
return ne;
}, de_AnalyticsConfiguration = (_, ee) => {
const ne = {};
if (null != _[_I]) ne[_I] = expectString(_[_I]);
if ("" === _.Filter) ; else if (null != _[_F]) ne[_F] = de_AnalyticsFilter(expectUnion(_[_F]), ee);
if (null != _[_SCA]) ne[_SCA] = de_StorageClassAnalysis(_[_SCA], ee);
return ne;
}, de_AnalyticsConfigurationList = (_, ee) => (_ || []).filter((_ => null != _)).map((_ => de_AnalyticsConfiguration(_, ee))), de_AnalyticsExportDestination = (_, ee) => {
const ne = {};
if (null != _[_SBD]) ne[_SBD] = de_AnalyticsS3BucketDestination(_[_SBD], ee);
return ne;
}, de_AnalyticsFilter = (_, ee) => {
if (null != _[_P]) return {
Prefix: expectString(_[_P])
};
if (null != _[_Ta]) return {
Tag: de_Tag(_[_Ta], ee)
};
if (null != _[_A]) return {
And: de_AnalyticsAndOperator(_[_A], ee)
}; else return {
$unknown: Object.entries(_)[0]
};
}, de_AnalyticsS3BucketDestination = (_, ee) => {
const ne = {};
if (null != _[_Fo]) ne[_Fo] = expectString(_[_Fo]);
if (null != _[_BAI]) ne[_BAI] = expectString(_[_BAI]);
if (null != _[_B]) ne[_B] = expectString(_[_B]);
if (null != _[_P]) ne[_P] = expectString(_[_P]);
return ne;
}, de_Bucket = (_, ee) => {
const ne = {};
if (null != _[_N]) ne[_N] = expectString(_[_N]);
if (null != _[_CDr]) ne[_CDr] = expectNonNull(parseRfc3339DateTimeWithOffset(_[_CDr]));
return ne;
}, de_Buckets = (_, ee) => (_ || []).filter((_ => null != _)).map((_ => de_Bucket(_, ee))), de_Checksum = (_, ee) => {
const ne = {};
if (null != _[_CCRC]) ne[_CCRC] = expectString(_[_CCRC]);
if (null != _[_CCRCC]) ne[_CCRCC] = expectString(_[_CCRCC]);
if (null != _[_CSHA]) ne[_CSHA] = expectString(_[_CSHA]);
if (null != _[_CSHAh]) ne[_CSHAh] = expectString(_[_CSHAh]);
return ne;
}, de_ChecksumAlgorithmList = (_, ee) => (_ || []).filter((_ => null != _)).map((_ => expectString(_))), de_CommonPrefix = (_, ee) => {
const ne = {};
if (null != _[_P]) ne[_P] = expectString(_[_P]);
return ne;
}, de_CommonPrefixList = (_, ee) => (_ || []).filter((_ => null != _)).map((_ => de_CommonPrefix(_, ee))), de_Condition = (_, ee) => {
const ne = {};
if (null != _[_HECRE]) ne[_HECRE] = expectString(_[_HECRE]);
if (null != _[_KPE]) ne[_KPE] = expectString(_[_KPE]);
return ne;
}, de_ContinuationEvent = (_, ee) => ({}), de_CopyObjectResult = (_, ee) => {
const ne = {};
if (null != _[_ETa]) ne[_ETa] = expectString(_[_ETa]);
if (null != _[_LM]) ne[_LM] = expectNonNull(parseRfc3339DateTimeWithOffset(_[_LM]));
if (null != _[_CCRC]) ne[_CCRC] = expectString(_[_CCRC]);
if (null != _[_CCRCC]) ne[_CCRCC] = expectString(_[_CCRCC]);
if (null != _[_CSHA]) ne[_CSHA] = expectString(_[_CSHA]);
if (null != _[_CSHAh]) ne[_CSHAh] = expectString(_[_CSHAh]);
return ne;
}, de_CopyPartResult = (_, ee) => {
const ne = {};
if (null != _[_ETa]) ne[_ETa] = expectString(_[_ETa]);
if (null != _[_LM]) ne[_LM] = expectNonNull(parseRfc3339DateTimeWithOffset(_[_LM]));
if (null != _[_CCRC]) ne[_CCRC] = expectString(_[_CCRC]);
if (null != _[_CCRCC]) ne[_CCRCC] = expectString(_[_CCRCC]);
if (null != _[_CSHA]) ne[_CSHA] = expectString(_[_CSHA]);
if (null != _[_CSHAh]) ne[_CSHAh] = expectString(_[_CSHAh]);
return ne;
}, de_CORSRule = (_, ee) => {
const ne = {};
if (null != _[_ID_]) ne[_ID_] = expectString(_[_ID_]);
if ("" === _.AllowedHeader) ne[_AHl] = []; else if (null != _[_AH]) ne[_AHl] = de_AllowedHeaders(getArrayIfSingleItem(_[_AH]), ee);
if ("" === _.AllowedMethod) ne[_AMl] = []; else if (null != _[_AM]) ne[_AMl] = de_AllowedMethods(getArrayIfSingleItem(_[_AM]), ee);
if ("" === _.AllowedOrigin) ne[_AOl] = []; else if (null != _[_AO]) ne[_AOl] = de_AllowedOrigins(getArrayIfSingleItem(_[_AO]), ee);
if ("" === _.ExposeHeader) ne[_EH] = []; else if (null != _[_EHx]) ne[_EH] = de_ExposeHeaders(getArrayIfSingleItem(_[_EHx]), ee);
if (null != _[_MAS]) ne[_MAS] = strictParseInt32(_[_MAS]);
return ne;
}, de_CORSRules = (_, ee) => (_ || []).filter((_ => null != _)).map((_ => de_CORSRule(_, ee))), de_DefaultRetention = (_, ee) => {
const ne = {};
if (null != _[_Mo]) ne[_Mo] = expectString(_[_Mo]);
if (null != _[_Da]) ne[_Da] = strictParseInt32(_[_Da]);
if (null != _[_Y]) ne[_Y] = strictParseInt32(_[_Y]);
return ne;
}, de_DeletedObject = (_, ee) => {
const ne = {};
if (null != _[_K]) ne[_K] = expectString(_[_K]);
if (null != _[_VI]) ne[_VI] = expectString(_[_VI]);
if (null != _[_DM]) ne[_DM] = parseBoolean(_[_DM]);
if (null != _[_DMVI]) ne[_DMVI] = expectString(_[_DMVI]);
return ne;
}, de_DeletedObjects = (_, ee) => (_ || []).filter((_ => null != _)).map((_ => de_DeletedObject(_, ee))), de_DeleteMarkerEntry = (_, ee) => {
const ne = {};
if (null != _[_O]) ne[_O] = de_Owner(_[_O], ee);
if (null != _[_K]) ne[_K] = expectString(_[_K]);
if (null != _[_VI]) ne[_VI] = expectString(_[_VI]);
if (null != _[_IL]) ne[_IL] = parseBoolean(_[_IL]);
if (null != _[_LM]) ne[_LM] = expectNonNull(parseRfc3339DateTimeWithOffset(_[_LM]));
return ne;
}, de_DeleteMarkerReplication = (_, ee) => {
const ne = {};
if (null != _[_S]) ne[_S] = expectString(_[_S]);
return ne;
}, de_DeleteMarkers = (_, ee) => (_ || []).filter((_ => null != _)).map((_ => de_DeleteMarkerEntry(_, ee))), de_Destination = (_, ee) => {
const ne = {};
if (null != _[_B]) ne[_B] = expectString(_[_B]);
if (null != _[_Ac]) ne[_Ac] = expectString(_[_Ac]);
if (null != _[_SC]) ne[_SC] = expectString(_[_SC]);
if (null != _[_ACT]) ne[_ACT] = de_AccessControlTranslation(_[_ACT], ee);
if (null != _[_ECn]) ne[_ECn] = de_EncryptionConfiguration(_[_ECn], ee);
if (null != _[_RTe]) ne[_RTe] = de_ReplicationTime(_[_RTe], ee);
if (null != _[_Me]) ne[_Me] = de_Metrics(_[_Me], ee);
return ne;
}, de_EncryptionConfiguration = (_, ee) => {
const ne = {};
if (null != _[_RKKID]) ne[_RKKID] = expectString(_[_RKKID]);
return ne;
}, de_EndEvent = (_, ee) => ({}), de__Error = (_, ee) => {
const ne = {};
if (null != _[_K]) ne[_K] = expectString(_[_K]);
if (null != _[_VI]) ne[_VI] = expectString(_[_VI]);
if (null != _[_Cod]) ne[_Cod] = expectString(_[_Cod]);
if (null != _[_Mes]) ne[_Mes] = expectString(_[_Mes]);
return ne;
}, de_ErrorDocument = (_, ee) => {
const ne = {};
if (null != _[_K]) ne[_K] = expectString(_[_K]);
return ne;
}, de_Errors = (_, ee) => (_ || []).filter((_ => null != _)).map((_ => de__Error(_, ee))), de_EventBridgeConfiguration = (_, ee) => ({}), de_EventList = (_, ee) => (_ || []).filter((_ => null != _)).map((_ => expectString(_))), de_ExistingObjectReplication = (_, ee) => {
const ne = {};
if (null != _[_S]) ne[_S] = expectString(_[_S]);
return ne;
}, de_ExposeHeaders = (_, ee) => (_ || []).filter((_ => null != _)).map((_ => expectString(_))), de_FilterRule = (_, ee) => {
const ne = {};
if (null != _[_N]) ne[_N] = expectString(_[_N]);
if (null != _[_Va]) ne[_Va] = expectString(_[_Va]);
return ne;
}, de_FilterRuleList = (_, ee) => (_ || []).filter((_ => null != _)).map((_ => de_FilterRule(_, ee))), de_GetObjectAttributesParts = (_, ee) => {
const ne = {};
if (null != _[_PC]) ne[_TPC] = strictParseInt32(_[_PC]);
if (null != _[_PNM]) ne[_PNM] = expectString(_[_PNM]);
if (null != _[_NPNM]) ne[_NPNM] = expectString(_[_NPNM]);
if (null != _[_MP]) ne[_MP] = strictParseInt32(_[_MP]);
if (null != _[_IT]) ne[_IT] = parseBoolean(_[_IT]);
if ("" === _.Part) ne[_Part] = []; else if (null != _[_Par]) ne[_Part] = de_PartsList(getArrayIfSingleItem(_[_Par]), ee);
return ne;
}, de_Grant = (_, ee) => {
const ne = {};
if (null != _[_Gra]) ne[_Gra] = de_Grantee(_[_Gra], ee);
if (null != _[_Pe]) ne[_Pe] = expectString(_[_Pe]);
return ne;
}, de_Grantee = (_, ee) => {
const ne = {};
if (null != _[_DN]) ne[_DN] = expectString(_[_DN]);
if (null != _[_EA]) ne[_EA] = expectString(_[_EA]);
if (null != _[_ID_]) ne[_ID_] = expectString(_[_ID_]);
if (null != _[_URI]) ne[_URI] = expectString(_[_URI]);
if (null != _[_x]) ne[_Ty] = expectString(_[_x]);
return ne;
}, de_Grants = (_, ee) => (_ || []).filter((_ => null != _)).map((_ => de_Grant(_, ee))), de_IndexDocument = (_, ee) => {
const ne = {};
if (null != _[_Su]) ne[_Su] = expectString(_[_Su]);
return ne;
}, de_Initiator = (_, ee) => {
const ne = {};
if (null != _[_ID_]) ne[_ID_] = expectString(_[_ID_]);
if (null != _[_DN]) ne[_DN] = expectString(_[_DN]);
return ne;
}, de_IntelligentTieringAndOperator = (_, ee) => {
const ne = {};
if (null != _[_P]) ne[_P] = expectString(_[_P]);
if ("" === _.Tag) ne[_Tag] = []; else if (null != _[_Ta]) ne[_Tag] = de_TagSet(getArrayIfSingleItem(_[_Ta]), ee);
return ne;
}, de_IntelligentTieringConfiguration = (_, ee) => {
const ne = {};
if (null != _[_I]) ne[_I] = expectString(_[_I]);
if (null != _[_F]) ne[_F] = de_IntelligentTieringFilter(_[_F], ee);
if (null != _[_S]) ne[_S] = expectString(_[_S]);
if ("" === _.Tiering) ne[_Tie] = []; else if (null != _[_Tier]) ne[_Tie] = de_TieringList(getArrayIfSingleItem(_[_Tier]), ee);
return ne;
}, de_IntelligentTieringConfigurationList = (_, ee) => (_ || []).filter((_ => null != _)).map((_ => de_IntelligentTieringConfiguration(_, ee))), de_IntelligentTieringFilter = (_, ee) => {
const ne = {};
if (null != _[_P]) ne[_P] = expectString(_[_P]);
if (null != _[_Ta]) ne[_Ta] = de_Tag(_[_Ta], ee);
if (null != _[_A]) ne[_A] = de_IntelligentTieringAndOperator(_[_A], ee);
return ne;
}, de_InventoryConfiguration = (_, ee) => {
const ne = {};
if (null != _[_Des]) ne[_Des] = de_InventoryDestination(_[_Des], ee);
if (null != _[_IE]) ne[_IE] = parseBoolean(_[_IE]);
if (null != _[_F]) ne[_F] = de_InventoryFilter(_[_F], ee);
if (null != _[_I]) ne[_I] = expectString(_[_I]);
if (null != _[_IOV]) ne[_IOV] = expectString(_[_IOV]);
if ("" === _.OptionalFields) ne[_OF] = []; else if (null != _[_OF] && null != _[_OF][_Fi]) ne[_OF] = de_InventoryOptionalFields(getArrayIfSingleItem(_[_OF][_Fi]), ee);
if (null != _[_Sc]) ne[_Sc] = de_InventorySchedule(_[_Sc], ee);
return ne;
}, de_InventoryConfigurationList = (_, ee) => (_ || []).filter((_ => null != _)).map((_ => de_InventoryConfiguration(_, ee))), de_InventoryDestination = (_, ee) => {
const ne = {};
if (null != _[_SBD]) ne[_SBD] = de_InventoryS3BucketDestination(_[_SBD], ee);
return ne;
}, de_InventoryEncryption = (_, ee) => {
const ne = {};
if (null != _[_SS]) ne[_SSES] = de_SSES3(_[_SS], ee);
if (null != _[_SK]) ne[_SSEKMS] = de_SSEKMS(_[_SK], ee);
return ne;
}, de_InventoryFilter = (_, ee) => {
const ne = {};
if (null != _[_P]) ne[_P] = expectString(_[_P]);
return ne;
}, de_InventoryOptionalFields = (_, ee) => (_ || []).filter((_ => null != _)).map((_ => expectString(_))), de_InventoryS3BucketDestination = (_, ee) => {
const ne = {};
if (null != _[_AIc]) ne[_AIc] = expectString(_[_AIc]);
if (null != _[_B]) ne[_B] = expectString(_[_B]);
if (null != _[_Fo]) ne[_Fo] = expectString(_[_Fo]);
if (null != _[_P]) ne[_P] = expectString(_[_P]);
if (null != _[_En]) ne[_En] = de_InventoryEncryption(_[_En], ee);
return ne;
}, de_InventorySchedule = (_, ee) => {
const ne = {};
if (null != _[_Fr]) ne[_Fr] = expectString(_[_Fr]);
return ne;
}, de_LambdaFunctionConfiguration = (_, ee) => {
const ne = {};
if (null != _[_I]) ne[_I] = expectString(_[_I]);
if (null != _[_CF]) ne[_LFA] = expectString(_[_CF]);
if ("" === _.Event) ne[_Eve] = []; else if (null != _[_Ev]) ne[_Eve] = de_EventList(getArrayIfSingleItem(_[_Ev]), ee);
if (null != _[_F]) ne[_F] = de_NotificationConfigurationFilter(_[_F], ee);
return ne;
}, de_LambdaFunctionConfigurationList = (_, ee) => (_ || []).filter((_ => null != _)).map((_ => de_LambdaFunctionConfiguration(_, ee))), de_LifecycleExpiration = (_, ee) => {
const ne = {};
if (null != _[_Dat]) ne[_Dat] = expectNonNull(parseRfc3339DateTimeWithOffset(_[_Dat]));
if (null != _[_Da]) ne[_Da] = strictParseInt32(_[_Da]);
if (null != _[_EODM]) ne[_EODM] = parseBoolean(_[_EODM]);
return ne;
}, de_LifecycleRule = (_, ee) => {
const ne = {};
if (null != _[_Exp]) ne[_Exp] = de_LifecycleExpiration(_[_Exp], ee);
if (null != _[_ID_]) ne[_ID_] = expectString(_[_ID_]);
if (null != _[_P]) ne[_P] = expectString(_[_P]);
if ("" === _.Filter) ; else if (null != _[_F]) ne[_F] = de_LifecycleRuleFilter(expectUnion(_[_F]), ee);
if (null != _[_S]) ne[_S] = expectString(_[_S]);
if ("" === _.Transition) ne[_Tr] = []; else if (null != _[_Tra]) ne[_Tr] = de_TransitionList(getArrayIfSingleItem(_[_Tra]), ee);
if ("" === _.NoncurrentVersionTransition) ne[_NVT] = []; else if (null != _[_NVTo]) ne[_NVT] = de_NoncurrentVersionTransitionList(getArrayIfSingleItem(_[_NVTo]), ee);
if (null != _[_NVE]) ne[_NVE] = de_NoncurrentVersionExpiration(_[_NVE], ee);
if (null != _[_AIMU]) ne[_AIMU] = de_AbortIncompleteMultipartUpload(_[_AIMU], ee);
return ne;
}, de_LifecycleRuleAndOperator = (_, ee) => {
const ne = {};
if (null != _[_P]) ne[_P] = expectString(_[_P]);
if ("" === _.Tag) ne[_Tag] = []; else if (null != _[_Ta]) ne[_Tag] = de_TagSet(getArrayIfSingleItem(_[_Ta]), ee);
if (null != _[_OSGT]) ne[_OSGT] = strictParseLong(_[_OSGT]);
if (null != _[_OSLT]) ne[_OSLT] = strictParseLong(_[_OSLT]);
return ne;
}, de_LifecycleRuleFilter = (_, ee) => {
if (null != _[_P]) return {
Prefix: expectString(_[_P])
};
if (null != _[_Ta]) return {
Tag: de_Tag(_[_Ta], ee)
};
if (null != _[_OSGT]) return {
ObjectSizeGreaterThan: strictParseLong(_[_OSGT])
};
if (null != _[_OSLT]) return {
ObjectSizeLessThan: strictParseLong(_[_OSLT])
};
if (null != _[_A]) return {
And: de_LifecycleRuleAndOperator(_[_A], ee)
}; else return {
$unknown: Object.entries(_)[0]
};
}, de_LifecycleRules = (_, ee) => (_ || []).filter((_ => null != _)).map((_ => de_LifecycleRule(_, ee))), de_LoggingEnabled = (_, ee) => {
const ne = {};
if (null != _[_TB]) ne[_TB] = expectString(_[_TB]);
if ("" === _.TargetGrants) ne[_TG] = []; else if (null != _[_TG] && null != _[_TG][_G]) ne[_TG] = de_TargetGrants(getArrayIfSingleItem(_[_TG][_G]), ee);
if (null != _[_TP]) ne[_TP] = expectString(_[_TP]);
if (null != _[_TOKF]) ne[_TOKF] = de_TargetObjectKeyFormat(_[_TOKF], ee);
return ne;
}, de_Metrics = (_, ee) => {
const ne = {};
if (null != _[_S]) ne[_S] = expectString(_[_S]);
if (null != _[_ETv]) ne[_ETv] = de_ReplicationTimeValue(_[_ETv], ee);
return ne;
}, de_MetricsAndOperator = (_, ee) => {
const ne = {};
if (null != _[_P]) ne[_P] = expectString(_[_P]);
if ("" === _.Tag) ne[_Tag] = []; else if (null != _[_Ta]) ne[_Tag] = de_TagSet(getArrayIfSingleItem(_[_Ta]), ee);
if (null != _[_APAc]) ne[_APAc] = expectString(_[_APAc]);
return ne;
}, de_MetricsConfiguration = (_, ee) => {
const ne = {};
if (null != _[_I]) ne[_I] = expectString(_[_I]);
if ("" === _.Filter) ; else if (null != _[_F]) ne[_F] = de_MetricsFilter(expectUnion(_[_F]), ee);
return ne;
}, de_MetricsConfigurationList = (_, ee) => (_ || []).filter((_ => null != _)).map((_ => de_MetricsConfiguration(_, ee))), de_MetricsFilter = (_, ee) => {
if (null != _[_P]) return {
Prefix: expectString(_[_P])
};
if (null != _[_Ta]) return {
Tag: de_Tag(_[_Ta], ee)
};
if (null != _[_APAc]) return {
AccessPointArn: expectString(_[_APAc])
};
if (null != _[_A]) return {
And: de_MetricsAndOperator(_[_A], ee)
}; else return {
$unknown: Object.entries(_)[0]
};
}, de_MultipartUpload = (_, ee) => {
const ne = {};
if (null != _[_UI]) ne[_UI] = expectString(_[_UI]);
if (null != _[_K]) ne[_K] = expectString(_[_K]);
if (null != _[_Ini]) ne[_Ini] = expectNonNull(parseRfc3339DateTimeWithOffset(_[_Ini]));
if (null != _[_SC]) ne[_SC] = expectString(_[_SC]);
if (null != _[_O]) ne[_O] = de_Owner(_[_O], ee);
if (null != _[_In]) ne[_In] = de_Initiator(_[_In], ee);
if (null != _[_CA]) ne[_CA] = expectString(_[_CA]);
return ne;
}, de_MultipartUploadList = (_, ee) => (_ || []).filter((_ => null != _)).map((_ => de_MultipartUpload(_, ee))), de_NoncurrentVersionExpiration = (_, ee) => {
const ne = {};
if (null != _[_ND]) ne[_ND] = strictParseInt32(_[_ND]);
if (null != _[_NNV]) ne[_NNV] = strictParseInt32(_[_NNV]);
return ne;
}, de_NoncurrentVersionTransition = (_, ee) => {
const ne = {};
if (null != _[_ND]) ne[_ND] = strictParseInt32(_[_ND]);
if (null != _[_SC]) ne[_SC] = expectString(_[_SC]);
if (null != _[_NNV]) ne[_NNV] = strictParseInt32(_[_NNV]);
return ne;
}, de_NoncurrentVersionTransitionList = (_, ee) => (_ || []).filter((_ => null != _)).map((_ => de_NoncurrentVersionTransition(_, ee))), de_NotificationConfigurationFilter = (_, ee) => {
const ne = {};
if (null != _[_SKe]) ne[_K] = de_S3KeyFilter(_[_SKe], ee);
return ne;
}, de__Object = (_, ee) => {
const ne = {};
if (null != _[_K]) ne[_K] = expectString(_[_K]);
if (null != _[_LM]) ne[_LM] = expectNonNull(parseRfc3339DateTimeWithOffset(_[_LM]));
if (null != _[_ETa]) ne[_ETa] = expectString(_[_ETa]);
if ("" === _.ChecksumAlgorithm) ne[_CA] = []; else if (null != _[_CA]) ne[_CA] = de_ChecksumAlgorithmList(getArrayIfSingleItem(_[_CA]), ee);
if (null != _[_Si]) ne[_Si] = strictParseLong(_[_Si]);
if (null != _[_SC]) ne[_SC] = expectString(_[_SC]);
if (null != _[_O]) ne[_O] = de_Owner(_[_O], ee);
if (null != _[_RSe]) ne[_RSe] = de_RestoreStatus(_[_RSe], ee);
return ne;
}, de_ObjectList = (_, ee) => (_ || []).filter((_ => null != _)).map((_ => de__Object(_, ee))), de_ObjectLockConfiguration = (_, ee) => {
const ne = {};
if (null != _[_OLE]) ne[_OLE] = expectString(_[_OLE]);
if (null != _[_Ru]) ne[_Ru] = de_ObjectLockRule(_[_Ru], ee);
return ne;
}, de_ObjectLockLegalHold = (_, ee) => {
const ne = {};
if (null != _[_S]) ne[_S] = expectString(_[_S]);
return ne;
}, de_ObjectLockRetention = (_, ee) => {
const ne = {};
if (null != _[_Mo]) ne[_Mo] = expectString(_[_Mo]);
if (null != _[_RUD]) ne[_RUD] = expectNonNull(parseRfc3339DateTimeWithOffset(_[_RUD]));
return ne;
}, de_ObjectLockRule = (_, ee) => {
const ne = {};
if (null != _[_DRe]) ne[_DRe] = de_DefaultRetention(_[_DRe], ee);
return ne;
}, de_ObjectPart = (_, ee) => {
const ne = {};
if (null != _[_PN]) ne[_PN] = strictParseInt32(_[_PN]);
if (null != _[_Si]) ne[_Si] = strictParseLong(_[_Si]);
if (null != _[_CCRC]) ne[_CCRC] = expectString(_[_CCRC]);
if (null != _[_CCRCC]) ne[_CCRCC] = expectString(_[_CCRCC]);
if (null != _[_CSHA]) ne[_CSHA] = expectString(_[_CSHA]);
if (null != _[_CSHAh]) ne[_CSHAh] = expectString(_[_CSHAh]);
return ne;
}, de_ObjectVersion = (_, ee) => {
const ne = {};
if (null != _[_ETa]) ne[_ETa] = expectString(_[_ETa]);
if ("" === _.ChecksumAlgorithm) ne[_CA] = []; else if (null != _[_CA]) ne[_CA] = de_ChecksumAlgorithmList(getArrayIfSingleItem(_[_CA]), ee);
if (null != _[_Si]) ne[_Si] = strictParseLong(_[_Si]);
if (null != _[_SC]) ne[_SC] = expectString(_[_SC]);
if (null != _[_K]) ne[_K] = expectString(_[_K]);
if (null != _[_VI]) ne[_VI] = expectString(_[_VI]);
if (null != _[_IL]) ne[_IL] = parseBoolean(_[_IL]);
if (null != _[_LM]) ne[_LM] = expectNonNull(parseRfc3339DateTimeWithOffset(_[_LM]));
if (null != _[_O]) ne[_O] = de_Owner(_[_O], ee);
if (null != _[_RSe]) ne[_RSe] = de_RestoreStatus(_[_RSe], ee);
return ne;
}, de_ObjectVersionList = (_, ee) => (_ || []).filter((_ => null != _)).map((_ => de_ObjectVersion(_, ee))), de_Owner = (_, ee) => {
const ne = {};
if (null != _[_DN]) ne[_DN] = expectString(_[_DN]);
if (null != _[_ID_]) ne[_ID_] = expectString(_[_ID_]);
return ne;
}, de_OwnershipControls = (_, ee) => {
const ne = {};
if ("" === _.Rule) ne[_Rul] = []; else if (null != _[_Ru]) ne[_Rul] = de_OwnershipControlsRules(getArrayIfSingleItem(_[_Ru]), ee);
return ne;
}, de_OwnershipControlsRule = (_, ee) => {
const ne = {};
if (null != _[_OO]) ne[_OO] = expectString(_[_OO]);
return ne;
}, de_OwnershipControlsRules = (_, ee) => (_ || []).filter((_ => null != _)).map((_ => de_OwnershipControlsRule(_, ee))), de_Part = (_, ee) => {
const ne = {};
if (null != _[_PN]) ne[_PN] = strictParseInt32(_[_PN]);
if (null != _[_LM]) ne[_LM] = expectNonNull(parseRfc3339DateTimeWithOffset(_[_LM]));
if (null != _[_ETa]) ne[_ETa] = expectString(_[_ETa]);
if (null != _[_Si]) ne[_Si] = strictParseLong(_[_Si]);
if (null != _[_CCRC]) ne[_CCRC] = expectString(_[_CCRC]);
if (null != _[_CCRCC]) ne[_CCRCC] = expectString(_[_CCRCC]);
if (null != _[_CSHA]) ne[_CSHA] = expectString(_[_CSHA]);
if (null != _[_CSHAh]) ne[_CSHAh] = expectString(_[_CSHAh]);
return ne;
}, de_PartitionedPrefix = (_, ee) => {
const ne = {};
if (null != _[_PDS]) ne[_PDS] = expectString(_[_PDS]);
return ne;
}, de_Parts = (_, ee) => (_ || []).filter((_ => null != _)).map((_ => de_Part(_, ee))), de_PartsList = (_, ee) => (_ || []).filter((_ => null != _)).map((_ => de_ObjectPart(_, ee))), de_PolicyStatus = (_, ee) => {
const ne = {};
if (null != _[_IP]) ne[_IP] = parseBoolean(_[_IP]);
return ne;
}, de_Progress = (_, ee) => {
const ne = {};
if (null != _[_BS]) ne[_BS] = strictParseLong(_[_BS]);
if (null != _[_BP]) ne[_BP] = strictParseLong(_[_BP]);
if (null != _[_BRy]) ne[_BRy] = strictParseLong(_[_BRy]);
return ne;
}, de_PublicAccessBlockConfiguration = (_, ee) => {
const ne = {};
if (null != _[_BPA]) ne[_BPA] = parseBoolean(_[_BPA]);
if (null != _[_IPA]) ne[_IPA] = parseBoolean(_[_IPA]);
if (null != _[_BPP]) ne[_BPP] = parseBoolean(_[_BPP]);
if (null != _[_RPB]) ne[_RPB] = parseBoolean(_[_RPB]);
return ne;
}, de_QueueConfiguration = (_, ee) => {
const ne = {};
if (null != _[_I]) ne[_I] = expectString(_[_I]);
if (null != _[_Qu]) ne[_QA] = expectString(_[_Qu]);
if ("" === _.Event) ne[_Eve] = []; else if (null != _[_Ev]) ne[_Eve] = de_EventList(getArrayIfSingleItem(_[_Ev]), ee);
if (null != _[_F]) ne[_F] = de_NotificationConfigurationFilter(_[_F], ee);
return ne;
}, de_QueueConfigurationList = (_, ee) => (_ || []).filter((_ => null != _)).map((_ => de_QueueConfiguration(_, ee))), de_Redirect = (_, ee) => {
const ne = {};
if (null != _[_HN]) ne[_HN] = expectString(_[_HN]);
if (null != _[_HRC]) ne[_HRC] = expectString(_[_HRC]);
if (null != _[_Pr]) ne[_Pr] = expectString(_[_Pr]);
if (null != _[_RKPW]) ne[_RKPW] = expectString(_[_RKPW]);
if (null != _[_RKW]) ne[_RKW] = expectString(_[_RKW]);
return ne;
}, de_RedirectAllRequestsTo = (_, ee) => {
const ne = {};
if (null != _[_HN]) ne[_HN] = expectString(_[_HN]);
if (null != _[_Pr]) ne[_Pr] = expectString(_[_Pr]);
return ne;
}, de_ReplicaModifications = (_, ee) => {
const ne = {};
if (null != _[_S]) ne[_S] = expectString(_[_S]);
return ne;
}, de_ReplicationConfiguration = (_, ee) => {
const ne = {};
if (null != _[_Ro]) ne[_Ro] = expectString(_[_Ro]);
if ("" === _.Rule) ne[_Rul] = []; else if (null != _[_Ru]) ne[_Rul] = de_ReplicationRules(getArrayIfSingleItem(_[_Ru]), ee);
return ne;
}, de_ReplicationRule = (_, ee) => {
const ne = {};
if (null != _[_ID_]) ne[_ID_] = expectString(_[_ID_]);
if (null != _[_Pri]) ne[_Pri] = strictParseInt32(_[_Pri]);
if (null != _[_P]) ne[_P] = expectString(_[_P]);
if ("" === _.Filter) ; else if (null != _[_F]) ne[_F] = de_ReplicationRuleFilter(expectUnion(_[_F]), ee);
if (null != _[_S]) ne[_S] = expectString(_[_S]);
if (null != _[_SSC]) ne[_SSC] = de_SourceSelectionCriteria(_[_SSC], ee);
if (null != _[_EOR]) ne[_EOR] = de_ExistingObjectReplication(_[_EOR], ee);
if (null != _[_Des]) ne[_Des] = de_Destination(_[_Des], ee);
if (null != _[_DMR]) ne[_DMR] = de_DeleteMarkerReplication(_[_DMR], ee);
return ne;
}, de_ReplicationRuleAndOperator = (_, ee) => {
const ne = {};
if (null != _[_P]) ne[_P] = expectString(_[_P]);
if ("" === _.Tag) ne[_Tag] = []; else if (null != _[_Ta]) ne[_Tag] = de_TagSet(getArrayIfSingleItem(_[_Ta]), ee);
return ne;
}, de_ReplicationRuleFilter = (_, ee) => {
if (null != _[_P]) return {
Prefix: expectString(_[_P])
};
if (null != _[_Ta]) return {
Tag: de_Tag(_[_Ta], ee)
};
if (null != _[_A]) return {
And: de_ReplicationRuleAndOperator(_[_A], ee)
}; else return {
$unknown: Object.entries(_)[0]
};
}, de_ReplicationRules = (_, ee) => (_ || []).filter((_ => null != _)).map((_ => de_ReplicationRule(_, ee))), de_ReplicationTime = (_, ee) => {
const ne = {};
if (null != _[_S]) ne[_S] = expectString(_[_S]);
if (null != _[_Tim]) ne[_Tim] = de_ReplicationTimeValue(_[_Tim], ee);
return ne;
}, de_ReplicationTimeValue = (_, ee) => {
const ne = {};
if (null != _[_Mi]) ne[_Mi] = strictParseInt32(_[_Mi]);
return ne;
}, de_RestoreStatus = (_, ee) => {
const ne = {};
if (null != _[_IRIP]) ne[_IRIP] = parseBoolean(_[_IRIP]);
if (null != _[_RED]) ne[_RED] = expectNonNull(parseRfc3339DateTimeWithOffset(_[_RED]));
return ne;
}, de_RoutingRule = (_, ee) => {
const ne = {};
if (null != _[_Con]) ne[_Con] = de_Condition(_[_Con], ee);
if (null != _[_Red]) ne[_Red] = de_Redirect(_[_Red], ee);
return ne;
}, de_RoutingRules = (_, ee) => (_ || []).filter((_ => null != _)).map((_ => de_RoutingRule(_, ee))), de_S3KeyFilter = (_, ee) => {
const ne = {};
if ("" === _.FilterRule) ne[_FRi] = []; else if (null != _[_FR]) ne[_FRi] = de_FilterRuleList(getArrayIfSingleItem(_[_FR]), ee);
return ne;
}, de_ServerSideEncryptionByDefault = (_, ee) => {
const ne = {};
if (null != _[_SSEA]) ne[_SSEA] = expectString(_[_SSEA]);
if (null != _[_KMSMKID]) ne[_KMSMKID] = expectString(_[_KMSMKID]);
return ne;
}, de_ServerSideEncryptionConfiguration = (_, ee) => {
const ne = {};
if ("" === _.Rule) ne[_Rul] = []; else if (null != _[_Ru]) ne[_Rul] = de_ServerSideEncryptionRules(getArrayIfSingleItem(_[_Ru]), ee);
return ne;
}, de_ServerSideEncryptionRule = (_, ee) => {
const ne = {};
if (null != _[_ASSEBD]) ne[_ASSEBD] = de_ServerSideEncryptionByDefault(_[_ASSEBD], ee);
if (null != _[_BKE]) ne[_BKE] = parseBoolean(_[_BKE]);
return ne;
}, de_ServerSideEncryptionRules = (_, ee) => (_ || []).filter((_ => null != _)).map((_ => de_ServerSideEncryptionRule(_, ee))), de_SessionCredentials = (_, ee) => {
const ne = {};
if (null != _[_AKI]) ne[_AKI] = expectString(_[_AKI]);
if (null != _[_SAK]) ne[_SAK] = expectString(_[_SAK]);
if (null != _[_ST]) ne[_ST] = expectString(_[_ST]);
if (null != _[_Exp]) ne[_Exp] = expectNonNull(parseRfc3339DateTimeWithOffset(_[_Exp]));
return ne;
}, de_SimplePrefix = (_, ee) => ({}), de_SourceSelectionCriteria = (_, ee) => {
const ne = {};
if (null != _[_SKEO]) ne[_SKEO] = de_SseKmsEncryptedObjects(_[_SKEO], ee);
if (null != _[_RM]) ne[_RM] = de_ReplicaModifications(_[_RM], ee);
return ne;
}, de_SSEKMS = (_, ee) => {
const ne = {};
if (null != _[_KI]) ne[_KI] = expectString(_[_KI]);
return ne;
}, de_SseKmsEncryptedObjects = (_, ee) => {
const ne = {};
if (null != _[_S]) ne[_S] = expectString(_[_S]);
return ne;
}, de_SSES3 = (_, ee) => ({}), de_Stats = (_, ee) => {
const ne = {};
if (null != _[_BS]) ne[_BS] = strictParseLong(_[_BS]);
if (null != _[_BP]) ne[_BP] = strictParseLong(_[_BP]);
if (null != _[_BRy]) ne[_BRy] = strictParseLong(_[_BRy]);
return ne;
}, de_StorageClassAnalysis = (_, ee) => {
const ne = {};
if (null != _[_DE]) ne[_DE] = de_StorageClassAnalysisDataExport(_[_DE], ee);
return ne;
}, de_StorageClassAnalysisDataExport = (_, ee) => {
const ne = {};
if (null != _[_OSV]) ne[_OSV] = expectString(_[_OSV]);
if (null != _[_Des]) ne[_Des] = de_AnalyticsExportDestination(_[_Des], ee);
return ne;
}, de_Tag = (_, ee) => {
const ne = {};
if (null != _[_K]) ne[_K] = expectString(_[_K]);
if (null != _[_Va]) ne[_Va] = expectString(_[_Va]);
return ne;
}, de_TagSet = (_, ee) => (_ || []).filter((_ => null != _)).map((_ => de_Tag(_, ee))), de_TargetGrant = (_, ee) => {
const ne = {};
if (null != _[_Gra]) ne[_Gra] = de_Grantee(_[_Gra], ee);
if (null != _[_Pe]) ne[_Pe] = expectString(_[_Pe]);
return ne;
}, de_TargetGrants = (_, ee) => (_ || []).filter((_ => null != _)).map((_ => de_TargetGrant(_, ee))), de_TargetObjectKeyFormat = (_, ee) => {
const ne = {};
if (null != _[_SPi]) ne[_SPi] = de_SimplePrefix(_[_SPi], ee);
if (null != _[_PP]) ne[_PP] = de_PartitionedPrefix(_[_PP], ee);
return ne;
}, de_Tiering = (_, ee) => {
const ne = {};
if (null != _[_Da]) ne[_Da] = strictParseInt32(_[_Da]);
if (null != _[_AT]) ne[_AT] = expectString(_[_AT]);
return ne;
}, de_TieringList = (_, ee) => (_ || []).filter((_ => null != _)).map((_ => de_Tiering(_, ee))), de_TopicConfiguration = (_, ee) => {
const ne = {};
if (null != _[_I]) ne[_I] = expectString(_[_I]);
if (null != _[_Top]) ne[_TA] = expectString(_[_Top]);
if ("" === _.Event) ne[_Eve] = []; else if (null != _[_Ev]) ne[_Eve] = de_EventList(getArrayIfSingleItem(_[_Ev]), ee);
if (null != _[_F]) ne[_F] = de_NotificationConfigurationFilter(_[_F], ee);
return ne;
}, de_TopicConfigurationList = (_, ee) => (_ || []).filter((_ => null != _)).map((_ => de_TopicConfiguration(_, ee))), de_Transition = (_, ee) => {
const ne = {};
if (null != _[_Dat]) ne[_Dat] = expectNonNull(parseRfc3339DateTimeWithOffset(_[_Dat]));
if (null != _[_Da]) ne[_Da] = strictParseInt32(_[_Da]);
if (null != _[_SC]) ne[_SC] = expectString(_[_SC]);
return ne;
}, de_TransitionList = (_, ee) => (_ || []).filter((_ => null != _)).map((_ => de_Transition(_, ee))), deserializeMetadata2 = _ => {
var ee, ne;
return {
httpStatusCode: _.statusCode,
requestId: null != (ne = null != (ee = _.headers["x-amzn-requestid"]) ? ee : _.headers["x-amzn-request-id"]) ? ne : _.headers["x-amz-request-id"],
extendedRequestId: _.headers["x-amz-id-2"],
cfId: _.headers["x-amz-cf-id"]
};
}, collectBodyString3 = (_, ee) => collectBody(_, ee).then((_ => ee.utf8Encoder(_))), isSerializableHeaderValue = _ => !(null == _ || "" === _ || Object.getOwnPropertyNames(_).includes("length") && 0 == _.length || Object.getOwnPropertyNames(_).includes("size") && 0 == _.size), _A = "And", _AAO = "AnalyticsAndOperator", _AC = "AnalyticsConfiguration", _ACL = "ACL", _ACLc = "AccessControlList", _ACLn = "AnalyticsConfigurationList", _ACP = "AccessControlPolicy", _ACT = "AccessControlTranslation", _ACc = "AccelerateConfiguration", _AD = "AbortDate", _AED = "AnalyticsExportDestination", _AF = "AnalyticsFilter", _AH = "AllowedHeader", _AHl = "AllowedHeaders", _AI = "AnalyticsId", _AIMU = "AbortIncompleteMultipartUpload", _AIc = "AccountId", _AKI = "AccessKeyId", _AM = "AllowedMethod", _AMl = "AllowedMethods", _AO = "AllowedOrigin", _AOl = "AllowedOrigins", _APA = "AccessPointAlias", _APAc = "AccessPointArn", _AQRD = "AllowQuotedRecordDelimiter", _AR = "AcceptRanges", _ARI = "AbortRuleId", _AS = "ArchiveStatus", _ASBD = "AnalyticsS3BucketDestination", _ASEFF = "AnalyticsS3ExportFileFormat", _ASSEBD = "ApplyServerSideEncryptionByDefault", _AT = "AccessTier", _Ac = "Account", _B = "Bucket", _BAI = "BucketAccountId", _BAS = "BucketAccelerateStatus", _BGR = "BypassGovernanceRetention", _BI = "BucketInfo", _BKE = "BucketKeyEnabled", _BLC = "BucketLifecycleConfiguration", _BLCu = "BucketLocationConstraint", _BLN = "BucketLocationName", _BLP = "BucketLogsPermission", _BLS = "BucketLoggingStatus", _BLT = "BucketLocationType", _BN = "BucketName", _BP = "BytesProcessed", _BPA = "BlockPublicAcls", _BPP = "BlockPublicPolicy", _BR = "BucketRegion", _BRy = "BytesReturned", _BS = "BytesScanned", _BT = "BucketType", _BVS = "BucketVersioningStatus", _Bu = "Buckets", _C = "Credentials", _CA = "ChecksumAlgorithm", _CACL = "CannedACL", _CBC = "CreateBucketConfiguration", _CC = "CacheControl", _CCRC = "ChecksumCRC32", _CCRCC = "ChecksumCRC32C", _CD = "ContentDisposition", _CDr = "CreationDate", _CE = "ContentEncoding", _CF = "CloudFunction", _CFC = "CloudFunctionConfiguration", _CL = "ContentLanguage", _CLo = "ContentLength", _CM = "ChecksumMode", _CMD = "ContentMD5", _CMU = "CompletedMultipartUpload", _CORSC = "CORSConfiguration", _CORSR = "CORSRule", _CORSRu = "CORSRules", _CP = "CommonPrefixes", _CPo = "CompletedPart", _CR = "ContentRange", _CRSBA = "ConfirmRemoveSelfBucketAccess", _CS = "CopySource", _CSHA = "ChecksumSHA1", _CSHAh = "ChecksumSHA256", _CSIM = "CopySourceIfMatch", _CSIMS = "CopySourceIfModifiedSince", _CSINM = "CopySourceIfNoneMatch", _CSIUS = "CopySourceIfUnmodifiedSince", _CSR = "CopySourceRange", _CSSSECA = "CopySourceSSECustomerAlgorithm", _CSSSECK = "CopySourceSSECustomerKey", _CSSSECKMD = "CopySourceSSECustomerKeyMD5", _CSV = "CSV", _CSVI = "CopySourceVersionId", _CSVIn = "CSVInput", _CSVO = "CSVOutput", _CT = "ContentType", _CTo = "ContinuationToken", _CTom = "CompressionType", _Ch = "Checksum", _Co = "Contents", _Cod = "Code", _Com = "Comments", _Con = "Condition", _D = "Delimiter", _DAI = "DaysAfterInitiation", _DE = "DataExport", _DM = "DeleteMarker", _DMR = "DeleteMarkerReplication", _DMRS = "DeleteMarkerReplicationStatus", _DMVI = "DeleteMarkerVersionId", _DMe = "DeleteMarkers", _DN = "DisplayName", _DR = "DataRedundancy", _DRe = "DefaultRetention", _Da = "Days", _Dat = "Date", _De = "Deleted", _Del = "Delete", _Des = "Destination", _Desc = "Description", _E = "Expires", _EA = "EmailAddress", _EBC = "EventBridgeConfiguration", _EBO = "ExpectedBucketOwner", _EC = "ErrorCode", _ECn = "EncryptionConfiguration", _ED = "ErrorDocument", _EH = "ExposeHeaders", _EHx = "ExposeHeader", _EM = "ErrorMessage", _EODM = "ExpiredObjectDeleteMarker", _EOR = "ExistingObjectReplication", _EORS = "ExistingObjectReplicationStatus", _ERP = "EnableRequestProgress", _ES = "ExpiresString", _ESBO = "ExpectedSourceBucketOwner", _ESx = "ExpirationStatus", _ET = "EncodingType", _ETa = "ETag", _ETn = "EncryptionType", _ETv = "EventThreshold", _ETx = "ExpressionType", _En = "Encryption", _Ena = "Enabled", _End = "End", _Er = "Error", _Err = "Errors", _Ev = "Event", _Eve = "Events", _Ex = "Expression", _Exp = "Expiration", _F = "Filter", _FD = "FieldDelimiter", _FHI = "FileHeaderInfo", _FO = "FetchOwner", _FR = "FilterRule", _FRN = "FilterRuleName", _FRV = "FilterRuleValue", _FRi = "FilterRules", _Fi = "Field", _Fo = "Format", _Fr = "Frequency", _G = "Grant", _GFC = "GrantFullControl", _GJP = "GlacierJobParameters", _GR = "GrantRead", _GRACP = "GrantReadACP", _GW = "GrantWrite", _GWACP = "GrantWriteACP", _Gr = "Grants", _Gra = "Grantee", _HECRE = "HttpErrorCodeReturnedEquals", _HN = "HostName", _HRC = "HttpRedirectCode", _I = "Id", _IC = "InventoryConfiguration", _ICL = "InventoryConfigurationList", _ID = "IndexDocument", _ID_ = "ID", _IDn = "InventoryDestination", _IE = "IsEnabled", _IEn = "InventoryEncryption", _IF = "InventoryFilter", _IFn = "InventoryFormat", _IFnv = "InventoryFrequency", _II = "InventoryId", _IIOV = "InventoryIncludedObjectVersions", _IL = "IsLatest", _IM = "IfMatch", _IMS = "IfModifiedSince", _INM = "IfNoneMatch", _IOF = "InventoryOptionalField", _IOV = "IncludedObjectVersions", _IP = "IsPublic", _IPA = "IgnorePublicAcls", _IRIP = "IsRestoreInProgress", _IS = "InputSerialization", _ISBD = "InventoryS3BucketDestination", _ISn = "InventorySchedule", _IT = "IsTruncated", _ITAO = "IntelligentTieringAndOperator", _ITAT = "IntelligentTieringAccessTier", _ITC = "IntelligentTieringConfiguration", _ITCL = "IntelligentTieringConfigurationList", _ITD = "IntelligentTieringDays", _ITF = "IntelligentTieringFilter", _ITI = "IntelligentTieringId", _ITS = "IntelligentTieringStatus", _IUS = "IfUnmodifiedSince", _In = "Initiator", _Ini = "Initiated", _JSON = "JSON", _JSONI = "JSONInput", _JSONO = "JSONOutput", _JSONT = "JSONType", _K = "Key", _KC = "KeyCount", _KI = "KeyId", _KM = "KeyMarker", _KMSC = "KMSContext", _KMSKI = "KMSKeyId", _KMSMKID = "KMSMasterKeyID", _KPE = "KeyPrefixEquals", _L = "Location", _LC = "LocationConstraint", _LE = "LoggingEnabled", _LEi = "LifecycleExpiration", _LFA = "LambdaFunctionArn", _LFC = "LambdaFunctionConfigurations", _LFCa = "LambdaFunctionConfiguration", _LI = "LocationInfo", _LM = "LastModified", _LNAS = "LocationNameAsString", _LP = "LocationPrefix", _LR = "LifecycleRule", _LRAO = "LifecycleRuleAndOperator", _LRF = "LifecycleRuleFilter", _LT = "LocationType", _M = "Marker", _MAO = "MetricsAndOperator", _MAS = "MaxAgeSeconds", _MC = "MetricsConfiguration", _MCL = "MetricsConfigurationList", _MD = "MetadataDirective", _MDB = "MaxDirectoryBuckets", _MDf = "MfaDelete", _ME = "MetadataEntry", _MF = "MetricsFilter", _MFA = "MFA", _MFAD = "MFADelete", _MI = "MetricsId", _MK = "MaxKeys", _MKe = "MetadataKey", _MM = "MissingMeta", _MP = "MaxParts", _MS = "MetricsStatus", _MU = "MaxUploads", _MV = "MetadataValue", _Me = "Metrics", _Mes = "Message", _Mi = "Minutes", _Mo = "Mode", _N = "Name", _NC = "NotificationConfiguration", _NCF = "NotificationConfigurationFilter", _NCT = "NextContinuationToken", _ND = "NoncurrentDays", _NI = "NotificationId", _NKM = "NextKeyMarker", _NM = "NextMarker", _NNV = "NewerNoncurrentVersions", _NPNM = "NextPartNumberMarker", _NUIM = "NextUploadIdMarker", _NVE = "NoncurrentVersionExpiration", _NVIM = "NextVersionIdMarker", _NVT = "NoncurrentVersionTransitions", _NVTo = "NoncurrentVersionTransition", _O = "Owner", _OA = "ObjectAttributes", _OC = "OwnershipControls", _OCACL = "ObjectCannedACL", _OCR = "OwnershipControlsRule", _OF = "OptionalFields", _OI = "ObjectIdentifier", _OK = "ObjectKey", _OL = "OutputLocation", _OLC = "ObjectLockConfiguration", _OLE = "ObjectLockEnabled", _OLEFB = "ObjectLockEnabledForBucket", _OLLH = "ObjectLockLegalHold", _OLLHS = "ObjectLockLegalHoldStatus", _OLM = "ObjectLockMode", _OLR = "ObjectLockRetention", _OLRM = "ObjectLockRetentionMode", _OLRUD = "ObjectLockRetainUntilDate", _OLRb = "ObjectLockRule", _OO = "ObjectOwnership", _OOA = "OptionalObjectAttributes", _OOw = "OwnerOverride", _OP = "ObjectParts", _OS = "OutputSerialization", _OSGT = "ObjectSizeGreaterThan", _OSGTB = "ObjectSizeGreaterThanBytes", _OSLT = "ObjectSizeLessThan", _OSLTB = "ObjectSizeLessThanBytes", _OSV = "OutputSchemaVersion", _OSb = "ObjectSize", _OVI = "ObjectVersionId", _Ob = "Objects", _P = "Prefix", _PABC = "PublicAccessBlockConfiguration", _PC = "PartsCount", _PDS = "PartitionDateSource", _PI = "ParquetInput", _PN = "PartNumber", _PNM = "PartNumberMarker", _PP = "PartitionedPrefix", _Pa = "Payer", _Par = "Part", _Parq = "Parquet", _Part = "Parts", _Pe = "Permission", _Pr = "Protocol", _Pri = "Priority", _Q = "Quiet", _QA = "QueueArn", _QC = "QueueConfiguration", _QCu = "QueueConfigurations", _QCuo = "QuoteCharacter", _QEC = "QuoteEscapeCharacter", _QF = "QuoteFields", _Qu = "Queue", _R = "Range", _RART = "RedirectAllRequestsTo", _RC = "RequestCharged", _RCC = "ResponseCacheControl", _RCD = "ResponseContentDisposition", _RCE = "ResponseContentEncoding", _RCL = "ResponseContentLanguage", _RCT = "ResponseContentType", _RCe = "ReplicationConfiguration", _RD = "RecordDelimiter", _RE = "ResponseExpires", _RED = "RestoreExpiryDate", _RKKID = "ReplicaKmsKeyID", _RKPW = "ReplaceKeyPrefixWith", _RKW = "ReplaceKeyWith", _RM = "ReplicaModifications", _RMS = "ReplicaModificationsStatus", _ROP = "RestoreOutputPath", _RP = "RequestPayer", _RPB = "RestrictPublicBuckets", _RPC = "RequestPaymentConfiguration", _RPe = "RequestProgress", _RR = "RequestRoute", _RRAO = "ReplicationRuleAndOperator", _RRF = "ReplicationRuleFilter", _RRS = "ReplicationRuleStatus", _RRT = "RestoreRequestType", _RRe = "ReplicationRule", _RRes = "RestoreRequest", _RRo = "RoutingRules", _RRou = "RoutingRule", _RS = "ReplicationStatus", _RSe = "RestoreStatus", _RT = "RequestToken", _RTS = "ReplicationTimeStatus", _RTV = "ReplicationTimeValue", _RTe = "ReplicationTime", _RUD = "RetainUntilDate", _Re = "Restore", _Red = "Redirect", _Ro = "Role", _Ru = "Rule", _Rul = "Rules", _S = "Status", _SA = "StartAfter", _SAK = "SecretAccessKey", _SBD = "S3BucketDestination", _SC = "StorageClass", _SCA = "StorageClassAnalysis", _SCADE = "StorageClassAnalysisDataExport", _SCASV = "StorageClassAnalysisSchemaVersion", _SCt = "StatusCode", _SDV = "SkipDestinationValidation", _SK = "SSE-KMS", _SKEO = "SseKmsEncryptedObjects", _SKEOS = "SseKmsEncryptedObjectsStatus", _SKF = "S3KeyFilter", _SKe = "S3Key", _SL = "S3Location", _SM = "SessionMode", _SOCR = "SelectObjectContentRequest", _SP = "SelectParameters", _SPi = "SimplePrefix", _SR = "ScanRange", _SS = "SSE-S3", _SSC = "SourceSelectionCriteria", _SSE = "ServerSideEncryption", _SSEA = "SSEAlgorithm", _SSEBD = "ServerSideEncryptionByDefault", _SSEC = "ServerSideEncryptionConfiguration", _SSECA = "SSECustomerAlgorithm", _SSECK = "SSECustomerKey", _SSECKMD = "SSECustomerKeyMD5", _SSEKMS = "SSEKMS", _SSEKMSEC = "SSEKMSEncryptionContext", _SSEKMSKI = "SSEKMSKeyId", _SSER = "ServerSideEncryptionRule", _SSES = "SSES3", _ST = "SessionToken", _S_ = "S3", _Sc = "Schedule", _Se = "Setting", _Si = "Size", _St = "Start", _Su = "Suffix", _T = "Tagging", _TA = "TopicArn", _TB = "TargetBucket", _TC = "TagCount", _TCo = "TopicConfiguration", _TCop = "TopicConfigurations", _TD = "TaggingDirective", _TG = "TargetGrants", _TGa = "TargetGrant", _TOKF = "TargetObjectKeyFormat", _TP = "TargetPrefix", _TPC = "TotalPartsCount", _TS = "TagSet", _TSC = "TransitionStorageClass", _Ta = "Tag", _Tag = "Tags", _Ti = "Tier", _Tie = "Tierings", _Tier = "Tiering", _Tim = "Time", _To = "Token", _Top = "Topic", _Tr = "Transitions", _Tra = "Transition", _Ty = "Type", _U = "Upload", _UI = "UploadId", _UIM = "UploadIdMarker", _UM = "UserMetadata", _URI = "URI", _Up = "Uploads", _V = "Version", _VC = "VersionCount", _VCe = "VersioningConfiguration", _VI = "VersionId", _VIM = "VersionIdMarker", _Va = "Value", _Ve = "Versions", _WC = "WebsiteConfiguration", _WRL = "WebsiteRedirectLocation", _Y = "Years", _a4 = "analytics", _ac = "accelerate", _acl = "acl", _ar = "accept-ranges", _at = "attributes", _c = "cors", _cc = "cache-control", _cd = "content-disposition", _ce = "content-encoding", _cl = "content-language", _cl_ = "content-length", _cm = "content-md5", _cr = "content-range", _ct = "content-type", _ct_ = "continuation-token", _d = "delete", _de = "delimiter", _e = "expires", _en = "encryption", _et = "encoding-type", _eta = "etag", _ex = "expiresstring", _fo = "fetch-owner", _i = "id", _im = "if-match", _ims = "if-modified-since", _in = "inventory", _inm = "if-none-match", _it = "intelligent-tiering", _ius = "if-unmodified-since", _km = "key-marker", _l = "lifecycle", _lh = "legal-hold", _lm = "last-modified", _lo = "location", _log = "logging", _lt = "list-type", _m = "metrics", _ma = "marker", _mdb = "max-directory-buckets", _me = "member", _mk = "max-keys", _mp = "max-parts", _mu = "max-uploads", _n = "notification", _oC = "ownershipControls", _ol = "object-lock", _p = "policy", _pAB = "publicAccessBlock", _pN = "partNumber", _pS = "policyStatus", _pnm = "part-number-marker", _pr = "prefix", _r = "replication", _rP = "requestPayment", _ra = "range", _rcc = "response-cache-control", _rcd = "response-content-disposition", _rce = "response-content-encoding", _rcl = "response-content-language", _rct = "response-content-type", _re = "response-expires", _res = "restore", _ret = "retention", _s = "session", _sa = "start-after", _se = "select", _st = "select-type", _t = "tagging", _to = "torrent", _u = "uploads", _uI = "uploadId", _uim = "upload-id-marker", _v = "versioning", _vI = "versionId", _ve = '', _ver = "versions", _vim = "version-id-marker", _w = "website", _x = "xsi:type", _xaa = "x-amz-acl", _xaad = "x-amz-abort-date", _xaapa = "x-amz-access-point-alias", _xaari = "x-amz-abort-rule-id", _xaas = "x-amz-archive-status", _xabgr = "x-amz-bypass-governance-retention", _xabln = "x-amz-bucket-location-name", _xablt = "x-amz-bucket-location-type", _xabole = "x-amz-bucket-object-lock-enabled", _xabolt = "x-amz-bucket-object-lock-token", _xabr = "x-amz-bucket-region", _xaca = "x-amz-checksum-algorithm", _xacc = "x-amz-checksum-crc32", _xacc_ = "x-amz-checksum-crc32c", _xacm = "x-amz-checksum-mode", _xacrsba = "x-amz-confirm-remove-self-bucket-access", _xacs = "x-amz-checksum-sha1", _xacs_ = "x-amz-checksum-sha256", _xacs__ = "x-amz-copy-source", _xacsim = "x-amz-copy-source-if-match", _xacsims = "x-amz-copy-source-if-modified-since", _xacsinm = "x-amz-copy-source-if-none-match", _xacsius = "x-amz-copy-source-if-unmodified-since", _xacsm = "x-amz-create-session-mode", _xacsr = "x-amz-copy-source-range", _xacssseca = "x-amz-copy-source-server-side-encryption-customer-algorithm", _xacssseck = "x-amz-copy-source-server-side-encryption-customer-key", _xacssseckm = "x-amz-copy-source-server-side-encryption-customer-key-md5", _xacsvi = "x-amz-copy-source-version-id", _xadm = "x-amz-delete-marker", _xae = "x-amz-expiration", _xaebo = "x-amz-expected-bucket-owner", _xafec = "x-amz-fwd-error-code", _xafem = "x-amz-fwd-error-message", _xafhar = "x-amz-fwd-header-accept-ranges", _xafhcc = "x-amz-fwd-header-cache-control", _xafhcd = "x-amz-fwd-header-content-disposition", _xafhce = "x-amz-fwd-header-content-encoding", _xafhcl = "x-amz-fwd-header-content-language", _xafhcr = "x-amz-fwd-header-content-range", _xafhct = "x-amz-fwd-header-content-type", _xafhe = "x-amz-fwd-header-etag", _xafhe_ = "x-amz-fwd-header-expires", _xafhlm = "x-amz-fwd-header-last-modified", _xafhxacc = "x-amz-fwd-header-x-amz-checksum-crc32", _xafhxacc_ = "x-amz-fwd-header-x-amz-checksum-crc32c", _xafhxacs = "x-amz-fwd-header-x-amz-checksum-sha1", _xafhxacs_ = "x-amz-fwd-header-x-amz-checksum-sha256", _xafhxadm = "x-amz-fwd-header-x-amz-delete-marker", _xafhxae = "x-amz-fwd-header-x-amz-expiration", _xafhxamm = "x-amz-fwd-header-x-amz-missing-meta", _xafhxampc = "x-amz-fwd-header-x-amz-mp-parts-count", _xafhxaollh = "x-amz-fwd-header-x-amz-object-lock-legal-hold", _xafhxaolm = "x-amz-fwd-header-x-amz-object-lock-mode", _xafhxaolrud = "x-amz-fwd-header-x-amz-object-lock-retain-until-date", _xafhxar = "x-amz-fwd-header-x-amz-restore", _xafhxarc = "x-amz-fwd-header-x-amz-request-charged", _xafhxars = "x-amz-fwd-header-x-amz-replication-status", _xafhxasc = "x-amz-fwd-header-x-amz-storage-class", _xafhxasse = "x-amz-fwd-header-x-amz-server-side-encryption", _xafhxasseakki = "x-amz-fwd-header-x-amz-server-side-encryption-aws-kms-key-id", _xafhxassebke = "x-amz-fwd-header-x-amz-server-side-encryption-bucket-key-enabled", _xafhxasseca = "x-amz-fwd-header-x-amz-server-side-encryption-customer-algorithm", _xafhxasseckm = "x-amz-fwd-header-x-amz-server-side-encryption-customer-key-md5", _xafhxatc = "x-amz-fwd-header-x-amz-tagging-count", _xafhxavi = "x-amz-fwd-header-x-amz-version-id", _xafs = "x-amz-fwd-status", _xagfc = "x-amz-grant-full-control", _xagr = "x-amz-grant-read", _xagra = "x-amz-grant-read-acp", _xagw = "x-amz-grant-write", _xagwa = "x-amz-grant-write-acp", _xam = "x-amz-mfa", _xamd = "x-amz-metadata-directive", _xamm = "x-amz-missing-meta", _xamp = "x-amz-max-parts", _xampc = "x-amz-mp-parts-count", _xaoa = "x-amz-object-attributes", _xaollh = "x-amz-object-lock-legal-hold", _xaolm = "x-amz-object-lock-mode", _xaolrud = "x-amz-object-lock-retain-until-date", _xaoo = "x-amz-object-ownership", _xaooa = "x-amz-optional-object-attributes", _xapnm = "x-amz-part-number-marker", _xar = "x-amz-restore", _xarc = "x-amz-request-charged", _xarop = "x-amz-restore-output-path", _xarp = "x-amz-request-payer", _xarr = "x-amz-request-route", _xars = "x-amz-replication-status", _xart = "x-amz-request-token", _xasc = "x-amz-storage-class", _xasca = "x-amz-sdk-checksum-algorithm", _xasdv = "x-amz-skip-destination-validation", _xasebo = "x-amz-source-expected-bucket-owner", _xasse = "x-amz-server-side-encryption", _xasseakki = "x-amz-server-side-encryption-aws-kms-key-id", _xassebke = "x-amz-server-side-encryption-bucket-key-enabled", _xassec = "x-amz-server-side-encryption-context", _xasseca = "x-amz-server-side-encryption-customer-algorithm", _xasseck = "x-amz-server-side-encryption-customer-key", _xasseckm = "x-amz-server-side-encryption-customer-key-md5", _xat = "x-amz-tagging", _xatc = "x-amz-tagging-count", _xatd = "x-amz-tagging-directive", _xavi = "x-amz-version-id", _xawrl = "x-amz-website-redirect-location", _xi = "x-id", CreateSessionCommand = class extends(Command.classBuilder().ep({
...commonParams,
DisableS3ExpressSessionAuth: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "CreateSession", {}).n("S3Client", "CreateSessionCommand").f(void 0, CreateSessionOutputFilterSensitiveLog).ser(se_CreateSessionCommand).de(de_CreateSessionCommand).build()){}, package_default = {
name: "@aws-sdk/client-s3",
description: "AWS SDK for JavaScript S3 Client for Node.js, Browser and React Native",
version: "3.563.0",
scripts: {
build: "concurrently 'yarn:build:cjs' 'yarn:build:es' 'yarn:build:types'",
"build:cjs": "node ../../scripts/compilation/inline client-s3",
"build:es": "tsc -p tsconfig.es.json",
"build:include:deps": "lerna run --scope $npm_package_name --include-dependencies build",
"build:types": "tsc -p tsconfig.types.json",
"build:types:downlevel": "downlevel-dts dist-types dist-types/ts3.4",
clean: "rimraf ./dist-* && rimraf *.tsbuildinfo",
"extract:docs": "api-extractor run --local",
"generate:client": "node ../../scripts/generate-clients/single-service --solo s3",
test: "yarn test:unit",
"test:e2e": "yarn test:e2e:node && yarn test:e2e:browser",
"test:e2e:browser": "ts-mocha test/**/*.browser.ispec.ts && karma start karma.conf.js",
"test:e2e:node": "jest --c jest.config.e2e.js",
"test:unit": "ts-mocha test/unit/**/*.spec.ts"
},
main: "./dist-cjs/index.js",
types: "./dist-types/index.d.ts",
module: "./dist-es/index.js",
sideEffects: false,
dependencies: {
"@aws-crypto/sha1-browser": "3.0.0",
"@aws-crypto/sha256-browser": "3.0.0",
"@aws-crypto/sha256-js": "3.0.0",
"@aws-sdk/client-sts": "3.556.0",
"@aws-sdk/core": "3.556.0",
"@aws-sdk/credential-provider-node": "3.563.0",
"@aws-sdk/middleware-bucket-endpoint": "3.535.0",
"@aws-sdk/middleware-expect-continue": "3.535.0",
"@aws-sdk/middleware-flexible-checksums": "3.535.0",
"@aws-sdk/middleware-host-header": "3.535.0",
"@aws-sdk/middleware-location-constraint": "3.535.0",
"@aws-sdk/middleware-logger": "3.535.0",
"@aws-sdk/middleware-recursion-detection": "3.535.0",
"@aws-sdk/middleware-sdk-s3": "3.556.0",
"@aws-sdk/middleware-signing": "3.556.0",
"@aws-sdk/middleware-ssec": "3.537.0",
"@aws-sdk/middleware-user-agent": "3.540.0",
"@aws-sdk/region-config-resolver": "3.535.0",
"@aws-sdk/signature-v4-multi-region": "3.556.0",
"@aws-sdk/types": "3.535.0",
"@aws-sdk/util-endpoints": "3.540.0",
"@aws-sdk/util-user-agent-browser": "3.535.0",
"@aws-sdk/util-user-agent-node": "3.535.0",
"@aws-sdk/xml-builder": "3.535.0",
"@smithy/config-resolver": "^2.2.0",
"@smithy/core": "^1.4.2",
"@smithy/eventstream-serde-browser": "^2.2.0",
"@smithy/eventstream-serde-config-resolver": "^2.2.0",
"@smithy/eventstream-serde-node": "^2.2.0",
"@smithy/fetch-http-handler": "^2.5.0",
"@smithy/hash-blob-browser": "^2.2.0",
"@smithy/hash-node": "^2.2.0",
"@smithy/hash-stream-node": "^2.2.0",
"@smithy/invalid-dependency": "^2.2.0",
"@smithy/md5-js": "^2.2.0",
"@smithy/middleware-content-length": "^2.2.0",
"@smithy/middleware-endpoint": "^2.5.1",
"@smithy/middleware-retry": "^2.3.1",
"@smithy/middleware-serde": "^2.3.0",
"@smithy/middleware-stack": "^2.2.0",
"@smithy/node-config-provider": "^2.3.0",
"@smithy/node-http-handler": "^2.5.0",
"@smithy/protocol-http": "^3.3.0",
"@smithy/smithy-client": "^2.5.1",
"@smithy/types": "^2.12.0",
"@smithy/url-parser": "^2.2.0",
"@smithy/util-base64": "^2.3.0",
"@smithy/util-body-length-browser": "^2.2.0",
"@smithy/util-body-length-node": "^2.3.0",
"@smithy/util-defaults-mode-browser": "^2.2.1",
"@smithy/util-defaults-mode-node": "^2.3.1",
"@smithy/util-endpoints": "^1.2.0",
"@smithy/util-retry": "^2.2.0",
"@smithy/util-stream": "^2.2.0",
"@smithy/util-utf8": "^2.3.0",
"@smithy/util-waiter": "^2.2.0",
tslib: "^2.6.2"
},
devDependencies: {
"@aws-sdk/signature-v4-crt": "3.556.0",
"@smithy/service-client-documentation-generator": "^2.2.0",
"@tsconfig/node14": "1.0.3",
"@types/chai": "^4.2.11",
"@types/mocha": "^8.0.4",
"@types/node": "^14.14.31",
concurrently: "7.0.0",
"downlevel-dts": "0.10.1",
rimraf: "3.0.2",
typescript: "~4.9.5"
},
engines: {
node: ">=14.0.0"
},
typesVersions: {
"<4.0": {
"dist-types/*": [ "dist-types/ts3.4/*" ]
}
},
files: [ "dist-*/**" ],
author: {
name: "AWS SDK for JavaScript Team",
url: "https://aws.amazon.com/javascript/"
},
license: "Apache-2.0",
browser: {
"./dist-es/runtimeConfig": "./dist-es/runtimeConfig.browser"
},
"react-native": {
"./dist-es/runtimeConfig": "./dist-es/runtimeConfig.native"
},
homepage: "https://github.com/aws/aws-sdk-js-v3/tree/main/clients/client-s3",
repository: {
type: "git",
url: "https://github.com/aws/aws-sdk-js-v3.git",
directory: "clients/client-s3"
}
}, import_sha1_browser = __toESM(require_build4()), import_sha256_browser = __toESM(require_build6()), import_bowser = __toESM(require_es5()), defaultUserAgent = ({serviceId: _, clientVersion: ee}) => async () => {
var ne, ie, re, se, oe, le, ue;
const de = "undefined" != typeof window && (null == (ne = null == window ? void 0 : window.navigator) ? void 0 : ne.userAgent) ? import_bowser.default.parse(window.navigator.userAgent) : void 0, fe = [ [ "aws-sdk-js", ee ], [ "ua", "2.0" ], [ `os/${(null == (ie = null == de ? void 0 : de.os) ? void 0 : ie.name) || "other"}`, null == (re = null == de ? void 0 : de.os) ? void 0 : re.version ], [ "lang/js" ], [ "md/browser", `${null != (oe = null == (se = null == de ? void 0 : de.browser) ? void 0 : se.name) ? oe : "unknown"}_${null != (ue = null == (le = null == de ? void 0 : de.browser) ? void 0 : le.version) ? ue : "unknown"}` ] ];
if (_) fe.push([ `api/${_}`, ee ]);
return fe;
}, import_crc322 = __toESM(require_build7()), Int642 = class _Int64 {
constructor(_) {
this.bytes = _;
if (8 !== _.byteLength) throw new Error("Int64 buffers must be exactly 8 bytes");
}
static fromNumber(_) {
if (_ > 0x8000000000000000 || _ < -0x8000000000000000) throw new Error(`${_} is too large (or, if negative, too small) to represent as an Int64`);
const ee = new Uint8Array(8);
for (let ne = 7, ie = Math.abs(Math.round(_)); ne > -1 && ie > 0; ne--, ie /= 256) ee[ne] = ie;
if (_ < 0) negate2(ee);
return new _Int64(ee);
}
valueOf() {
const _ = this.bytes.slice(0), ee = 128 & _[0];
if (ee) negate2(_);
return parseInt(toHex(_), 16) * (ee ? -1 : 1);
}
toString() {
return String(this.valueOf());
}
};
function negate2(_) {
for (let ee = 0; ee < 8; ee++) _[ee] ^= 255;
for (let ee = 7; ee > -1; ee--) {
_[ee]++;
if (0 !== _[ee]) break;
}
}
var HEADER_VALUE_TYPE2, HeaderMarshaller = class {
constructor(_, ee) {
this.toUtf8 = _;
this.fromUtf8 = ee;
}
format(_) {
const ee = [];
for (const ne of Object.keys(_)) {
const ie = this.fromUtf8(ne);
ee.push(Uint8Array.from([ ie.byteLength ]), ie, this.formatHeaderValue(_[ne]));
}
const ne = new Uint8Array(ee.reduce(((_, ee) => _ + ee.byteLength), 0));
let ie = 0;
for (const _ of ee) {
ne.set(_, ie);
ie += _.byteLength;
}
return ne;
}
formatHeaderValue(_) {
switch (_.type) {
case "boolean":
return Uint8Array.from([ _.value ? 0 : 1 ]);
case "byte":
return Uint8Array.from([ 2, _.value ]);
case "short":
const ee = new DataView(new ArrayBuffer(3));
ee.setUint8(0, 3);
ee.setInt16(1, _.value, false);
return new Uint8Array(ee.buffer);
case "integer":
const ne = new DataView(new ArrayBuffer(5));
ne.setUint8(0, 4);
ne.setInt32(1, _.value, false);
return new Uint8Array(ne.buffer);
case "long":
const ie = new Uint8Array(9);
ie[0] = 5;
ie.set(_.value.bytes, 1);
return ie;
case "binary":
const re = new DataView(new ArrayBuffer(3 + _.value.byteLength));
re.setUint8(0, 6);
re.setUint16(1, _.value.byteLength, false);
const se = new Uint8Array(re.buffer);
se.set(_.value, 3);
return se;
case "string":
const oe = this.fromUtf8(_.value), le = new DataView(new ArrayBuffer(3 + oe.byteLength));
le.setUint8(0, 7);
le.setUint16(1, oe.byteLength, false);
const ue = new Uint8Array(le.buffer);
ue.set(oe, 3);
return ue;
case "timestamp":
const de = new Uint8Array(9);
de[0] = 8;
de.set(Int642.fromNumber(_.value.valueOf()).bytes, 1);
return de;
case "uuid":
if (!UUID_PATTERN2.test(_.value)) throw new Error(`Invalid UUID received: ${_.value}`);
const fe = new Uint8Array(17);
fe[0] = 9;
fe.set(fromHex(_.value.replace(/\-/g, "")), 1);
return fe;
}
}
parse(_) {
const ee = {};
let ne = 0;
for (;ne < _.byteLength; ) {
const ie = _.getUint8(ne++), re = this.toUtf8(new Uint8Array(_.buffer, _.byteOffset + ne, ie));
ne += ie;
switch (_.getUint8(ne++)) {
case 0:
ee[re] = {
type: BOOLEAN_TAG,
value: true
};
break;
case 1:
ee[re] = {
type: BOOLEAN_TAG,
value: false
};
break;
case 2:
ee[re] = {
type: BYTE_TAG,
value: _.getInt8(ne++)
};
break;
case 3:
ee[re] = {
type: SHORT_TAG,
value: _.getInt16(ne, false)
};
ne += 2;
break;
case 4:
ee[re] = {
type: INT_TAG,
value: _.getInt32(ne, false)
};
ne += 4;
break;
case 5:
ee[re] = {
type: LONG_TAG,
value: new Int642(new Uint8Array(_.buffer, _.byteOffset + ne, 8))
};
ne += 8;
break;
case 6:
const ie = _.getUint16(ne, false);
ne += 2;
ee[re] = {
type: BINARY_TAG,
value: new Uint8Array(_.buffer, _.byteOffset + ne, ie)
};
ne += ie;
break;
case 7:
const se = _.getUint16(ne, false);
ne += 2;
ee[re] = {
type: STRING_TAG,
value: this.toUtf8(new Uint8Array(_.buffer, _.byteOffset + ne, se))
};
ne += se;
break;
case 8:
ee[re] = {
type: TIMESTAMP_TAG,
value: new Date(new Int642(new Uint8Array(_.buffer, _.byteOffset + ne, 8)).valueOf())
};
ne += 8;
break;
case 9:
const oe = new Uint8Array(_.buffer, _.byteOffset + ne, 16);
ne += 16;
ee[re] = {
type: UUID_TAG,
value: `${toHex(oe.subarray(0, 4))}-${toHex(oe.subarray(4, 6))}-${toHex(oe.subarray(6, 8))}-${toHex(oe.subarray(8, 10))}-${toHex(oe.subarray(10))}`
};
break;
default:
throw new Error("Unrecognized header type tag");
}
}
return ee;
}
};
(function(_) {
_[_["boolTrue"] = 0] = "boolTrue";
_[_["boolFalse"] = 1] = "boolFalse";
_[_["byte"] = 2] = "byte";
_[_["short"] = 3] = "short";
_[_["integer"] = 4] = "integer";
_[_["long"] = 5] = "long";
_[_["byteArray"] = 6] = "byteArray";
_[_["string"] = 7] = "string";
_[_["timestamp"] = 8] = "timestamp";
_[_["uuid"] = 9] = "uuid";
})(HEADER_VALUE_TYPE2 || (HEADER_VALUE_TYPE2 = {}));
var BOOLEAN_TAG = "boolean", BYTE_TAG = "byte", SHORT_TAG = "short", INT_TAG = "integer", LONG_TAG = "long", BINARY_TAG = "binary", STRING_TAG = "string", TIMESTAMP_TAG = "timestamp", UUID_TAG = "uuid", UUID_PATTERN2 = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/, import_crc32 = __toESM(require_build7()), PRELUDE_MEMBER_LENGTH = 4, PRELUDE_LENGTH = 2 * PRELUDE_MEMBER_LENGTH, CHECKSUM_LENGTH = 4, MINIMUM_MESSAGE_LENGTH = PRELUDE_LENGTH + 2 * CHECKSUM_LENGTH;
function splitMessage({byteLength: _, byteOffset: ee, buffer: ne}) {
if (_ < MINIMUM_MESSAGE_LENGTH) throw new Error("Provided message too short to accommodate event stream message overhead");
const ie = new DataView(ne, ee, _), re = ie.getUint32(0, false);
if (_ !== re) throw new Error("Reported message length does not match received message length");
const se = ie.getUint32(PRELUDE_MEMBER_LENGTH, false), oe = ie.getUint32(PRELUDE_LENGTH, false), le = ie.getUint32(_ - CHECKSUM_LENGTH, false), ue = (new import_crc32.Crc32).update(new Uint8Array(ne, ee, PRELUDE_LENGTH));
if (oe !== ue.digest()) throw new Error(`The prelude checksum specified in the message (${oe}) does not match the calculated CRC32 checksum (${ue.digest()})`);
ue.update(new Uint8Array(ne, ee + PRELUDE_LENGTH, _ - (PRELUDE_LENGTH + CHECKSUM_LENGTH)));
if (le !== ue.digest()) throw new Error(`The message checksum (${ue.digest()}) did not match the expected value of ${le}`);
return {
headers: new DataView(ne, ee + PRELUDE_LENGTH + CHECKSUM_LENGTH, se),
body: new Uint8Array(ne, ee + PRELUDE_LENGTH + CHECKSUM_LENGTH + se, re - se - (PRELUDE_LENGTH + CHECKSUM_LENGTH + CHECKSUM_LENGTH))
};
}
var EventStreamCodec = class {
constructor(_, ee) {
this.headerMarshaller = new HeaderMarshaller(_, ee);
this.messageBuffer = [];
this.isEndOfStream = false;
}
feed(_) {
this.messageBuffer.push(this.decode(_));
}
endOfStream() {
this.isEndOfStream = true;
}
getMessage() {
const _ = this.messageBuffer.pop(), ee = this.isEndOfStream;
return {
getMessage: () => _,
isEndOfStream: () => ee
};
}
getAvailableMessages() {
const _ = this.messageBuffer;
this.messageBuffer = [];
const ee = this.isEndOfStream;
return {
getMessages: () => _,
isEndOfStream: () => ee
};
}
encode({headers: _, body: ee}) {
const ne = this.headerMarshaller.format(_), ie = ne.byteLength + ee.byteLength + 16, re = new Uint8Array(ie), se = new DataView(re.buffer, re.byteOffset, re.byteLength), oe = new import_crc322.Crc32;
se.setUint32(0, ie, false);
se.setUint32(4, ne.byteLength, false);
se.setUint32(8, oe.update(re.subarray(0, 8)).digest(), false);
re.set(ne, 12);
re.set(ee, ne.byteLength + 12);
se.setUint32(ie - 4, oe.update(re.subarray(8, ie - 4)).digest(), false);
return re;
}
decode(_) {
const {headers: ee, body: ne} = splitMessage(_);
return {
headers: this.headerMarshaller.parse(ee),
body: ne
};
}
formatHeaders(_) {
return this.headerMarshaller.format(_);
}
}, MessageDecoderStream = class {
constructor(_) {
this.options = _;
}
[Symbol.asyncIterator]() {
return this.asyncIterator();
}
async* asyncIterator() {
for await (const _ of this.options.inputStream) {
const ee = this.options.decoder.decode(_);
yield ee;
}
}
}, MessageEncoderStream = class {
constructor(_) {
this.options = _;
}
[Symbol.asyncIterator]() {
return this.asyncIterator();
}
async* asyncIterator() {
for await (const _ of this.options.messageStream) {
const ee = this.options.encoder.encode(_);
yield ee;
}
if (this.options.includeEndFrame) yield new Uint8Array(0);
}
}, SmithyMessageDecoderStream = class {
constructor(_) {
this.options = _;
}
[Symbol.asyncIterator]() {
return this.asyncIterator();
}
async* asyncIterator() {
for await (const _ of this.options.messageStream) {
const ee = await this.options.deserializer(_);
if (void 0 !== ee) yield ee;
}
}
}, SmithyMessageEncoderStream = class {
constructor(_) {
this.options = _;
}
[Symbol.asyncIterator]() {
return this.asyncIterator();
}
async* asyncIterator() {
for await (const _ of this.options.inputStream) {
const ee = this.options.serializer(_);
yield ee;
}
}
};
function getChunkedStream(_) {
let ee = 0, ne = 0, ie = null, re = null;
const allocateMessage = _ => {
if ("number" != typeof _) throw new Error("Attempted to allocate an event message where size was not a number: " + _);
ee = _;
ne = 4;
ie = new Uint8Array(_);
new DataView(ie.buffer).setUint32(0, _, false);
};
return {
[Symbol.asyncIterator]: async function*() {
const se = _[Symbol.asyncIterator]();
for (;;) {
const {value: _, done: oe} = await se.next();
if (oe) {
if (!ee) return; else if (ee === ne) yield ie; else throw new Error("Truncated event message received.");
return;
}
const le = _.length;
let ue = 0;
for (;ue < le; ) {
if (!ie) {
const ee = le - ue;
if (!re) re = new Uint8Array(4);
const ie = Math.min(4 - ne, ee);
re.set(_.slice(ue, ue + ie), ne);
ne += ie;
ue += ie;
if (ne < 4) break;
allocateMessage(new DataView(re.buffer).getUint32(0, false));
re = null;
}
const se = Math.min(ee - ne, le - ue);
ie.set(_.slice(ue, ue + se), ne);
ne += se;
ue += se;
if (ee && ee === ne) {
yield ie;
ie = null;
ee = 0;
ne = 0;
}
}
}
}
};
}
function getMessageUnmarshaller(_, ee) {
return async function(ne) {
const {value: ie} = ne.headers[":message-type"];
if ("error" === ie) {
const _ = new Error(ne.headers[":error-message"].value || "UnknownError");
_.name = ne.headers[":error-code"].value;
throw _;
} else if ("exception" === ie) {
const ie = ne.headers[":exception-type"].value, re = {
[ie]: ne
}, se = await _(re);
if (se.$unknown) {
const _ = new Error(ee(ne.body));
_.name = ie;
throw _;
}
throw se[ie];
} else if ("event" === ie) {
const ee = {
[ne.headers[":event-type"].value]: ne
}, ie = await _(ee);
if (ie.$unknown) return;
return ie;
} else throw Error(`Unrecognizable event type: ${ne.headers[":event-type"].value}`);
};
}
var EventStreamMarshaller = class {
constructor({utf8Encoder: _, utf8Decoder: ee}) {
this.eventStreamCodec = new EventStreamCodec(_, ee);
this.utfEncoder = _;
}
deserialize(_, ee) {
const ne = getChunkedStream(_);
return new SmithyMessageDecoderStream({
messageStream: new MessageDecoderStream({
inputStream: ne,
decoder: this.eventStreamCodec
}),
deserializer: getMessageUnmarshaller(ee, this.utfEncoder)
});
}
serialize(_, ee) {
return new MessageEncoderStream({
messageStream: new SmithyMessageEncoderStream({
inputStream: _,
serializer: ee
}),
encoder: this.eventStreamCodec,
includeEndFrame: true
});
}
}, readableStreamtoIterable = _ => ({
[Symbol.asyncIterator]: async function*() {
const ee = _.getReader();
try {
for (;;) {
const {done: _, value: ne} = await ee.read();
if (_) return;
yield ne;
}
} finally {
ee.releaseLock();
}
}
}), iterableToReadableStream = _ => {
const ee = _[Symbol.asyncIterator]();
return new ReadableStream({
async pull(_) {
const {done: ne, value: ie} = await ee.next();
if (ne) return _.close();
_.enqueue(ie);
}
});
}, EventStreamMarshaller2 = class {
constructor({utf8Encoder: _, utf8Decoder: ee}) {
this.universalMarshaller = new EventStreamMarshaller({
utf8Decoder: ee,
utf8Encoder: _
});
}
deserialize(_, ee) {
const ne = isReadableStream(_) ? readableStreamtoIterable(_) : _;
return this.universalMarshaller.deserialize(ne, ee);
}
serialize(_, ee) {
const ne = this.universalMarshaller.serialize(_, ee);
return "function" == typeof ReadableStream ? iterableToReadableStream(ne) : ne;
}
}, isReadableStream = _ => "function" == typeof ReadableStream && _ instanceof ReadableStream, eventStreamSerdeProvider = _ => new EventStreamMarshaller2(_);
function blobReader(_, ee, ne = 1048576) {
return new Promise(((ie, re) => {
const se = new FileReader;
se.addEventListener("error", re);
se.addEventListener("abort", re);
const oe = _.size;
let le = 0;
function read() {
if (!(le >= oe)) se.readAsArrayBuffer(_.slice(le, Math.min(oe, le + ne))); else ie();
}
se.addEventListener("load", (_ => {
const ne = _.target.result;
ee(new Uint8Array(ne));
le += ne.byteLength;
read();
}));
read();
}));
}
var blobHasher = async function blobHasher2(_, ee) {
const ne = new _;
await blobReader(ee, (_ => {
ne.update(_);
}));
return ne.digest();
}, invalidProvider = _ => () => Promise.reject(_), BLOCK_SIZE = 64, DIGEST_LENGTH = 16, INIT = [ 1732584193, 4023233417, 2562383102, 271733878 ], Md52 = class {
constructor() {
this.reset();
}
update(_) {
if (isEmptyData(_)) return; else if (this.finished) throw new Error("Attempted to update an already finished hash.");
const ee = convertToBuffer(_);
let ne = 0, {byteLength: ie} = ee;
this.bytesHashed += ie;
for (;ie > 0; ) {
this.buffer.setUint8(this.bufferLength++, ee[ne++]);
ie--;
if (this.bufferLength === BLOCK_SIZE) {
this.hashBuffer();
this.bufferLength = 0;
}
}
}
async digest() {
if (!this.finished) {
const {buffer: _, bufferLength: ee, bytesHashed: ne} = this, ie = 8 * ne;
_.setUint8(this.bufferLength++, 128);
if (ee % BLOCK_SIZE >= BLOCK_SIZE - 8) {
for (let ee = this.bufferLength; ee < BLOCK_SIZE; ee++) _.setUint8(ee, 0);
this.hashBuffer();
this.bufferLength = 0;
}
for (let ee = this.bufferLength; ee < BLOCK_SIZE - 8; ee++) _.setUint8(ee, 0);
_.setUint32(BLOCK_SIZE - 8, ie >>> 0, true);
_.setUint32(BLOCK_SIZE - 4, Math.floor(ie / 4294967296), true);
this.hashBuffer();
this.finished = true;
}
const _ = new DataView(new ArrayBuffer(DIGEST_LENGTH));
for (let ee = 0; ee < 4; ee++) _.setUint32(4 * ee, this.state[ee], true);
return new Uint8Array(_.buffer, _.byteOffset, _.byteLength);
}
hashBuffer() {
const {buffer: _, state: ee} = this;
let ne = ee[0], ie = ee[1], re = ee[2], se = ee[3];
ne = ff(ne, ie, re, se, _.getUint32(0, true), 7, 3614090360);
se = ff(se, ne, ie, re, _.getUint32(4, true), 12, 3905402710);
re = ff(re, se, ne, ie, _.getUint32(8, true), 17, 606105819);
ie = ff(ie, re, se, ne, _.getUint32(12, true), 22, 3250441966);
ne = ff(ne, ie, re, se, _.getUint32(16, true), 7, 4118548399);
se = ff(se, ne, ie, re, _.getUint32(20, true), 12, 1200080426);
re = ff(re, se, ne, ie, _.getUint32(24, true), 17, 2821735955);
ie = ff(ie, re, se, ne, _.getUint32(28, true), 22, 4249261313);
ne = ff(ne, ie, re, se, _.getUint32(32, true), 7, 1770035416);
se = ff(se, ne, ie, re, _.getUint32(36, true), 12, 2336552879);
re = ff(re, se, ne, ie, _.getUint32(40, true), 17, 4294925233);
ie = ff(ie, re, se, ne, _.getUint32(44, true), 22, 2304563134);
ne = ff(ne, ie, re, se, _.getUint32(48, true), 7, 1804603682);
se = ff(se, ne, ie, re, _.getUint32(52, true), 12, 4254626195);
re = ff(re, se, ne, ie, _.getUint32(56, true), 17, 2792965006);
ie = ff(ie, re, se, ne, _.getUint32(60, true), 22, 1236535329);
ne = gg(ne, ie, re, se, _.getUint32(4, true), 5, 4129170786);
se = gg(se, ne, ie, re, _.getUint32(24, true), 9, 3225465664);
re = gg(re, se, ne, ie, _.getUint32(44, true), 14, 643717713);
ie = gg(ie, re, se, ne, _.getUint32(0, true), 20, 3921069994);
ne = gg(ne, ie, re, se, _.getUint32(20, true), 5, 3593408605);
se = gg(se, ne, ie, re, _.getUint32(40, true), 9, 38016083);
re = gg(re, se, ne, ie, _.getUint32(60, true), 14, 3634488961);
ie = gg(ie, re, se, ne, _.getUint32(16, true), 20, 3889429448);
ne = gg(ne, ie, re, se, _.getUint32(36, true), 5, 568446438);
se = gg(se, ne, ie, re, _.getUint32(56, true), 9, 3275163606);
re = gg(re, se, ne, ie, _.getUint32(12, true), 14, 4107603335);
ie = gg(ie, re, se, ne, _.getUint32(32, true), 20, 1163531501);
ne = gg(ne, ie, re, se, _.getUint32(52, true), 5, 2850285829);
se = gg(se, ne, ie, re, _.getUint32(8, true), 9, 4243563512);
re = gg(re, se, ne, ie, _.getUint32(28, true), 14, 1735328473);
ie = gg(ie, re, se, ne, _.getUint32(48, true), 20, 2368359562);
ne = hh(ne, ie, re, se, _.getUint32(20, true), 4, 4294588738);
se = hh(se, ne, ie, re, _.getUint32(32, true), 11, 2272392833);
re = hh(re, se, ne, ie, _.getUint32(44, true), 16, 1839030562);
ie = hh(ie, re, se, ne, _.getUint32(56, true), 23, 4259657740);
ne = hh(ne, ie, re, se, _.getUint32(4, true), 4, 2763975236);
se = hh(se, ne, ie, re, _.getUint32(16, true), 11, 1272893353);
re = hh(re, se, ne, ie, _.getUint32(28, true), 16, 4139469664);
ie = hh(ie, re, se, ne, _.getUint32(40, true), 23, 3200236656);
ne = hh(ne, ie, re, se, _.getUint32(52, true), 4, 681279174);
se = hh(se, ne, ie, re, _.getUint32(0, true), 11, 3936430074);
re = hh(re, se, ne, ie, _.getUint32(12, true), 16, 3572445317);
ie = hh(ie, re, se, ne, _.getUint32(24, true), 23, 76029189);
ne = hh(ne, ie, re, se, _.getUint32(36, true), 4, 3654602809);
se = hh(se, ne, ie, re, _.getUint32(48, true), 11, 3873151461);
re = hh(re, se, ne, ie, _.getUint32(60, true), 16, 530742520);
ie = hh(ie, re, se, ne, _.getUint32(8, true), 23, 3299628645);
ne = ii(ne, ie, re, se, _.getUint32(0, true), 6, 4096336452);
se = ii(se, ne, ie, re, _.getUint32(28, true), 10, 1126891415);
re = ii(re, se, ne, ie, _.getUint32(56, true), 15, 2878612391);
ie = ii(ie, re, se, ne, _.getUint32(20, true), 21, 4237533241);
ne = ii(ne, ie, re, se, _.getUint32(48, true), 6, 1700485571);
se = ii(se, ne, ie, re, _.getUint32(12, true), 10, 2399980690);
re = ii(re, se, ne, ie, _.getUint32(40, true), 15, 4293915773);
ie = ii(ie, re, se, ne, _.getUint32(4, true), 21, 2240044497);
ne = ii(ne, ie, re, se, _.getUint32(32, true), 6, 1873313359);
se = ii(se, ne, ie, re, _.getUint32(60, true), 10, 4264355552);
re = ii(re, se, ne, ie, _.getUint32(24, true), 15, 2734768916);
ie = ii(ie, re, se, ne, _.getUint32(52, true), 21, 1309151649);
ne = ii(ne, ie, re, se, _.getUint32(16, true), 6, 4149444226);
se = ii(se, ne, ie, re, _.getUint32(44, true), 10, 3174756917);
re = ii(re, se, ne, ie, _.getUint32(8, true), 15, 718787259);
ie = ii(ie, re, se, ne, _.getUint32(36, true), 21, 3951481745);
ee[0] = ne + ee[0] & 4294967295;
ee[1] = ie + ee[1] & 4294967295;
ee[2] = re + ee[2] & 4294967295;
ee[3] = se + ee[3] & 4294967295;
}
reset() {
this.state = Uint32Array.from(INIT);
this.buffer = new DataView(new ArrayBuffer(BLOCK_SIZE));
this.bufferLength = 0;
this.bytesHashed = 0;
this.finished = false;
}
};
function cmn(_, ee, ne, ie, re, se) {
return ((ee = (ee + _ & 4294967295) + (ie + se & 4294967295) & 4294967295) << re | ee >>> 32 - re) + ne & 4294967295;
}
function ff(_, ee, ne, ie, re, se, oe) {
return cmn(ee & ne | ~ee & ie, _, ee, re, se, oe);
}
function gg(_, ee, ne, ie, re, se, oe) {
return cmn(ee & ie | ne & ~ie, _, ee, re, se, oe);
}
function hh(_, ee, ne, ie, re, se, oe) {
return cmn(ee ^ ne ^ ie, _, ee, re, se, oe);
}
function ii(_, ee, ne, ie, re, se, oe) {
return cmn(ne ^ (ee | ~ie), _, ee, re, se, oe);
}
function isEmptyData(_) {
if ("string" == typeof _) return 0 === _.length; else return 0 === _.byteLength;
}
function convertToBuffer(_) {
if ("string" == typeof _) return fromUtf8(_);
if (ArrayBuffer.isView(_)) return new Uint8Array(_.buffer, _.byteOffset, _.byteLength / Uint8Array.BYTES_PER_ELEMENT); else return new Uint8Array(_);
}
var TEXT_ENCODER = "function" == typeof TextEncoder ? new TextEncoder : null, calculateBodyLength = _ => {
if ("string" == typeof _) {
if (TEXT_ENCODER) return TEXT_ENCODER.encode(_).byteLength;
let ee = _.length;
for (let ne = ee - 1; ne >= 0; ne--) {
const ie = _.charCodeAt(ne);
if (ie > 127 && ie <= 2047) ee++; else if (ie > 2047 && ie <= 65535) ee += 2;
if (ie >= 56320 && ie <= 57343) ne--;
}
return ee;
} else if ("number" == typeof _.byteLength) return _.byteLength; else if ("number" == typeof _.size) return _.size;
throw new Error(`Body Length computation failed for ${_}`);
}, signatureV4CrtContainer = {
CrtSignerV4: null
}, SignatureV4MultiRegion = class {
constructor(_) {
this.sigv4Signer = new SignatureV4S3Express(_);
this.signerOptions = _;
}
async sign(_, ee = {}) {
if ("*" === ee.signingRegion) {
if ("node" !== this.signerOptions.runtime) throw new Error("This request requires signing with SigV4Asymmetric algorithm. It's only available in Node.js");
return this.getSigv4aSigner().sign(_, ee);
}
return this.sigv4Signer.sign(_, ee);
}
async signWithCredentials(_, ee, ne = {}) {
if ("*" === ne.signingRegion) {
if ("node" !== this.signerOptions.runtime) throw new Error("This request requires signing with SigV4Asymmetric algorithm. It's only available in Node.js");
return this.getSigv4aSigner().signWithCredentials(_, ee, ne);
}
return this.sigv4Signer.signWithCredentials(_, ee, ne);
}
async presign(_, ee = {}) {
if ("*" === ee.signingRegion) {
if ("node" !== this.signerOptions.runtime) throw new Error("This request requires signing with SigV4Asymmetric algorithm. It's only available in Node.js");
return this.getSigv4aSigner().presign(_, ee);
}
return this.sigv4Signer.presign(_, ee);
}
async presignWithCredentials(_, ee, ne = {}) {
if ("*" === ne.signingRegion) throw new Error("Method presignWithCredentials is not supported for [signingRegion=*].");
return this.sigv4Signer.presignWithCredentials(_, ee, ne);
}
getSigv4aSigner() {
if (!this.sigv4aSigner) {
let _ = null;
try {
_ = signatureV4CrtContainer.CrtSignerV4;
if ("function" != typeof _) throw new Error;
} catch (_) {
_.message = `${_.message}\nPlease check whether you have installed the "@aws-sdk/signature-v4-crt" package explicitly. \nYou must also register the package by calling [require("@aws-sdk/signature-v4-crt");] or an ESM equivalent such as [import "@aws-sdk/signature-v4-crt";]. \nFor more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt`;
throw _;
}
this.sigv4aSigner = new _({
...this.signerOptions,
signingAlgorithm: 1
});
}
return this.sigv4aSigner;
}
}, ce = "required", cf = "type", cg = "conditions", ch3 = "fn", ci = "argv", cj = "ref", ck = "assign", cl = "url", cm = "properties", cn = "backend", co = "authSchemes", cp = "disableDoubleEncoding", cq = "signingName", cr = "signingRegion", cs = "headers", ct = "signingRegionSet", a2 = false, b = true, c = "isSet", d3 = "booleanEquals", e3 = "error", f3 = "aws.partition", g = "stringEquals", h2 = "getAttr", i = "name", j = "substring", k = "bucketSuffix", l = "parseURL", m = "{url#scheme}://{url#authority}/{uri_encoded_bucket}{url#path}", n2 = "endpoint", o = "tree", p = "aws.isVirtualHostableS3Bucket", q = "{url#scheme}://{Bucket}.{url#authority}{url#path}", r = "not", s = "{url#scheme}://{url#authority}{url#path}", t3 = "hardwareType", u = "regionPrefix", v = "bucketAliasSuffix", w = "outpostId", x = "isValidHostLabel", y = "sigv4a", z = "s3-outposts", A = "s3", B = "{url#scheme}://{url#authority}{url#normalizedPath}{Bucket}", C = "https://{Bucket}.s3-accelerate.{partitionResult#dnsSuffix}", D = "https://{Bucket}.s3.{partitionResult#dnsSuffix}", E = "aws.parseArn", F = "bucketArn", G = "arnType", H = "", I = "s3-object-lambda", J = "accesspoint", K = "accessPointName", L = "{url#scheme}://{accessPointName}-{bucketArn#accountId}.{url#authority}{url#path}", M = "mrapPartition", N = "outpostType", O = "arnPrefix", P = "{url#scheme}://{url#authority}{url#normalizedPath}{uri_encoded_bucket}", Q = "https://s3.{partitionResult#dnsSuffix}/{uri_encoded_bucket}", R = "https://s3.{partitionResult#dnsSuffix}", S = {
[ce]: false,
[cf]: "String"
}, T = {
[ce]: true,
default: false,
[cf]: "Boolean"
}, U = {
[ce]: false,
[cf]: "Boolean"
}, V = {
[ch3]: d3,
[ci]: [ {
[cj]: "Accelerate"
}, true ]
}, W = {
[ch3]: d3,
[ci]: [ {
[cj]: "UseFIPS"
}, true ]
}, X = {
[ch3]: d3,
[ci]: [ {
[cj]: "UseDualStack"
}, true ]
}, Y = {
[ch3]: c,
[ci]: [ {
[cj]: "Endpoint"
} ]
}, Z = {
[ch3]: f3,
[ci]: [ {
[cj]: "Region"
} ],
[ck]: "partitionResult"
}, aa = {
[ch3]: g,
[ci]: [ {
[ch3]: h2,
[ci]: [ {
[cj]: "partitionResult"
}, i ]
}, "aws-cn" ]
}, ab = {
[ch3]: c,
[ci]: [ {
[cj]: "Bucket"
} ]
}, ac = {
[cj]: "Bucket"
}, ad = {
[ch3]: l,
[ci]: [ {
[cj]: "Endpoint"
} ],
[ck]: "url"
}, ae = {
[ch3]: d3,
[ci]: [ {
[ch3]: h2,
[ci]: [ {
[cj]: "url"
}, "isIp" ]
}, true ]
}, af = {
[cj]: "url"
}, ag = {
[ch3]: "uriEncode",
[ci]: [ ac ],
[ck]: "uri_encoded_bucket"
}, ah = {
[cn]: "S3Express",
[co]: [ {
[cp]: true,
[i]: "sigv4",
[cq]: "s3express",
[cr]: "{Region}"
} ]
}, ai = {}, aj = {
[ch3]: p,
[ci]: [ ac, false ]
}, ak = {
[e3]: "S3Express bucket name is not a valid virtual hostable name.",
[cf]: e3
}, al = {
[cn]: "S3Express",
[co]: [ {
[cp]: true,
[i]: "sigv4-s3express",
[cq]: "s3express",
[cr]: "{Region}"
} ]
}, am = {
[ch3]: c,
[ci]: [ {
[cj]: "UseS3ExpressControlEndpoint"
} ]
}, an = {
[ch3]: d3,
[ci]: [ {
[cj]: "UseS3ExpressControlEndpoint"
}, true ]
}, ao = {
[ch3]: r,
[ci]: [ Y ]
}, ap = {
[e3]: "Unrecognized S3Express bucket name format.",
[cf]: e3
}, aq = {
[ch3]: r,
[ci]: [ ab ]
}, ar = {
[cj]: t3
}, as = {
[cg]: [ ao ],
[e3]: "Expected a endpoint to be specified but no endpoint was found",
[cf]: e3
}, at = {
[co]: [ {
[cp]: true,
[i]: y,
[cq]: z,
[ct]: [ "*" ]
}, {
[cp]: true,
[i]: "sigv4",
[cq]: z,
[cr]: "{Region}"
} ]
}, au = {
[ch3]: d3,
[ci]: [ {
[cj]: "ForcePathStyle"
}, false ]
}, av = {
[cj]: "ForcePathStyle"
}, aw = {
[ch3]: d3,
[ci]: [ {
[cj]: "Accelerate"
}, false ]
}, ax = {
[ch3]: g,
[ci]: [ {
[cj]: "Region"
}, "aws-global" ]
}, ay = {
[co]: [ {
[cp]: true,
[i]: "sigv4",
[cq]: A,
[cr]: "us-east-1"
} ]
}, az = {
[ch3]: r,
[ci]: [ ax ]
}, aA = {
[ch3]: d3,
[ci]: [ {
[cj]: "UseGlobalEndpoint"
}, true ]
}, aB = {
[cl]: "https://{Bucket}.s3-fips.dualstack.{Region}.{partitionResult#dnsSuffix}",
[cm]: {
[co]: [ {
[cp]: true,
[i]: "sigv4",
[cq]: A,
[cr]: "{Region}"
} ]
},
[cs]: {}
}, aC = {
[co]: [ {
[cp]: true,
[i]: "sigv4",
[cq]: A,
[cr]: "{Region}"
} ]
}, aD = {
[ch3]: d3,
[ci]: [ {
[cj]: "UseGlobalEndpoint"
}, false ]
}, aE = {
[ch3]: d3,
[ci]: [ {
[cj]: "UseDualStack"
}, false ]
}, aF = {
[cl]: "https://{Bucket}.s3-fips.{Region}.{partitionResult#dnsSuffix}",
[cm]: aC,
[cs]: {}
}, aG = {
[ch3]: d3,
[ci]: [ {
[cj]: "UseFIPS"
}, false ]
}, aH = {
[cl]: "https://{Bucket}.s3-accelerate.dualstack.{partitionResult#dnsSuffix}",
[cm]: aC,
[cs]: {}
}, aI = {
[cl]: "https://{Bucket}.s3.dualstack.{Region}.{partitionResult#dnsSuffix}",
[cm]: aC,
[cs]: {}
}, aJ = {
[ch3]: d3,
[ci]: [ {
[ch3]: h2,
[ci]: [ af, "isIp" ]
}, false ]
}, aK = {
[cl]: B,
[cm]: aC,
[cs]: {}
}, aL = {
[cl]: q,
[cm]: aC,
[cs]: {}
}, aM = {
[n2]: aL,
[cf]: n2
}, aN = {
[cl]: C,
[cm]: aC,
[cs]: {}
}, aO = {
[cl]: "https://{Bucket}.s3.{Region}.{partitionResult#dnsSuffix}",
[cm]: aC,
[cs]: {}
}, aP = {
[e3]: "Invalid region: region was not a valid DNS name.",
[cf]: e3
}, aQ = {
[cj]: F
}, aR = {
[cj]: G
}, aS = {
[ch3]: h2,
[ci]: [ aQ, "service" ]
}, aT = {
[cj]: K
}, aU = {
[cg]: [ X ],
[e3]: "S3 Object Lambda does not support Dual-stack",
[cf]: e3
}, aV = {
[cg]: [ V ],
[e3]: "S3 Object Lambda does not support S3 Accelerate",
[cf]: e3
}, aW = {
[cg]: [ {
[ch3]: c,
[ci]: [ {
[cj]: "DisableAccessPoints"
} ]
}, {
[ch3]: d3,
[ci]: [ {
[cj]: "DisableAccessPoints"
}, true ]
} ],
[e3]: "Access points are not supported for this operation",
[cf]: e3
}, aX = {
[cg]: [ {
[ch3]: c,
[ci]: [ {
[cj]: "UseArnRegion"
} ]
}, {
[ch3]: d3,
[ci]: [ {
[cj]: "UseArnRegion"
}, false ]
}, {
[ch3]: r,
[ci]: [ {
[ch3]: g,
[ci]: [ {
[ch3]: h2,
[ci]: [ aQ, "region" ]
}, "{Region}" ]
} ]
} ],
[e3]: "Invalid configuration: region from ARN `{bucketArn#region}` does not match client region `{Region}` and UseArnRegion is `false`",
[cf]: e3
}, aY = {
[ch3]: h2,
[ci]: [ {
[cj]: "bucketPartition"
}, i ]
}, aZ = {
[ch3]: h2,
[ci]: [ aQ, "accountId" ]
}, ba = {
[co]: [ {
[cp]: true,
[i]: "sigv4",
[cq]: I,
[cr]: "{bucketArn#region}"
} ]
}, bb = {
[e3]: "Invalid ARN: The access point name may only contain a-z, A-Z, 0-9 and `-`. Found: `{accessPointName}`",
[cf]: e3
}, bc = {
[e3]: "Invalid ARN: The account id may only contain a-z, A-Z, 0-9 and `-`. Found: `{bucketArn#accountId}`",
[cf]: e3
}, bd = {
[e3]: "Invalid region in ARN: `{bucketArn#region}` (invalid DNS name)",
[cf]: e3
}, be = {
[e3]: "Client was configured for partition `{partitionResult#name}` but ARN (`{Bucket}`) has `{bucketPartition#name}`",
[cf]: e3
}, bf = {
[e3]: "Invalid ARN: The ARN may only contain a single resource component after `accesspoint`.",
[cf]: e3
}, bg = {
[e3]: "Invalid ARN: Expected a resource of the format `accesspoint:` but no name was provided",
[cf]: e3
}, bh = {
[co]: [ {
[cp]: true,
[i]: "sigv4",
[cq]: A,
[cr]: "{bucketArn#region}"
} ]
}, bi = {
[co]: [ {
[cp]: true,
[i]: y,
[cq]: z,
[ct]: [ "*" ]
}, {
[cp]: true,
[i]: "sigv4",
[cq]: z,
[cr]: "{bucketArn#region}"
} ]
}, bj = {
[ch3]: E,
[ci]: [ ac ]
}, bk = {
[cl]: "https://s3-fips.dualstack.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",
[cm]: aC,
[cs]: {}
}, bl = {
[cl]: "https://s3-fips.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",
[cm]: aC,
[cs]: {}
}, bm = {
[cl]: "https://s3.dualstack.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",
[cm]: aC,
[cs]: {}
}, bn = {
[cl]: P,
[cm]: aC,
[cs]: {}
}, bo = {
[cl]: "https://s3.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",
[cm]: aC,
[cs]: {}
}, bp = {
[cj]: "UseObjectLambdaEndpoint"
}, bq = {
[co]: [ {
[cp]: true,
[i]: "sigv4",
[cq]: I,
[cr]: "{Region}"
} ]
}, br = {
[cl]: "https://s3-fips.dualstack.{Region}.{partitionResult#dnsSuffix}",
[cm]: aC,
[cs]: {}
}, bs = {
[cl]: "https://s3-fips.{Region}.{partitionResult#dnsSuffix}",
[cm]: aC,
[cs]: {}
}, bt = {
[cl]: "https://s3.dualstack.{Region}.{partitionResult#dnsSuffix}",
[cm]: aC,
[cs]: {}
}, bu = {
[cl]: s,
[cm]: aC,
[cs]: {}
}, bv = {
[cl]: "https://s3.{Region}.{partitionResult#dnsSuffix}",
[cm]: aC,
[cs]: {}
}, bw = [ {
[cj]: "Region"
} ], bx = [ {
[cj]: "Endpoint"
} ], by = [ ac ], bz = [ X ], bA = [ V ], bB = [ Y, ad ], bC = [ {
[ch3]: c,
[ci]: [ {
[cj]: "DisableS3ExpressSessionAuth"
} ]
}, {
[ch3]: d3,
[ci]: [ {
[cj]: "DisableS3ExpressSessionAuth"
}, true ]
} ], bD = [ ae ], bE = [ ag ], bF = [ aj ], bG = [ W ], bH = [ {
[ch3]: j,
[ci]: [ ac, 6, 14, true ],
[ck]: "s3expressAvailabilityZoneId"
}, {
[ch3]: j,
[ci]: [ ac, 14, 16, true ],
[ck]: "s3expressAvailabilityZoneDelim"
}, {
[ch3]: g,
[ci]: [ {
[cj]: "s3expressAvailabilityZoneDelim"
}, "--" ]
} ], bI = [ {
[cg]: [ W ],
[n2]: {
[cl]: "https://{Bucket}.s3express-fips-{s3expressAvailabilityZoneId}.{Region}.amazonaws.com",
[cm]: ah,
[cs]: {}
},
[cf]: n2
}, {
[n2]: {
[cl]: "https://{Bucket}.s3express-{s3expressAvailabilityZoneId}.{Region}.amazonaws.com",
[cm]: ah,
[cs]: {}
},
[cf]: n2
} ], bJ = [ {
[ch3]: j,
[ci]: [ ac, 6, 15, true ],
[ck]: "s3expressAvailabilityZoneId"
}, {
[ch3]: j,
[ci]: [ ac, 15, 17, true ],
[ck]: "s3expressAvailabilityZoneDelim"
}, {
[ch3]: g,
[ci]: [ {
[cj]: "s3expressAvailabilityZoneDelim"
}, "--" ]
} ], bK = [ {
[cg]: [ W ],
[n2]: {
[cl]: "https://{Bucket}.s3express-fips-{s3expressAvailabilityZoneId}.{Region}.amazonaws.com",
[cm]: al,
[cs]: {}
},
[cf]: n2
}, {
[n2]: {
[cl]: "https://{Bucket}.s3express-{s3expressAvailabilityZoneId}.{Region}.amazonaws.com",
[cm]: al,
[cs]: {}
},
[cf]: n2
} ], bL = [ ab ], bM = [ {
[ch3]: x,
[ci]: [ {
[cj]: w
}, false ]
} ], bN = [ {
[ch3]: g,
[ci]: [ {
[cj]: u
}, "beta" ]
} ], bO = [ "*" ], bP = [ Z ], bQ = [ {
[ch3]: x,
[ci]: [ {
[cj]: "Region"
}, false ]
} ], bR = [ {
[ch3]: g,
[ci]: [ {
[cj]: "Region"
}, "us-east-1" ]
} ], bS = [ {
[ch3]: g,
[ci]: [ aR, J ]
} ], bT = [ {
[ch3]: h2,
[ci]: [ aQ, "resourceId[1]" ],
[ck]: K
}, {
[ch3]: r,
[ci]: [ {
[ch3]: g,
[ci]: [ aT, H ]
} ]
} ], bU = [ aQ, "resourceId[1]" ], bV = [ {
[ch3]: r,
[ci]: [ {
[ch3]: g,
[ci]: [ {
[ch3]: h2,
[ci]: [ aQ, "region" ]
}, H ]
} ]
} ], bW = [ {
[ch3]: r,
[ci]: [ {
[ch3]: c,
[ci]: [ {
[ch3]: h2,
[ci]: [ aQ, "resourceId[2]" ]
} ]
} ]
} ], bX = [ aQ, "resourceId[2]" ], bY = [ {
[ch3]: f3,
[ci]: [ {
[ch3]: h2,
[ci]: [ aQ, "region" ]
} ],
[ck]: "bucketPartition"
} ], bZ = [ {
[ch3]: g,
[ci]: [ aY, {
[ch3]: h2,
[ci]: [ {
[cj]: "partitionResult"
}, i ]
} ]
} ], ca = [ {
[ch3]: x,
[ci]: [ {
[ch3]: h2,
[ci]: [ aQ, "region" ]
}, true ]
} ], cb = [ {
[ch3]: x,
[ci]: [ aZ, false ]
} ], cc = [ {
[ch3]: x,
[ci]: [ aT, false ]
} ], cd = [ {
[ch3]: x,
[ci]: [ {
[cj]: "Region"
}, true ]
} ], _data = {
version: "1.0",
parameters: {
Bucket: S,
Region: S,
UseFIPS: T,
UseDualStack: T,
Endpoint: S,
ForcePathStyle: T,
Accelerate: T,
UseGlobalEndpoint: T,
UseObjectLambdaEndpoint: U,
Key: S,
Prefix: S,
DisableAccessPoints: U,
DisableMultiRegionAccessPoints: T,
UseArnRegion: U,
UseS3ExpressControlEndpoint: U,
DisableS3ExpressSessionAuth: U
},
rules: [ {
[cg]: [ {
[ch3]: c,
[ci]: bw
} ],
rules: [ {
[cg]: [ V, W ],
error: "Accelerate cannot be used with FIPS",
[cf]: e3
}, {
[cg]: [ X, Y ],
error: "Cannot set dual-stack in combination with a custom endpoint.",
[cf]: e3
}, {
[cg]: [ Y, W ],
error: "A custom endpoint cannot be combined with FIPS",
[cf]: e3
}, {
[cg]: [ Y, V ],
error: "A custom endpoint cannot be combined with S3 Accelerate",
[cf]: e3
}, {
[cg]: [ W, Z, aa ],
error: "Partition does not support FIPS",
[cf]: e3
}, {
[cg]: [ ab, {
[ch3]: j,
[ci]: [ ac, 0, 6, b ],
[ck]: k
}, {
[ch3]: g,
[ci]: [ {
[cj]: k
}, "--x-s3" ]
} ],
rules: [ {
[cg]: bz,
error: "S3Express does not support Dual-stack.",
[cf]: e3
}, {
[cg]: bA,
error: "S3Express does not support S3 Accelerate.",
[cf]: e3
}, {
[cg]: bB,
rules: [ {
[cg]: bC,
rules: [ {
[cg]: bD,
rules: [ {
[cg]: bE,
rules: [ {
endpoint: {
[cl]: m,
[cm]: ah,
[cs]: ai
},
[cf]: n2
} ],
[cf]: o
} ],
[cf]: o
}, {
[cg]: bF,
rules: [ {
endpoint: {
[cl]: q,
[cm]: ah,
[cs]: ai
},
[cf]: n2
} ],
[cf]: o
}, ak ],
[cf]: o
}, {
[cg]: bD,
rules: [ {
[cg]: bE,
rules: [ {
endpoint: {
[cl]: m,
[cm]: al,
[cs]: ai
},
[cf]: n2
} ],
[cf]: o
} ],
[cf]: o
}, {
[cg]: bF,
rules: [ {
endpoint: {
[cl]: q,
[cm]: al,
[cs]: ai
},
[cf]: n2
} ],
[cf]: o
}, ak ],
[cf]: o
}, {
[cg]: [ am, an ],
rules: [ {
[cg]: [ ag, ao ],
rules: [ {
[cg]: bG,
endpoint: {
[cl]: "https://s3express-control-fips.{Region}.amazonaws.com/{uri_encoded_bucket}",
[cm]: ah,
[cs]: ai
},
[cf]: n2
}, {
endpoint: {
[cl]: "https://s3express-control.{Region}.amazonaws.com/{uri_encoded_bucket}",
[cm]: ah,
[cs]: ai
},
[cf]: n2
} ],
[cf]: o
} ],
[cf]: o
}, {
[cg]: bF,
rules: [ {
[cg]: bC,
rules: [ {
[cg]: bH,
rules: bI,
[cf]: o
}, {
[cg]: bJ,
rules: bI,
[cf]: o
}, ap ],
[cf]: o
}, {
[cg]: bH,
rules: bK,
[cf]: o
}, {
[cg]: bJ,
rules: bK,
[cf]: o
}, ap ],
[cf]: o
}, ak ],
[cf]: o
}, {
[cg]: [ aq, am, an ],
rules: [ {
[cg]: bB,
endpoint: {
[cl]: s,
[cm]: ah,
[cs]: ai
},
[cf]: n2
}, {
[cg]: bG,
endpoint: {
[cl]: "https://s3express-control-fips.{Region}.amazonaws.com",
[cm]: ah,
[cs]: ai
},
[cf]: n2
}, {
endpoint: {
[cl]: "https://s3express-control.{Region}.amazonaws.com",
[cm]: ah,
[cs]: ai
},
[cf]: n2
} ],
[cf]: o
}, {
[cg]: [ ab, {
[ch3]: j,
[ci]: [ ac, 49, 50, b ],
[ck]: t3
}, {
[ch3]: j,
[ci]: [ ac, 8, 12, b ],
[ck]: u
}, {
[ch3]: j,
[ci]: [ ac, 0, 7, b ],
[ck]: v
}, {
[ch3]: j,
[ci]: [ ac, 32, 49, b ],
[ck]: w
}, {
[ch3]: f3,
[ci]: bw,
[ck]: "regionPartition"
}, {
[ch3]: g,
[ci]: [ {
[cj]: v
}, "--op-s3" ]
} ],
rules: [ {
[cg]: bM,
rules: [ {
[cg]: [ {
[ch3]: g,
[ci]: [ ar, "e" ]
} ],
rules: [ {
[cg]: bN,
rules: [ as, {
[cg]: bB,
endpoint: {
[cl]: "https://{Bucket}.ec2.{url#authority}",
[cm]: at,
[cs]: ai
},
[cf]: n2
} ],
[cf]: o
}, {
endpoint: {
[cl]: "https://{Bucket}.ec2.s3-outposts.{Region}.{regionPartition#dnsSuffix}",
[cm]: at,
[cs]: ai
},
[cf]: n2
} ],
[cf]: o
}, {
[cg]: [ {
[ch3]: g,
[ci]: [ ar, "o" ]
} ],
rules: [ {
[cg]: bN,
rules: [ as, {
[cg]: bB,
endpoint: {
[cl]: "https://{Bucket}.op-{outpostId}.{url#authority}",
[cm]: at,
[cs]: ai
},
[cf]: n2
} ],
[cf]: o
}, {
endpoint: {
[cl]: "https://{Bucket}.op-{outpostId}.s3-outposts.{Region}.{regionPartition#dnsSuffix}",
[cm]: at,
[cs]: ai
},
[cf]: n2
} ],
[cf]: o
}, {
error: 'Unrecognized hardware type: "Expected hardware type o or e but got {hardwareType}"',
[cf]: e3
} ],
[cf]: o
}, {
error: "Invalid ARN: The outpost Id must only contain a-z, A-Z, 0-9 and `-`.",
[cf]: e3
} ],
[cf]: o
}, {
[cg]: bL,
rules: [ {
[cg]: [ Y, {
[ch3]: r,
[ci]: [ {
[ch3]: c,
[ci]: [ {
[ch3]: l,
[ci]: bx
} ]
} ]
} ],
error: "Custom endpoint `{Endpoint}` was not a valid URI",
[cf]: e3
}, {
[cg]: [ au, aj ],
rules: [ {
[cg]: bP,
rules: [ {
[cg]: bQ,
rules: [ {
[cg]: [ V, aa ],
error: "S3 Accelerate cannot be used in this region",
[cf]: e3
}, {
[cg]: [ X, W, aw, ao, ax ],
endpoint: {
[cl]: "https://{Bucket}.s3-fips.dualstack.us-east-1.{partitionResult#dnsSuffix}",
[cm]: ay,
[cs]: ai
},
[cf]: n2
}, {
[cg]: [ X, W, aw, ao, az, aA ],
rules: [ {
endpoint: aB,
[cf]: n2
} ],
[cf]: o
}, {
[cg]: [ X, W, aw, ao, az, aD ],
endpoint: aB,
[cf]: n2
}, {
[cg]: [ aE, W, aw, ao, ax ],
endpoint: {
[cl]: "https://{Bucket}.s3-fips.us-east-1.{partitionResult#dnsSuffix}",
[cm]: ay,
[cs]: ai
},
[cf]: n2
}, {
[cg]: [ aE, W, aw, ao, az, aA ],
rules: [ {
endpoint: aF,
[cf]: n2
} ],
[cf]: o
}, {
[cg]: [ aE, W, aw, ao, az, aD ],
endpoint: aF,
[cf]: n2
}, {
[cg]: [ X, aG, V, ao, ax ],
endpoint: {
[cl]: "https://{Bucket}.s3-accelerate.dualstack.us-east-1.{partitionResult#dnsSuffix}",
[cm]: ay,
[cs]: ai
},
[cf]: n2
}, {
[cg]: [ X, aG, V, ao, az, aA ],
rules: [ {
endpoint: aH,
[cf]: n2
} ],
[cf]: o
}, {
[cg]: [ X, aG, V, ao, az, aD ],
endpoint: aH,
[cf]: n2
}, {
[cg]: [ X, aG, aw, ao, ax ],
endpoint: {
[cl]: "https://{Bucket}.s3.dualstack.us-east-1.{partitionResult#dnsSuffix}",
[cm]: ay,
[cs]: ai
},
[cf]: n2
}, {
[cg]: [ X, aG, aw, ao, az, aA ],
rules: [ {
endpoint: aI,
[cf]: n2
} ],
[cf]: o
}, {
[cg]: [ X, aG, aw, ao, az, aD ],
endpoint: aI,
[cf]: n2
}, {
[cg]: [ aE, aG, aw, Y, ad, ae, ax ],
endpoint: {
[cl]: B,
[cm]: ay,
[cs]: ai
},
[cf]: n2
}, {
[cg]: [ aE, aG, aw, Y, ad, aJ, ax ],
endpoint: {
[cl]: q,
[cm]: ay,
[cs]: ai
},
[cf]: n2
}, {
[cg]: [ aE, aG, aw, Y, ad, ae, az, aA ],
rules: [ {
[cg]: bR,
endpoint: aK,
[cf]: n2
}, {
endpoint: aK,
[cf]: n2
} ],
[cf]: o
}, {
[cg]: [ aE, aG, aw, Y, ad, aJ, az, aA ],
rules: [ {
[cg]: bR,
endpoint: aL,
[cf]: n2
}, aM ],
[cf]: o
}, {
[cg]: [ aE, aG, aw, Y, ad, ae, az, aD ],
endpoint: aK,
[cf]: n2
}, {
[cg]: [ aE, aG, aw, Y, ad, aJ, az, aD ],
endpoint: aL,
[cf]: n2
}, {
[cg]: [ aE, aG, V, ao, ax ],
endpoint: {
[cl]: C,
[cm]: ay,
[cs]: ai
},
[cf]: n2
}, {
[cg]: [ aE, aG, V, ao, az, aA ],
rules: [ {
[cg]: bR,
endpoint: aN,
[cf]: n2
}, {
endpoint: aN,
[cf]: n2
} ],
[cf]: o
}, {
[cg]: [ aE, aG, V, ao, az, aD ],
endpoint: aN,
[cf]: n2
}, {
[cg]: [ aE, aG, aw, ao, ax ],
endpoint: {
[cl]: D,
[cm]: ay,
[cs]: ai
},
[cf]: n2
}, {
[cg]: [ aE, aG, aw, ao, az, aA ],
rules: [ {
[cg]: bR,
endpoint: {
[cl]: D,
[cm]: aC,
[cs]: ai
},
[cf]: n2
}, {
endpoint: aO,
[cf]: n2
} ],
[cf]: o
}, {
[cg]: [ aE, aG, aw, ao, az, aD ],
endpoint: aO,
[cf]: n2
} ],
[cf]: o
}, aP ],
[cf]: o
} ],
[cf]: o
}, {
[cg]: [ Y, ad, {
[ch3]: g,
[ci]: [ {
[ch3]: h2,
[ci]: [ af, "scheme" ]
}, "http" ]
}, {
[ch3]: p,
[ci]: [ ac, b ]
}, au, aG, aE, aw ],
rules: [ {
[cg]: bP,
rules: [ {
[cg]: bQ,
rules: [ aM ],
[cf]: o
}, aP ],
[cf]: o
} ],
[cf]: o
}, {
[cg]: [ au, {
[ch3]: E,
[ci]: by,
[ck]: F
} ],
rules: [ {
[cg]: [ {
[ch3]: h2,
[ci]: [ aQ, "resourceId[0]" ],
[ck]: G
}, {
[ch3]: r,
[ci]: [ {
[ch3]: g,
[ci]: [ aR, H ]
} ]
} ],
rules: [ {
[cg]: [ {
[ch3]: g,
[ci]: [ aS, I ]
} ],
rules: [ {
[cg]: bS,
rules: [ {
[cg]: bT,
rules: [ aU, aV, {
[cg]: bV,
rules: [ aW, {
[cg]: bW,
rules: [ aX, {
[cg]: bY,
rules: [ {
[cg]: bP,
rules: [ {
[cg]: bZ,
rules: [ {
[cg]: ca,
rules: [ {
[cg]: [ {
[ch3]: g,
[ci]: [ aZ, H ]
} ],
error: "Invalid ARN: Missing account id",
[cf]: e3
}, {
[cg]: cb,
rules: [ {
[cg]: cc,
rules: [ {
[cg]: bB,
endpoint: {
[cl]: L,
[cm]: ba,
[cs]: ai
},
[cf]: n2
}, {
[cg]: bG,
endpoint: {
[cl]: "https://{accessPointName}-{bucketArn#accountId}.s3-object-lambda-fips.{bucketArn#region}.{bucketPartition#dnsSuffix}",
[cm]: ba,
[cs]: ai
},
[cf]: n2
}, {
endpoint: {
[cl]: "https://{accessPointName}-{bucketArn#accountId}.s3-object-lambda.{bucketArn#region}.{bucketPartition#dnsSuffix}",
[cm]: ba,
[cs]: ai
},
[cf]: n2
} ],
[cf]: o
}, bb ],
[cf]: o
}, bc ],
[cf]: o
}, bd ],
[cf]: o
}, be ],
[cf]: o
} ],
[cf]: o
} ],
[cf]: o
}, bf ],
[cf]: o
}, {
error: "Invalid ARN: bucket ARN is missing a region",
[cf]: e3
} ],
[cf]: o
}, bg ],
[cf]: o
}, {
error: "Invalid ARN: Object Lambda ARNs only support `accesspoint` arn types, but found: `{arnType}`",
[cf]: e3
} ],
[cf]: o
}, {
[cg]: bS,
rules: [ {
[cg]: bT,
rules: [ {
[cg]: bV,
rules: [ {
[cg]: bS,
rules: [ {
[cg]: bV,
rules: [ aW, {
[cg]: bW,
rules: [ aX, {
[cg]: bY,
rules: [ {
[cg]: bP,
rules: [ {
[cg]: [ {
[ch3]: g,
[ci]: [ aY, "{partitionResult#name}" ]
} ],
rules: [ {
[cg]: ca,
rules: [ {
[cg]: [ {
[ch3]: g,
[ci]: [ aS, A ]
} ],
rules: [ {
[cg]: cb,
rules: [ {
[cg]: cc,
rules: [ {
[cg]: bA,
error: "Access Points do not support S3 Accelerate",
[cf]: e3
}, {
[cg]: [ W, X ],
endpoint: {
[cl]: "https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint-fips.dualstack.{bucketArn#region}.{bucketPartition#dnsSuffix}",
[cm]: bh,
[cs]: ai
},
[cf]: n2
}, {
[cg]: [ W, aE ],
endpoint: {
[cl]: "https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint-fips.{bucketArn#region}.{bucketPartition#dnsSuffix}",
[cm]: bh,
[cs]: ai
},
[cf]: n2
}, {
[cg]: [ aG, X ],
endpoint: {
[cl]: "https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint.dualstack.{bucketArn#region}.{bucketPartition#dnsSuffix}",
[cm]: bh,
[cs]: ai
},
[cf]: n2
}, {
[cg]: [ aG, aE, Y, ad ],
endpoint: {
[cl]: L,
[cm]: bh,
[cs]: ai
},
[cf]: n2
}, {
[cg]: [ aG, aE ],
endpoint: {
[cl]: "https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint.{bucketArn#region}.{bucketPartition#dnsSuffix}",
[cm]: bh,
[cs]: ai
},
[cf]: n2
} ],
[cf]: o
}, bb ],
[cf]: o
}, bc ],
[cf]: o
}, {
error: "Invalid ARN: The ARN was not for the S3 service, found: {bucketArn#service}",
[cf]: e3
} ],
[cf]: o
}, bd ],
[cf]: o
}, be ],
[cf]: o
} ],
[cf]: o
} ],
[cf]: o
}, bf ],
[cf]: o
} ],
[cf]: o
} ],
[cf]: o
}, {
[cg]: [ {
[ch3]: x,
[ci]: [ aT, b ]
} ],
rules: [ {
[cg]: bz,
error: "S3 MRAP does not support dual-stack",
[cf]: e3
}, {
[cg]: bG,
error: "S3 MRAP does not support FIPS",
[cf]: e3
}, {
[cg]: bA,
error: "S3 MRAP does not support S3 Accelerate",
[cf]: e3
}, {
[cg]: [ {
[ch3]: d3,
[ci]: [ {
[cj]: "DisableMultiRegionAccessPoints"
}, b ]
} ],
error: "Invalid configuration: Multi-Region Access Point ARNs are disabled.",
[cf]: e3
}, {
[cg]: [ {
[ch3]: f3,
[ci]: bw,
[ck]: M
} ],
rules: [ {
[cg]: [ {
[ch3]: g,
[ci]: [ {
[ch3]: h2,
[ci]: [ {
[cj]: M
}, i ]
}, {
[ch3]: h2,
[ci]: [ aQ, "partition" ]
} ]
} ],
rules: [ {
endpoint: {
[cl]: "https://{accessPointName}.accesspoint.s3-global.{mrapPartition#dnsSuffix}",
[cm]: {
[co]: [ {
[cp]: b,
name: y,
[cq]: A,
[ct]: bO
} ]
},
[cs]: ai
},
[cf]: n2
} ],
[cf]: o
}, {
error: "Client was configured for partition `{mrapPartition#name}` but bucket referred to partition `{bucketArn#partition}`",
[cf]: e3
} ],
[cf]: o
} ],
[cf]: o
}, {
error: "Invalid Access Point Name",
[cf]: e3
} ],
[cf]: o
}, bg ],
[cf]: o
}, {
[cg]: [ {
[ch3]: g,
[ci]: [ aS, z ]
} ],
rules: [ {
[cg]: bz,
error: "S3 Outposts does not support Dual-stack",
[cf]: e3
}, {
[cg]: bG,
error: "S3 Outposts does not support FIPS",
[cf]: e3
}, {
[cg]: bA,
error: "S3 Outposts does not support S3 Accelerate",
[cf]: e3
}, {
[cg]: [ {
[ch3]: c,
[ci]: [ {
[ch3]: h2,
[ci]: [ aQ, "resourceId[4]" ]
} ]
} ],
error: "Invalid Arn: Outpost Access Point ARN contains sub resources",
[cf]: e3
}, {
[cg]: [ {
[ch3]: h2,
[ci]: bU,
[ck]: w
} ],
rules: [ {
[cg]: bM,
rules: [ aX, {
[cg]: bY,
rules: [ {
[cg]: bP,
rules: [ {
[cg]: bZ,
rules: [ {
[cg]: ca,
rules: [ {
[cg]: cb,
rules: [ {
[cg]: [ {
[ch3]: h2,
[ci]: bX,
[ck]: N
} ],
rules: [ {
[cg]: [ {
[ch3]: h2,
[ci]: [ aQ, "resourceId[3]" ],
[ck]: K
} ],
rules: [ {
[cg]: [ {
[ch3]: g,
[ci]: [ {
[cj]: N
}, J ]
} ],
rules: [ {
[cg]: bB,
endpoint: {
[cl]: "https://{accessPointName}-{bucketArn#accountId}.{outpostId}.{url#authority}",
[cm]: bi,
[cs]: ai
},
[cf]: n2
}, {
endpoint: {
[cl]: "https://{accessPointName}-{bucketArn#accountId}.{outpostId}.s3-outposts.{bucketArn#region}.{bucketPartition#dnsSuffix}",
[cm]: bi,
[cs]: ai
},
[cf]: n2
} ],
[cf]: o
}, {
error: "Expected an outpost type `accesspoint`, found {outpostType}",
[cf]: e3
} ],
[cf]: o
}, {
error: "Invalid ARN: expected an access point name",
[cf]: e3
} ],
[cf]: o
}, {
error: "Invalid ARN: Expected a 4-component resource",
[cf]: e3
} ],
[cf]: o
}, bc ],
[cf]: o
}, bd ],
[cf]: o
}, be ],
[cf]: o
} ],
[cf]: o
} ],
[cf]: o
}, {
error: "Invalid ARN: The outpost Id may only contain a-z, A-Z, 0-9 and `-`. Found: `{outpostId}`",
[cf]: e3
} ],
[cf]: o
}, {
error: "Invalid ARN: The Outpost Id was not set",
[cf]: e3
} ],
[cf]: o
}, {
error: "Invalid ARN: Unrecognized format: {Bucket} (type: {arnType})",
[cf]: e3
} ],
[cf]: o
}, {
error: "Invalid ARN: No ARN type specified",
[cf]: e3
} ],
[cf]: o
}, {
[cg]: [ {
[ch3]: j,
[ci]: [ ac, 0, 4, a2 ],
[ck]: O
}, {
[ch3]: g,
[ci]: [ {
[cj]: O
}, "arn:" ]
}, {
[ch3]: r,
[ci]: [ {
[ch3]: c,
[ci]: [ bj ]
} ]
} ],
error: "Invalid ARN: `{Bucket}` was not a valid ARN",
[cf]: e3
}, {
[cg]: [ {
[ch3]: d3,
[ci]: [ av, b ]
}, bj ],
error: "Path-style addressing cannot be used with ARN buckets",
[cf]: e3
}, {
[cg]: bE,
rules: [ {
[cg]: bP,
rules: [ {
[cg]: [ aw ],
rules: [ {
[cg]: [ X, ao, W, ax ],
endpoint: {
[cl]: "https://s3-fips.dualstack.us-east-1.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",
[cm]: ay,
[cs]: ai
},
[cf]: n2
}, {
[cg]: [ X, ao, W, az, aA ],
rules: [ {
endpoint: bk,
[cf]: n2
} ],
[cf]: o
}, {
[cg]: [ X, ao, W, az, aD ],
endpoint: bk,
[cf]: n2
}, {
[cg]: [ aE, ao, W, ax ],
endpoint: {
[cl]: "https://s3-fips.us-east-1.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",
[cm]: ay,
[cs]: ai
},
[cf]: n2
}, {
[cg]: [ aE, ao, W, az, aA ],
rules: [ {
endpoint: bl,
[cf]: n2
} ],
[cf]: o
}, {
[cg]: [ aE, ao, W, az, aD ],
endpoint: bl,
[cf]: n2
}, {
[cg]: [ X, ao, aG, ax ],
endpoint: {
[cl]: "https://s3.dualstack.us-east-1.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",
[cm]: ay,
[cs]: ai
},
[cf]: n2
}, {
[cg]: [ X, ao, aG, az, aA ],
rules: [ {
endpoint: bm,
[cf]: n2
} ],
[cf]: o
}, {
[cg]: [ X, ao, aG, az, aD ],
endpoint: bm,
[cf]: n2
}, {
[cg]: [ aE, Y, ad, aG, ax ],
endpoint: {
[cl]: P,
[cm]: ay,
[cs]: ai
},
[cf]: n2
}, {
[cg]: [ aE, Y, ad, aG, az, aA ],
rules: [ {
[cg]: bR,
endpoint: bn,
[cf]: n2
}, {
endpoint: bn,
[cf]: n2
} ],
[cf]: o
}, {
[cg]: [ aE, Y, ad, aG, az, aD ],
endpoint: bn,
[cf]: n2
}, {
[cg]: [ aE, ao, aG, ax ],
endpoint: {
[cl]: Q,
[cm]: ay,
[cs]: ai
},
[cf]: n2
}, {
[cg]: [ aE, ao, aG, az, aA ],
rules: [ {
[cg]: bR,
endpoint: {
[cl]: Q,
[cm]: aC,
[cs]: ai
},
[cf]: n2
}, {
endpoint: bo,
[cf]: n2
} ],
[cf]: o
}, {
[cg]: [ aE, ao, aG, az, aD ],
endpoint: bo,
[cf]: n2
} ],
[cf]: o
}, {
error: "Path-style addressing cannot be used with S3 Accelerate",
[cf]: e3
} ],
[cf]: o
} ],
[cf]: o
} ],
[cf]: o
}, {
[cg]: [ {
[ch3]: c,
[ci]: [ bp ]
}, {
[ch3]: d3,
[ci]: [ bp, b ]
} ],
rules: [ {
[cg]: bP,
rules: [ {
[cg]: cd,
rules: [ aU, aV, {
[cg]: bB,
endpoint: {
[cl]: s,
[cm]: bq,
[cs]: ai
},
[cf]: n2
}, {
[cg]: bG,
endpoint: {
[cl]: "https://s3-object-lambda-fips.{Region}.{partitionResult#dnsSuffix}",
[cm]: bq,
[cs]: ai
},
[cf]: n2
}, {
endpoint: {
[cl]: "https://s3-object-lambda.{Region}.{partitionResult#dnsSuffix}",
[cm]: bq,
[cs]: ai
},
[cf]: n2
} ],
[cf]: o
}, aP ],
[cf]: o
} ],
[cf]: o
}, {
[cg]: [ aq ],
rules: [ {
[cg]: bP,
rules: [ {
[cg]: cd,
rules: [ {
[cg]: [ W, X, ao, ax ],
endpoint: {
[cl]: "https://s3-fips.dualstack.us-east-1.{partitionResult#dnsSuffix}",
[cm]: ay,
[cs]: ai
},
[cf]: n2
}, {
[cg]: [ W, X, ao, az, aA ],
rules: [ {
endpoint: br,
[cf]: n2
} ],
[cf]: o
}, {
[cg]: [ W, X, ao, az, aD ],
endpoint: br,
[cf]: n2
}, {
[cg]: [ W, aE, ao, ax ],
endpoint: {
[cl]: "https://s3-fips.us-east-1.{partitionResult#dnsSuffix}",
[cm]: ay,
[cs]: ai
},
[cf]: n2
}, {
[cg]: [ W, aE, ao, az, aA ],
rules: [ {
endpoint: bs,
[cf]: n2
} ],
[cf]: o
}, {
[cg]: [ W, aE, ao, az, aD ],
endpoint: bs,
[cf]: n2
}, {
[cg]: [ aG, X, ao, ax ],
endpoint: {
[cl]: "https://s3.dualstack.us-east-1.{partitionResult#dnsSuffix}",
[cm]: ay,
[cs]: ai
},
[cf]: n2
}, {
[cg]: [ aG, X, ao, az, aA ],
rules: [ {
endpoint: bt,
[cf]: n2
} ],
[cf]: o
}, {
[cg]: [ aG, X, ao, az, aD ],
endpoint: bt,
[cf]: n2
}, {
[cg]: [ aG, aE, Y, ad, ax ],
endpoint: {
[cl]: s,
[cm]: ay,
[cs]: ai
},
[cf]: n2
}, {
[cg]: [ aG, aE, Y, ad, az, aA ],
rules: [ {
[cg]: bR,
endpoint: bu,
[cf]: n2
}, {
endpoint: bu,
[cf]: n2
} ],
[cf]: o
}, {
[cg]: [ aG, aE, Y, ad, az, aD ],
endpoint: bu,
[cf]: n2
}, {
[cg]: [ aG, aE, ao, ax ],
endpoint: {
[cl]: R,
[cm]: ay,
[cs]: ai
},
[cf]: n2
}, {
[cg]: [ aG, aE, ao, az, aA ],
rules: [ {
[cg]: bR,
endpoint: {
[cl]: R,
[cm]: aC,
[cs]: ai
},
[cf]: n2
}, {
endpoint: bv,
[cf]: n2
} ],
[cf]: o
}, {
[cg]: [ aG, aE, ao, az, aD ],
endpoint: bv,
[cf]: n2
} ],
[cf]: o
}, aP ],
[cf]: o
} ],
[cf]: o
} ],
[cf]: o
}, {
error: "A region must be set when sending requests to S3.",
[cf]: e3
} ]
}, ruleSet = _data, defaultEndpointResolver = (_, ee = {}) => resolveEndpoint(ruleSet, {
endpointParams: _,
logger: ee.logger
});
customEndpointFunctions.aws = awsEndpointFunctions;
var getRuntimeConfig = _ => {
var ee, ne, ie, re, se, oe, le, ue, de, fe, he, pe, ge, me, ye;
return {
apiVersion: "2006-03-01",
base64Decoder: null != (ee = null == _ ? void 0 : _.base64Decoder) ? ee : fromBase64,
base64Encoder: null != (ne = null == _ ? void 0 : _.base64Encoder) ? ne : toBase64,
disableHostPrefix: null != (ie = null == _ ? void 0 : _.disableHostPrefix) ? ie : false,
endpointProvider: null != (re = null == _ ? void 0 : _.endpointProvider) ? re : defaultEndpointResolver,
extensions: null != (se = null == _ ? void 0 : _.extensions) ? se : [],
getAwsChunkedEncodingStream: null != (oe = null == _ ? void 0 : _.getAwsChunkedEncodingStream) ? oe : getAwsChunkedEncodingStream,
logger: null != (le = null == _ ? void 0 : _.logger) ? le : new NoOpLogger,
sdkStreamMixin: null != (ue = null == _ ? void 0 : _.sdkStreamMixin) ? ue : sdkStreamMixin,
serviceId: null != (de = null == _ ? void 0 : _.serviceId) ? de : "S3",
signerConstructor: null != (fe = null == _ ? void 0 : _.signerConstructor) ? fe : SignatureV4MultiRegion,
signingEscapePath: null != (he = null == _ ? void 0 : _.signingEscapePath) ? he : false,
urlParser: null != (pe = null == _ ? void 0 : _.urlParser) ? pe : parseUrl,
useArnRegion: null != (ge = null == _ ? void 0 : _.useArnRegion) ? ge : false,
utf8Decoder: null != (me = null == _ ? void 0 : _.utf8Decoder) ? me : fromUtf8,
utf8Encoder: null != (ye = null == _ ? void 0 : _.utf8Encoder) ? ye : toUtf8
};
}, import_bowser2 = __toESM(require_es5()), DEFAULTS_MODE_OPTIONS = [ "in-region", "cross-region", "mobile", "standard", "legacy" ], resolveDefaultsModeConfig = ({defaultsMode: _} = {}) => memoize((async () => {
const ee = "function" == typeof _ ? await _() : _;
switch (null == ee ? void 0 : ee.toLowerCase()) {
case "auto":
return Promise.resolve(isMobileBrowser() ? "mobile" : "standard");
case "mobile":
case "in-region":
case "cross-region":
case "standard":
case "legacy":
return Promise.resolve(null == ee ? void 0 : ee.toLocaleLowerCase());
case void 0:
return Promise.resolve("legacy");
default:
throw new Error(`Invalid parameter for "defaultsMode", expect ${DEFAULTS_MODE_OPTIONS.join(", ")}, got ${ee}`);
}
})), isMobileBrowser = () => {
var _, ee;
const ne = "undefined" != typeof window && (null == (_ = null == window ? void 0 : window.navigator) ? void 0 : _.userAgent) ? import_bowser2.default.parse(window.navigator.userAgent) : void 0, ie = null == (ee = null == ne ? void 0 : ne.platform) ? void 0 : ee.type;
return "tablet" === ie || "mobile" === ie;
}, getRuntimeConfig2 = _ => {
var ee, ne, ie, re, se, oe, le, ue, de, fe, he, pe, ge, me, ye;
const ve = resolveDefaultsModeConfig(_), defaultConfigProvider = () => ve().then(loadConfigsForDefaultMode), Se = getRuntimeConfig(_);
return {
...Se,
..._,
runtime: "browser",
defaultsMode: ve,
bodyLengthChecker: null != (ee = null == _ ? void 0 : _.bodyLengthChecker) ? ee : calculateBodyLength,
credentialDefaultProvider: null != (ne = null == _ ? void 0 : _.credentialDefaultProvider) ? ne : _ => () => Promise.reject(new Error("Credential is missing")),
defaultUserAgentProvider: null != (ie = null == _ ? void 0 : _.defaultUserAgentProvider) ? ie : defaultUserAgent({
serviceId: Se.serviceId,
clientVersion: package_default.version
}),
eventStreamSerdeProvider: null != (re = null == _ ? void 0 : _.eventStreamSerdeProvider) ? re : eventStreamSerdeProvider,
maxAttempts: null != (se = null == _ ? void 0 : _.maxAttempts) ? se : DEFAULT_MAX_ATTEMPTS,
md5: null != (oe = null == _ ? void 0 : _.md5) ? oe : Md52,
region: null != (le = null == _ ? void 0 : _.region) ? le : invalidProvider("Region is missing"),
requestHandler: FetchHttpHandler.create(null != (ue = null == _ ? void 0 : _.requestHandler) ? ue : defaultConfigProvider),
retryMode: null != (de = null == _ ? void 0 : _.retryMode) ? de : async () => (await defaultConfigProvider()).retryMode || DEFAULT_RETRY_MODE,
sha1: null != (fe = null == _ ? void 0 : _.sha1) ? fe : import_sha1_browser.Sha1,
sha256: null != (he = null == _ ? void 0 : _.sha256) ? he : import_sha256_browser.Sha256,
streamCollector: null != (pe = null == _ ? void 0 : _.streamCollector) ? pe : streamCollector,
streamHasher: null != (ge = null == _ ? void 0 : _.streamHasher) ? ge : blobHasher,
useDualstackEndpoint: null != (me = null == _ ? void 0 : _.useDualstackEndpoint) ? me : () => Promise.resolve(DEFAULT_USE_DUALSTACK_ENDPOINT),
useFipsEndpoint: null != (ye = null == _ ? void 0 : _.useFipsEndpoint) ? ye : () => Promise.resolve(DEFAULT_USE_FIPS_ENDPOINT)
};
}, getAwsRegionExtensionConfiguration = _ => {
let runtimeConfigRegion = async () => {
if (void 0 === _.region) throw new Error("Region is missing from runtimeConfig");
const ee = _.region;
if ("string" == typeof ee) return ee; else return ee();
};
return {
setRegion(_) {
runtimeConfigRegion = _;
},
region: () => runtimeConfigRegion
};
}, resolveAwsRegionExtensionConfiguration = _ => ({
region: _.region()
}), asPartial = _ => _, resolveRuntimeExtensions = (_, ee) => {
const ne = {
...asPartial(getAwsRegionExtensionConfiguration(_)),
...asPartial(getDefaultExtensionConfiguration(_)),
...asPartial(getHttpHandlerExtensionConfiguration(_))
};
ee.forEach((_ => _.configure(ne)));
return {
..._,
...resolveAwsRegionExtensionConfiguration(ne),
...resolveDefaultRuntimeConfig(ne),
...resolveHttpHandlerRuntimeConfig(ne)
};
}, S3Client = class extends Client {
constructor(...[_]) {
const ee = getRuntimeConfig2(_ || {}), ne = resolveClientEndpointParameters(ee), ie = resolveRegionConfig(ne), re = resolveEndpointConfig(ie), se = resolveHostHeaderConfig(resolveRetryConfig(re)), oe = resolveAwsAuthConfig(se), le = resolveUserAgentConfig(resolveS3Config(oe, {
session: [ () => this, CreateSessionCommand ]
})), ue = resolveEventStreamSerdeConfig(le), de = resolveRuntimeExtensions(ue, (null == _ ? void 0 : _.extensions) || []);
super(de);
this.config = de;
this.middlewareStack.use(getRetryPlugin(this.config));
this.middlewareStack.use(getContentLengthPlugin(this.config));
this.middlewareStack.use(getHostHeaderPlugin(this.config));
this.middlewareStack.use(getLoggerPlugin(this.config));
this.middlewareStack.use(getRecursionDetectionPlugin(this.config));
this.middlewareStack.use(getAwsAuthPlugin(this.config));
this.middlewareStack.use(getValidateBucketNamePlugin(this.config));
this.middlewareStack.use(getAddExpectContinuePlugin(this.config));
this.middlewareStack.use(getRegionRedirectMiddlewarePlugin(this.config));
this.middlewareStack.use(getS3ExpressPlugin(this.config));
this.middlewareStack.use(getUserAgentPlugin(this.config));
}
destroy() {
super.destroy();
}
}, AbortMultipartUploadCommand = class extends(Command.classBuilder().ep({
...commonParams,
Bucket: {
type: "contextParams",
name: "Bucket"
},
Key: {
type: "contextParams",
name: "Key"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "AbortMultipartUpload", {}).n("S3Client", "AbortMultipartUploadCommand").f(void 0, void 0).ser(se_AbortMultipartUploadCommand).de(de_AbortMultipartUploadCommand).build()){};
function ssecMiddleware(_) {
return ee => async ne => {
const ie = {
...ne.input
}, re = [ {
target: "SSECustomerKey",
hash: "SSECustomerKeyMD5"
}, {
target: "CopySourceSSECustomerKey",
hash: "CopySourceSSECustomerKeyMD5"
} ];
for (const ee of re) {
const ne = ie[ee.target];
if (ne) {
let re;
if ("string" == typeof ne) if (isValidBase64EncodedSSECustomerKey(ne, _)) re = _.base64Decoder(ne); else {
re = _.utf8Decoder(ne);
ie[ee.target] = _.base64Encoder(re);
} else {
re = ArrayBuffer.isView(ne) ? new Uint8Array(ne.buffer, ne.byteOffset, ne.byteLength) : new Uint8Array(ne);
ie[ee.target] = _.base64Encoder(re);
}
const se = new _.md5;
se.update(re);
ie[ee.hash] = _.base64Encoder(await se.digest());
}
}
return ee({
...ne,
input: ie
});
};
}
var ssecMiddlewareOptions = {
name: "ssecMiddleware",
step: "initialize",
tags: [ "SSE" ],
override: true
}, getSsecPlugin = _ => ({
applyToStack: ee => {
ee.add(ssecMiddleware(_), ssecMiddlewareOptions);
}
});
function isValidBase64EncodedSSECustomerKey(_, ee) {
if (!/^(?:[A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(_)) return false;
try {
return 32 === ee.base64Decoder(_).length;
} catch (_) {
return false;
}
}
var CompleteMultipartUploadCommand = class extends(Command.classBuilder().ep({
...commonParams,
Bucket: {
type: "contextParams",
name: "Bucket"
},
Key: {
type: "contextParams",
name: "Key"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()), getThrow200ExceptionsPlugin(ne), getSsecPlugin(ne) ];
})).s("AmazonS3", "CompleteMultipartUpload", {}).n("S3Client", "CompleteMultipartUploadCommand").f(CompleteMultipartUploadRequestFilterSensitiveLog, CompleteMultipartUploadOutputFilterSensitiveLog).ser(se_CompleteMultipartUploadCommand).de(de_CompleteMultipartUploadCommand).build()){}, CopyObjectCommand = class extends(Command.classBuilder().ep({
...commonParams,
DisableS3ExpressSessionAuth: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()), getThrow200ExceptionsPlugin(ne), getSsecPlugin(ne) ];
})).s("AmazonS3", "CopyObject", {}).n("S3Client", "CopyObjectCommand").f(CopyObjectRequestFilterSensitiveLog, CopyObjectOutputFilterSensitiveLog).ser(se_CopyObjectCommand).de(de_CopyObjectCommand).build()){};
function locationConstraintMiddleware(_) {
return ee => async ne => {
const {CreateBucketConfiguration: ie} = ne.input, re = await _.region();
if (!(null == ie ? void 0 : ie.LocationConstraint) && !(null == ie ? void 0 : ie.Location)) ne = {
...ne,
input: {
...ne.input,
CreateBucketConfiguration: "us-east-1" === re ? void 0 : {
LocationConstraint: re
}
}
};
return ee(ne);
};
}
var ChecksumAlgorithm, ChecksumLocation, locationConstraintMiddlewareOptions = {
step: "initialize",
tags: [ "LOCATION_CONSTRAINT", "CREATE_BUCKET_CONFIGURATION" ],
name: "locationConstraintMiddleware",
override: true
}, getLocationConstraintPlugin = _ => ({
applyToStack: ee => {
ee.add(locationConstraintMiddleware(_), locationConstraintMiddlewareOptions);
}
}), CreateBucketCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
DisableAccessPoints: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()), getLocationConstraintPlugin(ne) ];
})).s("AmazonS3", "CreateBucket", {}).n("S3Client", "CreateBucketCommand").f(void 0, void 0).ser(se_CreateBucketCommand).de(de_CreateBucketCommand).build()){}, CreateMultipartUploadCommand = class extends(Command.classBuilder().ep({
...commonParams,
Bucket: {
type: "contextParams",
name: "Bucket"
},
Key: {
type: "contextParams",
name: "Key"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()), getSsecPlugin(ne) ];
})).s("AmazonS3", "CreateMultipartUpload", {}).n("S3Client", "CreateMultipartUploadCommand").f(CreateMultipartUploadRequestFilterSensitiveLog, CreateMultipartUploadOutputFilterSensitiveLog).ser(se_CreateMultipartUploadCommand).de(de_CreateMultipartUploadCommand).build()){}, DeleteBucketAnalyticsConfigurationCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "DeleteBucketAnalyticsConfiguration", {}).n("S3Client", "DeleteBucketAnalyticsConfigurationCommand").f(void 0, void 0).ser(se_DeleteBucketAnalyticsConfigurationCommand).de(de_DeleteBucketAnalyticsConfigurationCommand).build()){}, DeleteBucketCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "DeleteBucket", {}).n("S3Client", "DeleteBucketCommand").f(void 0, void 0).ser(se_DeleteBucketCommand).de(de_DeleteBucketCommand).build()){}, DeleteBucketCorsCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "DeleteBucketCors", {}).n("S3Client", "DeleteBucketCorsCommand").f(void 0, void 0).ser(se_DeleteBucketCorsCommand).de(de_DeleteBucketCorsCommand).build()){}, DeleteBucketEncryptionCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "DeleteBucketEncryption", {}).n("S3Client", "DeleteBucketEncryptionCommand").f(void 0, void 0).ser(se_DeleteBucketEncryptionCommand).de(de_DeleteBucketEncryptionCommand).build()){}, DeleteBucketIntelligentTieringConfigurationCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "DeleteBucketIntelligentTieringConfiguration", {}).n("S3Client", "DeleteBucketIntelligentTieringConfigurationCommand").f(void 0, void 0).ser(se_DeleteBucketIntelligentTieringConfigurationCommand).de(de_DeleteBucketIntelligentTieringConfigurationCommand).build()){}, DeleteBucketInventoryConfigurationCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "DeleteBucketInventoryConfiguration", {}).n("S3Client", "DeleteBucketInventoryConfigurationCommand").f(void 0, void 0).ser(se_DeleteBucketInventoryConfigurationCommand).de(de_DeleteBucketInventoryConfigurationCommand).build()){}, DeleteBucketLifecycleCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "DeleteBucketLifecycle", {}).n("S3Client", "DeleteBucketLifecycleCommand").f(void 0, void 0).ser(se_DeleteBucketLifecycleCommand).de(de_DeleteBucketLifecycleCommand).build()){}, DeleteBucketMetricsConfigurationCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "DeleteBucketMetricsConfiguration", {}).n("S3Client", "DeleteBucketMetricsConfigurationCommand").f(void 0, void 0).ser(se_DeleteBucketMetricsConfigurationCommand).de(de_DeleteBucketMetricsConfigurationCommand).build()){}, DeleteBucketOwnershipControlsCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "DeleteBucketOwnershipControls", {}).n("S3Client", "DeleteBucketOwnershipControlsCommand").f(void 0, void 0).ser(se_DeleteBucketOwnershipControlsCommand).de(de_DeleteBucketOwnershipControlsCommand).build()){}, DeleteBucketPolicyCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "DeleteBucketPolicy", {}).n("S3Client", "DeleteBucketPolicyCommand").f(void 0, void 0).ser(se_DeleteBucketPolicyCommand).de(de_DeleteBucketPolicyCommand).build()){}, DeleteBucketReplicationCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "DeleteBucketReplication", {}).n("S3Client", "DeleteBucketReplicationCommand").f(void 0, void 0).ser(se_DeleteBucketReplicationCommand).de(de_DeleteBucketReplicationCommand).build()){}, DeleteBucketTaggingCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "DeleteBucketTagging", {}).n("S3Client", "DeleteBucketTaggingCommand").f(void 0, void 0).ser(se_DeleteBucketTaggingCommand).de(de_DeleteBucketTaggingCommand).build()){}, DeleteBucketWebsiteCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "DeleteBucketWebsite", {}).n("S3Client", "DeleteBucketWebsiteCommand").f(void 0, void 0).ser(se_DeleteBucketWebsiteCommand).de(de_DeleteBucketWebsiteCommand).build()){}, DeleteObjectCommand = class extends(Command.classBuilder().ep({
...commonParams,
Bucket: {
type: "contextParams",
name: "Bucket"
},
Key: {
type: "contextParams",
name: "Key"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "DeleteObject", {}).n("S3Client", "DeleteObjectCommand").f(void 0, void 0).ser(se_DeleteObjectCommand).de(de_DeleteObjectCommand).build()){};
(function(_) {
_["MD5"] = "MD5";
_["CRC32"] = "CRC32";
_["CRC32C"] = "CRC32C";
_["SHA1"] = "SHA1";
_["SHA256"] = "SHA256";
})(ChecksumAlgorithm || (ChecksumAlgorithm = {}));
(function(_) {
_["HEADER"] = "header";
_["TRAILER"] = "trailer";
})(ChecksumLocation || (ChecksumLocation = {}));
var DEFAULT_CHECKSUM_ALGORITHM = ChecksumAlgorithm.MD5, S3_EXPRESS_DEFAULT_CHECKSUM_ALGORITHM = ChecksumAlgorithm.CRC32, CLIENT_SUPPORTED_ALGORITHMS = [ ChecksumAlgorithm.CRC32, ChecksumAlgorithm.CRC32C, ChecksumAlgorithm.SHA1, ChecksumAlgorithm.SHA256 ], PRIORITY_ORDER_ALGORITHMS = [ ChecksumAlgorithm.CRC32, ChecksumAlgorithm.CRC32C, ChecksumAlgorithm.SHA1, ChecksumAlgorithm.SHA256 ], getChecksumAlgorithmForRequest = (_, {requestChecksumRequired: ee, requestAlgorithmMember: ne}, ie) => {
const re = ie ? S3_EXPRESS_DEFAULT_CHECKSUM_ALGORITHM : DEFAULT_CHECKSUM_ALGORITHM;
if (!ne || !_[ne]) return ee ? re : void 0;
const se = _[ne];
if (!CLIENT_SUPPORTED_ALGORITHMS.includes(se)) throw new Error(`The checksum algorithm "${se}" is not supported by the client. Select one of ${CLIENT_SUPPORTED_ALGORITHMS}.`);
return se;
}, getChecksumLocationName = _ => _ === ChecksumAlgorithm.MD5 ? "content-md5" : `x-amz-checksum-${_.toLowerCase()}`, hasHeader2 = (_, ee) => {
const ne = _.toLowerCase();
for (const _ of Object.keys(ee)) if (ne === _.toLowerCase()) return true;
return false;
}, isStreaming = _ => void 0 !== _ && "string" != typeof _ && !ArrayBuffer.isView(_) && !isArrayBuffer(_), import_crc323 = __toESM(require_build7()), import_crc32c = __toESM(require_build8()), selectChecksumAlgorithmFunction = (_, ee) => ({
[ChecksumAlgorithm.MD5]: ee.md5,
[ChecksumAlgorithm.CRC32]: import_crc323.AwsCrc32,
[ChecksumAlgorithm.CRC32C]: import_crc32c.AwsCrc32c,
[ChecksumAlgorithm.SHA1]: ee.sha1,
[ChecksumAlgorithm.SHA256]: ee.sha256
}[_]), stringHasher = (_, ee) => {
const ne = new _;
ne.update(toUint8Array(ee || ""));
return ne.digest();
}, flexibleChecksumsMiddlewareOptions = {
name: "flexibleChecksumsMiddleware",
step: "build",
tags: [ "BODY_CHECKSUM" ],
override: true
}, flexibleChecksumsMiddleware = (_, ee) => (ne, ie) => async re => {
if (!HttpRequest.isInstance(re.request)) return ne(re);
const {request: se} = re, {body: oe, headers: le} = se, {base64Encoder: ue, streamHasher: de} = _, {input: fe, requestChecksumRequired: he, requestAlgorithmMember: pe} = ee, ge = getChecksumAlgorithmForRequest(fe, {
requestChecksumRequired: he,
requestAlgorithmMember: pe
}, !!ie.isS3ExpressBucket);
let me = oe, ye = le;
if (ge) {
const ee = getChecksumLocationName(ge), ne = selectChecksumAlgorithmFunction(ge, _);
if (isStreaming(oe)) {
const {getAwsChunkedEncodingStream: ie, bodyLengthChecker: re} = _;
me = ie(oe, {
base64Encoder: ue,
bodyLengthChecker: re,
checksumLocationName: ee,
checksumAlgorithmFn: ne,
streamHasher: de
});
ye = {
...le,
"content-encoding": le["content-encoding"] ? `${le["content-encoding"]},aws-chunked` : "aws-chunked",
"transfer-encoding": "chunked",
"x-amz-decoded-content-length": le["content-length"],
"x-amz-content-sha256": "STREAMING-UNSIGNED-PAYLOAD-TRAILER",
"x-amz-trailer": ee
};
delete ye["content-length"];
} else if (!hasHeader2(ee, le)) {
const _ = await stringHasher(ne, oe);
ye = {
...le,
[ee]: ue(_)
};
}
}
return await ne({
...re,
request: {
...se,
headers: ye,
body: me
}
});
}, getChecksumAlgorithmListForResponse = (_ = []) => {
const ee = [];
for (const ne of PRIORITY_ORDER_ALGORITHMS) if (_.includes(ne) && CLIENT_SUPPORTED_ALGORITHMS.includes(ne)) ee.push(ne);
return ee;
}, isChecksumWithPartNumber = _ => {
const ee = _.lastIndexOf("-");
if (-1 !== ee) {
const ne = _.slice(ee + 1);
if (!ne.startsWith("0")) {
const _ = parseInt(ne, 10);
if (!isNaN(_) && _ >= 1 && _ <= 1e4) return true;
}
}
return false;
};
function createReadStreamOnBuffer(_) {
return new Blob([ _ ]).stream();
}
var getChecksum = async (_, {streamHasher: ee, checksumAlgorithmFn: ne, base64Encoder: ie}) => {
const re = isStreaming(_) ? ee(ne, _) : stringHasher(ne, _);
return ie(await re);
}, validateChecksumFromResponse = async (_, {config: ee, responseAlgorithms: ne}) => {
const ie = getChecksumAlgorithmListForResponse(ne), {body: re, headers: se} = _;
for (const _ of ie) {
const ne = getChecksumLocationName(_), ie = se[ne];
if (ie) {
const se = selectChecksumAlgorithmFunction(_, ee), {streamHasher: oe, base64Encoder: le} = ee, ue = await getChecksum(re, {
streamHasher: oe,
checksumAlgorithmFn: se,
base64Encoder: le
});
if (ue === ie) break;
throw new Error(`Checksum mismatch: expected "${ue}" but received "${ie}" in response header "${ne}".`);
}
}
}, flexibleChecksumsResponseMiddlewareOptions = {
name: "flexibleChecksumsResponseMiddleware",
toMiddleware: "deserializerMiddleware",
relation: "after",
tags: [ "BODY_CHECKSUM" ],
override: true
}, flexibleChecksumsResponseMiddleware = (_, ee) => (ne, ie) => async re => {
if (!HttpRequest.isInstance(re.request)) return ne(re);
const se = re.input, oe = await ne(re), le = oe.response;
let ue;
const {requestValidationModeMember: de, responseAlgorithms: fe} = ee;
if (de && "ENABLED" === se[de]) {
const {clientName: ee, commandName: ne} = ie;
if ("S3Client" === ee && "GetObjectCommand" === ne && getChecksumAlgorithmListForResponse(fe).every((_ => {
const ee = getChecksumLocationName(_), ne = le.headers[ee];
return !ne || isChecksumWithPartNumber(ne);
}))) return oe;
const re = isStreaming(le.body);
if (re) {
ue = await _.streamCollector(le.body);
le.body = createReadStreamOnBuffer(ue);
}
await validateChecksumFromResponse(oe.response, {
config: _,
responseAlgorithms: fe
});
if (re && ue) le.body = createReadStreamOnBuffer(ue);
}
return oe;
}, getFlexibleChecksumsPlugin = (_, ee) => ({
applyToStack: ne => {
ne.add(flexibleChecksumsMiddleware(_, ee), flexibleChecksumsMiddlewareOptions);
ne.addRelativeTo(flexibleChecksumsResponseMiddleware(_, ee), flexibleChecksumsResponseMiddlewareOptions);
}
}), DeleteObjectsCommand = class extends(Command.classBuilder().ep({
...commonParams,
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()), getFlexibleChecksumsPlugin(ne, {
input: this.input,
requestAlgorithmMember: "ChecksumAlgorithm",
requestChecksumRequired: true
}) ];
})).s("AmazonS3", "DeleteObjects", {}).n("S3Client", "DeleteObjectsCommand").f(void 0, void 0).ser(se_DeleteObjectsCommand).de(de_DeleteObjectsCommand).build()){}, DeleteObjectTaggingCommand = class extends(Command.classBuilder().ep({
...commonParams,
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "DeleteObjectTagging", {}).n("S3Client", "DeleteObjectTaggingCommand").f(void 0, void 0).ser(se_DeleteObjectTaggingCommand).de(de_DeleteObjectTaggingCommand).build()){}, DeletePublicAccessBlockCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "DeletePublicAccessBlock", {}).n("S3Client", "DeletePublicAccessBlockCommand").f(void 0, void 0).ser(se_DeletePublicAccessBlockCommand).de(de_DeletePublicAccessBlockCommand).build()){}, GetBucketAccelerateConfigurationCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "GetBucketAccelerateConfiguration", {}).n("S3Client", "GetBucketAccelerateConfigurationCommand").f(void 0, void 0).ser(se_GetBucketAccelerateConfigurationCommand).de(de_GetBucketAccelerateConfigurationCommand).build()){}, GetBucketAclCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "GetBucketAcl", {}).n("S3Client", "GetBucketAclCommand").f(void 0, void 0).ser(se_GetBucketAclCommand).de(de_GetBucketAclCommand).build()){}, GetBucketAnalyticsConfigurationCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "GetBucketAnalyticsConfiguration", {}).n("S3Client", "GetBucketAnalyticsConfigurationCommand").f(void 0, void 0).ser(se_GetBucketAnalyticsConfigurationCommand).de(de_GetBucketAnalyticsConfigurationCommand).build()){}, GetBucketCorsCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "GetBucketCors", {}).n("S3Client", "GetBucketCorsCommand").f(void 0, void 0).ser(se_GetBucketCorsCommand).de(de_GetBucketCorsCommand).build()){}, GetBucketEncryptionCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "GetBucketEncryption", {}).n("S3Client", "GetBucketEncryptionCommand").f(void 0, GetBucketEncryptionOutputFilterSensitiveLog).ser(se_GetBucketEncryptionCommand).de(de_GetBucketEncryptionCommand).build()){}, GetBucketIntelligentTieringConfigurationCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "GetBucketIntelligentTieringConfiguration", {}).n("S3Client", "GetBucketIntelligentTieringConfigurationCommand").f(void 0, void 0).ser(se_GetBucketIntelligentTieringConfigurationCommand).de(de_GetBucketIntelligentTieringConfigurationCommand).build()){}, GetBucketInventoryConfigurationCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "GetBucketInventoryConfiguration", {}).n("S3Client", "GetBucketInventoryConfigurationCommand").f(void 0, GetBucketInventoryConfigurationOutputFilterSensitiveLog).ser(se_GetBucketInventoryConfigurationCommand).de(de_GetBucketInventoryConfigurationCommand).build()){}, GetBucketLifecycleConfigurationCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "GetBucketLifecycleConfiguration", {}).n("S3Client", "GetBucketLifecycleConfigurationCommand").f(void 0, void 0).ser(se_GetBucketLifecycleConfigurationCommand).de(de_GetBucketLifecycleConfigurationCommand).build()){}, GetBucketLocationCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "GetBucketLocation", {}).n("S3Client", "GetBucketLocationCommand").f(void 0, void 0).ser(se_GetBucketLocationCommand).de(de_GetBucketLocationCommand).build()){}, GetBucketLoggingCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "GetBucketLogging", {}).n("S3Client", "GetBucketLoggingCommand").f(void 0, void 0).ser(se_GetBucketLoggingCommand).de(de_GetBucketLoggingCommand).build()){}, GetBucketMetricsConfigurationCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "GetBucketMetricsConfiguration", {}).n("S3Client", "GetBucketMetricsConfigurationCommand").f(void 0, void 0).ser(se_GetBucketMetricsConfigurationCommand).de(de_GetBucketMetricsConfigurationCommand).build()){}, GetBucketNotificationConfigurationCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "GetBucketNotificationConfiguration", {}).n("S3Client", "GetBucketNotificationConfigurationCommand").f(void 0, void 0).ser(se_GetBucketNotificationConfigurationCommand).de(de_GetBucketNotificationConfigurationCommand).build()){}, GetBucketOwnershipControlsCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "GetBucketOwnershipControls", {}).n("S3Client", "GetBucketOwnershipControlsCommand").f(void 0, void 0).ser(se_GetBucketOwnershipControlsCommand).de(de_GetBucketOwnershipControlsCommand).build()){}, GetBucketPolicyCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "GetBucketPolicy", {}).n("S3Client", "GetBucketPolicyCommand").f(void 0, void 0).ser(se_GetBucketPolicyCommand).de(de_GetBucketPolicyCommand).build()){}, GetBucketPolicyStatusCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "GetBucketPolicyStatus", {}).n("S3Client", "GetBucketPolicyStatusCommand").f(void 0, void 0).ser(se_GetBucketPolicyStatusCommand).de(de_GetBucketPolicyStatusCommand).build()){}, GetBucketReplicationCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "GetBucketReplication", {}).n("S3Client", "GetBucketReplicationCommand").f(void 0, void 0).ser(se_GetBucketReplicationCommand).de(de_GetBucketReplicationCommand).build()){}, GetBucketRequestPaymentCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "GetBucketRequestPayment", {}).n("S3Client", "GetBucketRequestPaymentCommand").f(void 0, void 0).ser(se_GetBucketRequestPaymentCommand).de(de_GetBucketRequestPaymentCommand).build()){}, GetBucketTaggingCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "GetBucketTagging", {}).n("S3Client", "GetBucketTaggingCommand").f(void 0, void 0).ser(se_GetBucketTaggingCommand).de(de_GetBucketTaggingCommand).build()){}, GetBucketVersioningCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "GetBucketVersioning", {}).n("S3Client", "GetBucketVersioningCommand").f(void 0, void 0).ser(se_GetBucketVersioningCommand).de(de_GetBucketVersioningCommand).build()){}, GetBucketWebsiteCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "GetBucketWebsite", {}).n("S3Client", "GetBucketWebsiteCommand").f(void 0, void 0).ser(se_GetBucketWebsiteCommand).de(de_GetBucketWebsiteCommand).build()){}, GetObjectAclCommand = class extends(Command.classBuilder().ep({
...commonParams,
Bucket: {
type: "contextParams",
name: "Bucket"
},
Key: {
type: "contextParams",
name: "Key"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "GetObjectAcl", {}).n("S3Client", "GetObjectAclCommand").f(void 0, void 0).ser(se_GetObjectAclCommand).de(de_GetObjectAclCommand).build()){}, GetObjectAttributesCommand = class extends(Command.classBuilder().ep({
...commonParams,
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()), getSsecPlugin(ne) ];
})).s("AmazonS3", "GetObjectAttributes", {}).n("S3Client", "GetObjectAttributesCommand").f(GetObjectAttributesRequestFilterSensitiveLog, void 0).ser(se_GetObjectAttributesCommand).de(de_GetObjectAttributesCommand).build()){}, GetObjectCommand = class extends(Command.classBuilder().ep({
...commonParams,
Bucket: {
type: "contextParams",
name: "Bucket"
},
Key: {
type: "contextParams",
name: "Key"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()), getSsecPlugin(ne), getS3ExpiresMiddlewarePlugin(ne), getFlexibleChecksumsPlugin(ne, {
input: this.input,
requestChecksumRequired: false,
requestValidationModeMember: "ChecksumMode",
responseAlgorithms: [ "CRC32", "CRC32C", "SHA256", "SHA1" ]
}) ];
})).s("AmazonS3", "GetObject", {}).n("S3Client", "GetObjectCommand").f(GetObjectRequestFilterSensitiveLog, GetObjectOutputFilterSensitiveLog).ser(se_GetObjectCommand).de(de_GetObjectCommand).build()){}, GetObjectLegalHoldCommand = class extends(Command.classBuilder().ep({
...commonParams,
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "GetObjectLegalHold", {}).n("S3Client", "GetObjectLegalHoldCommand").f(void 0, void 0).ser(se_GetObjectLegalHoldCommand).de(de_GetObjectLegalHoldCommand).build()){}, GetObjectLockConfigurationCommand = class extends(Command.classBuilder().ep({
...commonParams,
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "GetObjectLockConfiguration", {}).n("S3Client", "GetObjectLockConfigurationCommand").f(void 0, void 0).ser(se_GetObjectLockConfigurationCommand).de(de_GetObjectLockConfigurationCommand).build()){}, GetObjectRetentionCommand = class extends(Command.classBuilder().ep({
...commonParams,
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "GetObjectRetention", {}).n("S3Client", "GetObjectRetentionCommand").f(void 0, void 0).ser(se_GetObjectRetentionCommand).de(de_GetObjectRetentionCommand).build()){}, GetObjectTaggingCommand = class extends(Command.classBuilder().ep({
...commonParams,
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "GetObjectTagging", {}).n("S3Client", "GetObjectTaggingCommand").f(void 0, void 0).ser(se_GetObjectTaggingCommand).de(de_GetObjectTaggingCommand).build()){}, GetObjectTorrentCommand = class extends(Command.classBuilder().ep({
...commonParams,
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "GetObjectTorrent", {}).n("S3Client", "GetObjectTorrentCommand").f(void 0, GetObjectTorrentOutputFilterSensitiveLog).ser(se_GetObjectTorrentCommand).de(de_GetObjectTorrentCommand).build()){}, GetPublicAccessBlockCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "GetPublicAccessBlock", {}).n("S3Client", "GetPublicAccessBlockCommand").f(void 0, void 0).ser(se_GetPublicAccessBlockCommand).de(de_GetPublicAccessBlockCommand).build()){}, HeadBucketCommand = class extends(Command.classBuilder().ep({
...commonParams,
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "HeadBucket", {}).n("S3Client", "HeadBucketCommand").f(void 0, void 0).ser(se_HeadBucketCommand).de(de_HeadBucketCommand).build()){}, HeadObjectCommand = class extends(Command.classBuilder().ep({
...commonParams,
Bucket: {
type: "contextParams",
name: "Bucket"
},
Key: {
type: "contextParams",
name: "Key"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()), getSsecPlugin(ne), getS3ExpiresMiddlewarePlugin(ne) ];
})).s("AmazonS3", "HeadObject", {}).n("S3Client", "HeadObjectCommand").f(HeadObjectRequestFilterSensitiveLog, HeadObjectOutputFilterSensitiveLog).ser(se_HeadObjectCommand).de(de_HeadObjectCommand).build()){}, ListBucketAnalyticsConfigurationsCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "ListBucketAnalyticsConfigurations", {}).n("S3Client", "ListBucketAnalyticsConfigurationsCommand").f(void 0, void 0).ser(se_ListBucketAnalyticsConfigurationsCommand).de(de_ListBucketAnalyticsConfigurationsCommand).build()){}, ListBucketIntelligentTieringConfigurationsCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "ListBucketIntelligentTieringConfigurations", {}).n("S3Client", "ListBucketIntelligentTieringConfigurationsCommand").f(void 0, void 0).ser(se_ListBucketIntelligentTieringConfigurationsCommand).de(de_ListBucketIntelligentTieringConfigurationsCommand).build()){}, ListBucketInventoryConfigurationsCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "ListBucketInventoryConfigurations", {}).n("S3Client", "ListBucketInventoryConfigurationsCommand").f(void 0, ListBucketInventoryConfigurationsOutputFilterSensitiveLog).ser(se_ListBucketInventoryConfigurationsCommand).de(de_ListBucketInventoryConfigurationsCommand).build()){}, ListBucketMetricsConfigurationsCommand = class extends(Command.classBuilder().ep({
...commonParams,
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "ListBucketMetricsConfigurations", {}).n("S3Client", "ListBucketMetricsConfigurationsCommand").f(void 0, void 0).ser(se_ListBucketMetricsConfigurationsCommand).de(de_ListBucketMetricsConfigurationsCommand).build()){}, ListBucketsCommand = class extends(Command.classBuilder().ep({
...commonParams
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "ListBuckets", {}).n("S3Client", "ListBucketsCommand").f(void 0, void 0).ser(se_ListBucketsCommand).de(de_ListBucketsCommand).build()){}, ListDirectoryBucketsCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "ListDirectoryBuckets", {}).n("S3Client", "ListDirectoryBucketsCommand").f(void 0, void 0).ser(se_ListDirectoryBucketsCommand).de(de_ListDirectoryBucketsCommand).build()){}, ListMultipartUploadsCommand = class extends(Command.classBuilder().ep({
...commonParams,
Bucket: {
type: "contextParams",
name: "Bucket"
},
Prefix: {
type: "contextParams",
name: "Prefix"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "ListMultipartUploads", {}).n("S3Client", "ListMultipartUploadsCommand").f(void 0, void 0).ser(se_ListMultipartUploadsCommand).de(de_ListMultipartUploadsCommand).build()){}, ListObjectsCommand = class extends(Command.classBuilder().ep({
...commonParams,
Bucket: {
type: "contextParams",
name: "Bucket"
},
Prefix: {
type: "contextParams",
name: "Prefix"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "ListObjects", {}).n("S3Client", "ListObjectsCommand").f(void 0, void 0).ser(se_ListObjectsCommand).de(de_ListObjectsCommand).build()){}, ListObjectsV2Command = class extends(Command.classBuilder().ep({
...commonParams,
Bucket: {
type: "contextParams",
name: "Bucket"
},
Prefix: {
type: "contextParams",
name: "Prefix"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "ListObjectsV2", {}).n("S3Client", "ListObjectsV2Command").f(void 0, void 0).ser(se_ListObjectsV2Command).de(de_ListObjectsV2Command).build()){}, ListObjectVersionsCommand = class extends(Command.classBuilder().ep({
...commonParams,
Bucket: {
type: "contextParams",
name: "Bucket"
},
Prefix: {
type: "contextParams",
name: "Prefix"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "ListObjectVersions", {}).n("S3Client", "ListObjectVersionsCommand").f(void 0, void 0).ser(se_ListObjectVersionsCommand).de(de_ListObjectVersionsCommand).build()){}, ListPartsCommand = class extends(Command.classBuilder().ep({
...commonParams,
Bucket: {
type: "contextParams",
name: "Bucket"
},
Key: {
type: "contextParams",
name: "Key"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()), getSsecPlugin(ne) ];
})).s("AmazonS3", "ListParts", {}).n("S3Client", "ListPartsCommand").f(ListPartsRequestFilterSensitiveLog, void 0).ser(se_ListPartsCommand).de(de_ListPartsCommand).build()){}, PutBucketAccelerateConfigurationCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()), getFlexibleChecksumsPlugin(ne, {
input: this.input,
requestAlgorithmMember: "ChecksumAlgorithm",
requestChecksumRequired: false
}) ];
})).s("AmazonS3", "PutBucketAccelerateConfiguration", {}).n("S3Client", "PutBucketAccelerateConfigurationCommand").f(void 0, void 0).ser(se_PutBucketAccelerateConfigurationCommand).de(de_PutBucketAccelerateConfigurationCommand).build()){}, PutBucketAclCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()), getFlexibleChecksumsPlugin(ne, {
input: this.input,
requestAlgorithmMember: "ChecksumAlgorithm",
requestChecksumRequired: true
}) ];
})).s("AmazonS3", "PutBucketAcl", {}).n("S3Client", "PutBucketAclCommand").f(void 0, void 0).ser(se_PutBucketAclCommand).de(de_PutBucketAclCommand).build()){}, PutBucketAnalyticsConfigurationCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "PutBucketAnalyticsConfiguration", {}).n("S3Client", "PutBucketAnalyticsConfigurationCommand").f(void 0, void 0).ser(se_PutBucketAnalyticsConfigurationCommand).de(de_PutBucketAnalyticsConfigurationCommand).build()){}, PutBucketCorsCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()), getFlexibleChecksumsPlugin(ne, {
input: this.input,
requestAlgorithmMember: "ChecksumAlgorithm",
requestChecksumRequired: true
}) ];
})).s("AmazonS3", "PutBucketCors", {}).n("S3Client", "PutBucketCorsCommand").f(void 0, void 0).ser(se_PutBucketCorsCommand).de(de_PutBucketCorsCommand).build()){}, PutBucketEncryptionCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()), getFlexibleChecksumsPlugin(ne, {
input: this.input,
requestAlgorithmMember: "ChecksumAlgorithm",
requestChecksumRequired: true
}) ];
})).s("AmazonS3", "PutBucketEncryption", {}).n("S3Client", "PutBucketEncryptionCommand").f(PutBucketEncryptionRequestFilterSensitiveLog, void 0).ser(se_PutBucketEncryptionCommand).de(de_PutBucketEncryptionCommand).build()){}, PutBucketIntelligentTieringConfigurationCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "PutBucketIntelligentTieringConfiguration", {}).n("S3Client", "PutBucketIntelligentTieringConfigurationCommand").f(void 0, void 0).ser(se_PutBucketIntelligentTieringConfigurationCommand).de(de_PutBucketIntelligentTieringConfigurationCommand).build()){}, PutBucketInventoryConfigurationCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "PutBucketInventoryConfiguration", {}).n("S3Client", "PutBucketInventoryConfigurationCommand").f(PutBucketInventoryConfigurationRequestFilterSensitiveLog, void 0).ser(se_PutBucketInventoryConfigurationCommand).de(de_PutBucketInventoryConfigurationCommand).build()){}, PutBucketLifecycleConfigurationCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()), getFlexibleChecksumsPlugin(ne, {
input: this.input,
requestAlgorithmMember: "ChecksumAlgorithm",
requestChecksumRequired: true
}) ];
})).s("AmazonS3", "PutBucketLifecycleConfiguration", {}).n("S3Client", "PutBucketLifecycleConfigurationCommand").f(void 0, void 0).ser(se_PutBucketLifecycleConfigurationCommand).de(de_PutBucketLifecycleConfigurationCommand).build()){}, PutBucketLoggingCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()), getFlexibleChecksumsPlugin(ne, {
input: this.input,
requestAlgorithmMember: "ChecksumAlgorithm",
requestChecksumRequired: true
}) ];
})).s("AmazonS3", "PutBucketLogging", {}).n("S3Client", "PutBucketLoggingCommand").f(void 0, void 0).ser(se_PutBucketLoggingCommand).de(de_PutBucketLoggingCommand).build()){}, PutBucketMetricsConfigurationCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "PutBucketMetricsConfiguration", {}).n("S3Client", "PutBucketMetricsConfigurationCommand").f(void 0, void 0).ser(se_PutBucketMetricsConfigurationCommand).de(de_PutBucketMetricsConfigurationCommand).build()){}, PutBucketNotificationConfigurationCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "PutBucketNotificationConfiguration", {}).n("S3Client", "PutBucketNotificationConfigurationCommand").f(void 0, void 0).ser(se_PutBucketNotificationConfigurationCommand).de(de_PutBucketNotificationConfigurationCommand).build()){}, PutBucketOwnershipControlsCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()), getFlexibleChecksumsPlugin(ne, {
input: this.input,
requestChecksumRequired: true
}) ];
})).s("AmazonS3", "PutBucketOwnershipControls", {}).n("S3Client", "PutBucketOwnershipControlsCommand").f(void 0, void 0).ser(se_PutBucketOwnershipControlsCommand).de(de_PutBucketOwnershipControlsCommand).build()){}, PutBucketPolicyCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()), getFlexibleChecksumsPlugin(ne, {
input: this.input,
requestAlgorithmMember: "ChecksumAlgorithm",
requestChecksumRequired: true
}) ];
})).s("AmazonS3", "PutBucketPolicy", {}).n("S3Client", "PutBucketPolicyCommand").f(void 0, void 0).ser(se_PutBucketPolicyCommand).de(de_PutBucketPolicyCommand).build()){}, PutBucketReplicationCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()), getFlexibleChecksumsPlugin(ne, {
input: this.input,
requestAlgorithmMember: "ChecksumAlgorithm",
requestChecksumRequired: true
}) ];
})).s("AmazonS3", "PutBucketReplication", {}).n("S3Client", "PutBucketReplicationCommand").f(void 0, void 0).ser(se_PutBucketReplicationCommand).de(de_PutBucketReplicationCommand).build()){}, PutBucketRequestPaymentCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()), getFlexibleChecksumsPlugin(ne, {
input: this.input,
requestAlgorithmMember: "ChecksumAlgorithm",
requestChecksumRequired: true
}) ];
})).s("AmazonS3", "PutBucketRequestPayment", {}).n("S3Client", "PutBucketRequestPaymentCommand").f(void 0, void 0).ser(se_PutBucketRequestPaymentCommand).de(de_PutBucketRequestPaymentCommand).build()){}, PutBucketTaggingCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()), getFlexibleChecksumsPlugin(ne, {
input: this.input,
requestAlgorithmMember: "ChecksumAlgorithm",
requestChecksumRequired: true
}) ];
})).s("AmazonS3", "PutBucketTagging", {}).n("S3Client", "PutBucketTaggingCommand").f(void 0, void 0).ser(se_PutBucketTaggingCommand).de(de_PutBucketTaggingCommand).build()){}, PutBucketVersioningCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()), getFlexibleChecksumsPlugin(ne, {
input: this.input,
requestAlgorithmMember: "ChecksumAlgorithm",
requestChecksumRequired: true
}) ];
})).s("AmazonS3", "PutBucketVersioning", {}).n("S3Client", "PutBucketVersioningCommand").f(void 0, void 0).ser(se_PutBucketVersioningCommand).de(de_PutBucketVersioningCommand).build()){}, PutBucketWebsiteCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()), getFlexibleChecksumsPlugin(ne, {
input: this.input,
requestAlgorithmMember: "ChecksumAlgorithm",
requestChecksumRequired: true
}) ];
})).s("AmazonS3", "PutBucketWebsite", {}).n("S3Client", "PutBucketWebsiteCommand").f(void 0, void 0).ser(se_PutBucketWebsiteCommand).de(de_PutBucketWebsiteCommand).build()){}, PutObjectAclCommand = class extends(Command.classBuilder().ep({
...commonParams,
Bucket: {
type: "contextParams",
name: "Bucket"
},
Key: {
type: "contextParams",
name: "Key"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()), getFlexibleChecksumsPlugin(ne, {
input: this.input,
requestAlgorithmMember: "ChecksumAlgorithm",
requestChecksumRequired: true
}) ];
})).s("AmazonS3", "PutObjectAcl", {}).n("S3Client", "PutObjectAclCommand").f(void 0, void 0).ser(se_PutObjectAclCommand).de(de_PutObjectAclCommand).build()){}, PutObjectCommand = class extends(Command.classBuilder().ep({
...commonParams,
Bucket: {
type: "contextParams",
name: "Bucket"
},
Key: {
type: "contextParams",
name: "Key"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()), getCheckContentLengthHeaderPlugin(ne), getSsecPlugin(ne), getFlexibleChecksumsPlugin(ne, {
input: this.input,
requestAlgorithmMember: "ChecksumAlgorithm",
requestChecksumRequired: false
}) ];
})).s("AmazonS3", "PutObject", {}).n("S3Client", "PutObjectCommand").f(PutObjectRequestFilterSensitiveLog, PutObjectOutputFilterSensitiveLog).ser(se_PutObjectCommand).de(de_PutObjectCommand).build()){}, PutObjectLegalHoldCommand = class extends(Command.classBuilder().ep({
...commonParams,
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()), getFlexibleChecksumsPlugin(ne, {
input: this.input,
requestAlgorithmMember: "ChecksumAlgorithm",
requestChecksumRequired: true
}) ];
})).s("AmazonS3", "PutObjectLegalHold", {}).n("S3Client", "PutObjectLegalHoldCommand").f(void 0, void 0).ser(se_PutObjectLegalHoldCommand).de(de_PutObjectLegalHoldCommand).build()){}, PutObjectLockConfigurationCommand = class extends(Command.classBuilder().ep({
...commonParams,
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()), getFlexibleChecksumsPlugin(ne, {
input: this.input,
requestAlgorithmMember: "ChecksumAlgorithm",
requestChecksumRequired: true
}) ];
})).s("AmazonS3", "PutObjectLockConfiguration", {}).n("S3Client", "PutObjectLockConfigurationCommand").f(void 0, void 0).ser(se_PutObjectLockConfigurationCommand).de(de_PutObjectLockConfigurationCommand).build()){}, PutObjectRetentionCommand = class extends(Command.classBuilder().ep({
...commonParams,
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()), getFlexibleChecksumsPlugin(ne, {
input: this.input,
requestAlgorithmMember: "ChecksumAlgorithm",
requestChecksumRequired: true
}) ];
})).s("AmazonS3", "PutObjectRetention", {}).n("S3Client", "PutObjectRetentionCommand").f(void 0, void 0).ser(se_PutObjectRetentionCommand).de(de_PutObjectRetentionCommand).build()){}, PutObjectTaggingCommand = class extends(Command.classBuilder().ep({
...commonParams,
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()), getFlexibleChecksumsPlugin(ne, {
input: this.input,
requestAlgorithmMember: "ChecksumAlgorithm",
requestChecksumRequired: true
}) ];
})).s("AmazonS3", "PutObjectTagging", {}).n("S3Client", "PutObjectTaggingCommand").f(void 0, void 0).ser(se_PutObjectTaggingCommand).de(de_PutObjectTaggingCommand).build()){}, PutPublicAccessBlockCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseS3ExpressControlEndpoint: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()), getFlexibleChecksumsPlugin(ne, {
input: this.input,
requestAlgorithmMember: "ChecksumAlgorithm",
requestChecksumRequired: true
}) ];
})).s("AmazonS3", "PutPublicAccessBlock", {}).n("S3Client", "PutPublicAccessBlockCommand").f(void 0, void 0).ser(se_PutPublicAccessBlockCommand).de(de_PutPublicAccessBlockCommand).build()){}, RestoreObjectCommand = class extends(Command.classBuilder().ep({
...commonParams,
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()), getFlexibleChecksumsPlugin(ne, {
input: this.input,
requestAlgorithmMember: "ChecksumAlgorithm",
requestChecksumRequired: false
}) ];
})).s("AmazonS3", "RestoreObject", {}).n("S3Client", "RestoreObjectCommand").f(RestoreObjectRequestFilterSensitiveLog, void 0).ser(se_RestoreObjectCommand).de(de_RestoreObjectCommand).build()){}, SelectObjectContentCommand = class extends(Command.classBuilder().ep({
...commonParams,
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()), getSsecPlugin(ne) ];
})).s("AmazonS3", "SelectObjectContent", {
eventStream: {
output: true
}
}).n("S3Client", "SelectObjectContentCommand").f(SelectObjectContentRequestFilterSensitiveLog, SelectObjectContentOutputFilterSensitiveLog).ser(se_SelectObjectContentCommand).de(de_SelectObjectContentCommand).build()){}, UploadPartCommand = class extends(Command.classBuilder().ep({
...commonParams,
Bucket: {
type: "contextParams",
name: "Bucket"
},
Key: {
type: "contextParams",
name: "Key"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()), getSsecPlugin(ne), getFlexibleChecksumsPlugin(ne, {
input: this.input,
requestAlgorithmMember: "ChecksumAlgorithm",
requestChecksumRequired: false
}) ];
})).s("AmazonS3", "UploadPart", {}).n("S3Client", "UploadPartCommand").f(UploadPartRequestFilterSensitiveLog, UploadPartOutputFilterSensitiveLog).ser(se_UploadPartCommand).de(de_UploadPartCommand).build()){}, UploadPartCopyCommand = class extends(Command.classBuilder().ep({
...commonParams,
DisableS3ExpressSessionAuth: {
type: "staticContextParams",
value: true
},
Bucket: {
type: "contextParams",
name: "Bucket"
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()), getThrow200ExceptionsPlugin(ne), getSsecPlugin(ne) ];
})).s("AmazonS3", "UploadPartCopy", {}).n("S3Client", "UploadPartCopyCommand").f(UploadPartCopyRequestFilterSensitiveLog, UploadPartCopyOutputFilterSensitiveLog).ser(se_UploadPartCopyCommand).de(de_UploadPartCopyCommand).build()){}, WriteGetObjectResponseCommand = class extends(Command.classBuilder().ep({
...commonParams,
UseObjectLambdaEndpoint: {
type: "staticContextParams",
value: true
}
}).m((function(_, ee, ne, ie) {
return [ getSerdePlugin(ne, this.serialize, this.deserialize), getEndpointPlugin(ne, _.getEndpointParameterInstructions()) ];
})).s("AmazonS3", "WriteGetObjectResponse", {}).n("S3Client", "WriteGetObjectResponseCommand").f(WriteGetObjectResponseRequestFilterSensitiveLog, void 0).ser(se_WriteGetObjectResponseCommand).de(de_WriteGetObjectResponseCommand).build()){}, commands = {
AbortMultipartUploadCommand,
CompleteMultipartUploadCommand,
CopyObjectCommand,
CreateBucketCommand,
CreateMultipartUploadCommand,
CreateSessionCommand,
DeleteBucketCommand,
DeleteBucketAnalyticsConfigurationCommand,
DeleteBucketCorsCommand,
DeleteBucketEncryptionCommand,
DeleteBucketIntelligentTieringConfigurationCommand,
DeleteBucketInventoryConfigurationCommand,
DeleteBucketLifecycleCommand,
DeleteBucketMetricsConfigurationCommand,
DeleteBucketOwnershipControlsCommand,
DeleteBucketPolicyCommand,
DeleteBucketReplicationCommand,
DeleteBucketTaggingCommand,
DeleteBucketWebsiteCommand,
DeleteObjectCommand,
DeleteObjectsCommand,
DeleteObjectTaggingCommand,
DeletePublicAccessBlockCommand,
GetBucketAccelerateConfigurationCommand,
GetBucketAclCommand,
GetBucketAnalyticsConfigurationCommand,
GetBucketCorsCommand,
GetBucketEncryptionCommand,
GetBucketIntelligentTieringConfigurationCommand,
GetBucketInventoryConfigurationCommand,
GetBucketLifecycleConfigurationCommand,
GetBucketLocationCommand,
GetBucketLoggingCommand,
GetBucketMetricsConfigurationCommand,
GetBucketNotificationConfigurationCommand,
GetBucketOwnershipControlsCommand,
GetBucketPolicyCommand,
GetBucketPolicyStatusCommand,
GetBucketReplicationCommand,
GetBucketRequestPaymentCommand,
GetBucketTaggingCommand,
GetBucketVersioningCommand,
GetBucketWebsiteCommand,
GetObjectCommand,
GetObjectAclCommand,
GetObjectAttributesCommand,
GetObjectLegalHoldCommand,
GetObjectLockConfigurationCommand,
GetObjectRetentionCommand,
GetObjectTaggingCommand,
GetObjectTorrentCommand,
GetPublicAccessBlockCommand,
HeadBucketCommand,
HeadObjectCommand,
ListBucketAnalyticsConfigurationsCommand,
ListBucketIntelligentTieringConfigurationsCommand,
ListBucketInventoryConfigurationsCommand,
ListBucketMetricsConfigurationsCommand,
ListBucketsCommand,
ListDirectoryBucketsCommand,
ListMultipartUploadsCommand,
ListObjectsCommand,
ListObjectsV2Command,
ListObjectVersionsCommand,
ListPartsCommand,
PutBucketAccelerateConfigurationCommand,
PutBucketAclCommand,
PutBucketAnalyticsConfigurationCommand,
PutBucketCorsCommand,
PutBucketEncryptionCommand,
PutBucketIntelligentTieringConfigurationCommand,
PutBucketInventoryConfigurationCommand,
PutBucketLifecycleConfigurationCommand,
PutBucketLoggingCommand,
PutBucketMetricsConfigurationCommand,
PutBucketNotificationConfigurationCommand,
PutBucketOwnershipControlsCommand,
PutBucketPolicyCommand,
PutBucketReplicationCommand,
PutBucketRequestPaymentCommand,
PutBucketTaggingCommand,
PutBucketVersioningCommand,
PutBucketWebsiteCommand,
PutObjectCommand,
PutObjectAclCommand,
PutObjectLegalHoldCommand,
PutObjectLockConfigurationCommand,
PutObjectRetentionCommand,
PutObjectTaggingCommand,
PutPublicAccessBlockCommand,
RestoreObjectCommand,
SelectObjectContentCommand,
UploadPartCommand,
UploadPartCopyCommand,
WriteGetObjectResponseCommand
}, S3 = class extends S3Client {};
createAggregatedClient(commands, S3);
var CheckPointInfoDefault = {
lastLocalSeq: 0,
knownIDs: new Set,
sentIDs: new Set,
receivedFiles: new Set,
sentFiles: new Set
}, PREFIX_TRENCH = "trench", PREFIX_EPHEMERAL = "ephemeral", PREFIX_PERMANENT = "permanent", idx = 0, series = `${Date.now()}`;
function generateId(_) {
if (++idx > 1e4) {
series = `${Date.now()}`;
idx = 0;
}
return `${PREFIX_TRENCH}-${_}-${series}-${idx + 1e7}`;
}
function createRange(_, ee) {
return [ `${PREFIX_TRENCH}-${_}-${ee}-`, `${PREFIX_TRENCH}-${_}-${ee}.` ];
}
function createId(_, ee, ne) {
return `${PREFIX_TRENCH}-${_}-${ee}-${ne + 1e7}`;
}
var indexes = new Map, inProgress = new Set, failed = new Map, Trench = class {
constructor(_, ee = true) {
this._flushTask = void 0;
this.concealing = new Map;
this._db = _;
if (ee) this._flushTask = (async () => {
const ee = await _.keys(`${PREFIX_TRENCH}-${PREFIX_EPHEMERAL}`, `${PREFIX_TRENCH}-${PREFIX_EPHEMERAL}.`);
for (const ne of ee) await _.delete(ne);
})();
}
async eraseAllEphemerals() {
const _ = await this._db.keys(`${PREFIX_TRENCH}-${PREFIX_EPHEMERAL}`, `${PREFIX_TRENCH}-${PREFIX_EPHEMERAL}.`);
for (const ee of _) await this._db.delete(ee);
}
async eraseAllPermanences() {
const _ = await this._db.keys(`${PREFIX_TRENCH}-${PREFIX_PERMANENT}`, `${PREFIX_TRENCH}-${PREFIX_PERMANENT}.`);
for (const ee of _) await this._db.delete(ee);
}
conceal(_) {
const ee = generateId(PREFIX_EPHEMERAL);
this.concealing.set(ee, _);
this._db.set(ee, _).then((async _ => {
if (this.concealing.has(ee)) this.concealing.delete(ee); else await this._db.delete(ee);
}));
return ee;
}
async bury(_) {
if (this.concealing.has(_)) this.concealing.delete(_);
await this._db.delete(_);
}
async expose(_) {
if (this.concealing.has(_)) {
const ee = this.concealing.get(_);
this.concealing.delete(_);
return ee;
}
const ee = await this._db.get(_);
await this._db.delete(_);
return ee;
}
_evacuate(_, ee) {
return async () => {
if (this._flushTask) {
await this._flushTask;
this._flushTask = void 0;
}
await _;
const ne = await this._db.get(ee);
await this._db.delete(ee);
return ne;
};
}
evacuatePromise(_) {
const ee = generateId(PREFIX_EPHEMERAL), ne = (async () => {
const ne = await _;
await this._db.set(ee, ne);
})();
return this._evacuate(ne, ee);
}
evacuate(_) {
if (_ instanceof Promise) return this.evacuatePromise(_);
const ee = generateId(PREFIX_EPHEMERAL), ne = this._db.set(ee, _);
return this._evacuate(ne, ee);
}
async _queue(_, ee, ne, ie) {
var re;
if (void 0 === ie) {
ie = null != (re = indexes.get(ee)) ? re : 0;
indexes.set(ee, ie + 1);
}
const se = createId(_, ee, ie);
await this._db.set(se, ne);
}
async _dequeue(_, ee) {
const ne = createRange(_, ee), ie = (await this._db.keys(ne[0], ne[1])).filter((_ => !inProgress.has(_)));
if (0 !== ie.length) return await this.expose(ie[0]);
}
async _dequeueWithCommit(_, ee) {
const ne = createRange(_, ee), ie = await this._db.keys(ne[0], ne[1]), re = ie.filter((_ => !inProgress.has(_)));
if (0 === re.length) return;
const se = re[0];
inProgress.add(se);
const oe = failed.get(se) || 0, le = await this._db.get(se);
return {
key: se,
value: le,
cancelCount: oe,
pendingItems: ie.length - 1,
commit: async () => {
await this._db.delete(se);
failed.delete(se);
inProgress.delete(se);
},
cancel: () => {
failed.set(se, (failed.get(se) || 0) + 1);
inProgress.delete(se);
}
};
}
queue(_, ee, ne) {
return this._queue(PREFIX_EPHEMERAL, _, ee, ne);
}
dequeue(_) {
return this._dequeue(PREFIX_EPHEMERAL, _);
}
dequeueWithCommit(_) {
return this._dequeueWithCommit(PREFIX_EPHEMERAL, _);
}
queuePermanent(_, ee, ne) {
return this._queue(PREFIX_PERMANENT, _, ee, ne);
}
dequeuePermanent(_) {
return this._dequeue(PREFIX_PERMANENT, _);
}
dequeuePermanentWithCommit(_) {
return this._dequeueWithCommit(PREFIX_PERMANENT, _);
}
}, RECORD_SPLIT = "\n", UNIT_SPLIT = "", te = new TextEncoder;
function serializeDoc(_) {
if (_._id.startsWith("h:")) {
const ee = escapeNewLineFromString(_.data);
return te.encode(`~${_._id}${UNIT_SPLIT}${ee}${RECORD_SPLIT}`);
}
return te.encode(JSON.stringify(_) + RECORD_SPLIT);
}
var JournalSyncAbstract = class {
constructor(_, ee, ne, ie, re, se, oe, le = "") {
this.id = "";
this.key = "";
this.bucket = "";
this.endpoint = "";
this.region = "auto";
this.hash = "";
this.batchSize = 100;
this.requestedStop = false;
this.notifier = new Notifier;
this._currentCheckPointInfo = {
...CheckPointInfoDefault
};
this.isPacking = false;
this.isDownloading = false;
this.id = _;
this.key = ee;
this.bucket = ie;
this.endpoint = ne;
this.region = le;
this.db = se.getDatabase();
this.env = se;
this.useCustomRequestHandler = oe;
this.processReplication = async _ => await se.processReplication(_);
this.store = re;
this.hash = this.getHash(ne, ie, le);
this.trench = new Trench(re);
}
getHash(_, ee, ne) {
return btoa(encodeURI([ _, ee, ne ].join()));
}
applyNewConfig(_, ee, ne, ie, re, se, oe, le = "") {
this.id = _;
this.key = ee;
this.bucket = ie;
this.endpoint = ne;
this.region = le;
this.db = se.getDatabase();
this.env = se;
this.useCustomRequestHandler = oe;
this.processReplication = async _ => await se.processReplication(_);
this.store = re;
this.hash = this.getHash(ne, ie, le);
}
updateInfo(_) {
var ee, ne, ie, re, se, oe, le;
const ue = this.env.replicationStat.value;
this.env.replicationStat.value = {
sent: null != (ee = _.sent) ? ee : ue.sent,
arrived: null != (ne = _.arrived) ? ne : ue.arrived,
maxPullSeq: null != (ie = _.maxPullSeq) ? ie : ue.maxPullSeq,
maxPushSeq: null != (re = _.maxPushSeq) ? re : ue.maxPushSeq,
lastSyncPullSeq: null != (se = _.lastSyncPullSeq) ? se : ue.lastSyncPullSeq,
lastSyncPushSeq: null != (oe = _.lastSyncPushSeq) ? oe : ue.lastSyncPushSeq,
syncStatus: null != (le = _.syncStatus) ? le : ue.syncStatus
};
}
async updateCheckPointInfo(_) {
const ee = `bucketsync-checkpoint-${this.hash}`, ne = _(await this.getCheckpointInfo());
this._currentCheckPointInfo = ne;
await this.store.set(ee, ne);
return ne;
}
async getCheckpointInfo() {
const _ = `bucketsync-checkpoint-${this.hash}`, ee = await this.store.get(_) || {}, ne = [ "knownIDs", "sentIDs", "receivedFiles", "sentFiles" ];
for (const _ of ne) if (_ in ee && typeof Array.isArray(ee[_])) ee[_] = new Set(ee[_]);
this._currentCheckPointInfo = {
...CheckPointInfoDefault,
...ee
};
return this._currentCheckPointInfo;
}
async resetAllCaches() {
await this.trench.eraseAllPermanences();
}
async resetCheckpointInfo() {
await this.updateCheckPointInfo((_ => ({
...CheckPointInfoDefault
})));
}
async _createJournalPack(_) {
const ee = await this.getCheckpointInfo(), ne = _ || ee.lastLocalSeq;
Logger(`Journal reading from seq:${ne}`, LOG_LEVEL_VERBOSE);
let ie = 0, re = 0;
const se = this.db.changes({
live: false,
since: _ || ne,
conflicts: true,
limit: this.batchSize,
return_docs: true,
attachments: false,
style: "all_docs",
filter: _ => {
const ee = this.getDocKey(_);
if (this._currentCheckPointInfo.knownIDs.has(ee)) {
ie++;
return false;
}
if (this._currentCheckPointInfo.sentIDs.has(ee)) {
ie++;
return false;
}
re++;
return true;
}
}), oe = await se;
if (0 == oe.results.length) return {
changes: [],
hasNext: false,
packLastSeq: oe.last_seq
};
Logger(`${re} items possibly needs to be sent (${ie} keys has been received before)`, LOG_LEVEL_DEBUG);
const le = await this.db.bulkGet({
docs: oe.results.map((_ => _.changes.map((ee => ({
id: _.id,
rev: ee.rev
}))))).flat(),
revs: true
}), ue = oe.last_seq, de = ue < (await this.db.info()).update_seq;
return {
changes: le.results.map((_ => _.docs)).flat().filter((_ => "ok" in _)).map((_ => _.ok)),
hasNext: de,
packLastSeq: ue
};
}
getDocKey(_) {
if (_ && _._id.startsWith("h:")) return _._id; else return _._id + "-" + _._rev;
}
async uploadQueued(_ = false, ee = false) {
return await shareRunningResult("upload_queue", (async () => {
const ne = "send_journal", ie = "Uploading journal:", re = _ ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO;
let se = 0;
do {
const _ = await this.trench.dequeuePermanentWithCommit("upload_queue");
if (!_) {
if (this.isPacking) {
Logger(`${ie} Queue run out, but process is running. wait for the next.`, LOG_LEVEL_VERBOSE);
await Promise.race([ this.notifier.nextNotify, delay(3e3) ]);
continue;
}
if (se) Logger(`${ie}: ${se} files have been uploaded!`, re, ne); else if (!ee) Logger("No files needs to be uploaded!", re, ne);
return true;
}
const {key: oe, value: le, commit: ue, cancel: de, cancelCount: fe, pendingItems: he} = _;
this.updateInfo({
sent: se,
maxPushSeq: he + se,
lastSyncPushSeq: 1
});
Logger(`${ie} ${se} / ${he + se}${0 != fe ? `\nRETRY:${fe}` : ""}`, re, ne);
Logger(`${ie} ${oe} ${0 != fe ? `TRY:${fe}` : ""} ${he} left`, LOG_LEVEL_VERBOSE);
if (fe > 3) {
Logger(`${ie} Something went wrong on processing queue ${oe}.`, LOG_LEVEL_NOTICE);
return false;
}
const pe = `${Date.now()}-docs.jsonl.gz`, ge = "application/octet-stream", me = new Blob([ le ], {
type: ge
});
try {
if (!await this.uploadFile(pe, me, ge)) throw new Error("Could not send journalPack to the bucket");
await ue();
se++;
await this.updateCheckPointInfo((_ => ({
..._,
sentFiles: _.sentFiles.add(pe)
})));
Logger(`${ie}: Uploaded ${oe} as ${pe}`, LOG_LEVEL_INFO);
} catch (_) {
Logger(`${ie} Could not send journalPack to the bucket (${oe} as ${pe})`, LOG_LEVEL_NOTICE);
Logger(_, LOG_LEVEL_VERBOSE);
Logger(`${ie} Uploading ${oe} cancelled for retry`, LOG_LEVEL_VERBOSE);
de();
await delay(1e3);
continue;
}
} while (false == this.requestedStop);
}));
}
async packAndCompress(_ = false) {
return await shareRunningResult("create_send_data", (async () => {
try {
this.isPacking = true;
const ee = "pack_journal", ne = _ ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO;
this.requestedStop = false;
const ie = await this.getCheckpointInfo(), re = (await this.db.info()).update_seq, se = ie.sentIDs, oe = 250, le = 10485760;
let ue = ie.lastLocalSeq, de = 0;
const fe = [];
let he = false;
const pe = ie.lastLocalSeq, ge = re - pe;
Logger("Packing Journal: Start sending", ne, ee);
do {
if (this.requestedStop) {
Logger("Packing Journal : Stop requested", ne, ee);
he = true;
break;
}
const {changes: _, hasNext: ie, packLastSeq: re} = await this._createJournalPack(ue), me = re - pe;
if (0 == _.length) he = true; else {
Logger(`Packing Journal: ${me} / ${ge}`, ne, ee);
for (const ee of _) {
const _ = serializeDoc(ee);
se.add(this.getDocKey(ee));
de += _.length;
fe.push(_);
if (fe.length > oe || de > le) {
const _ = concatUInt8Array(fe), ee = _.byteLength, ne = await wrappedDeflate(_, {
consume: true,
level: 8
});
Logger(`Packing Journal: Compressed ${ee} bytes to ${ne.byteLength} bytes (${0 != ee ? Math.ceil(ne.byteLength / ee * 100) : "--"}%)`, LOG_LEVEL_VERBOSE);
this.trench.queuePermanent("upload_queue", ne);
this.notifier.notify();
fe.length = 0;
de = 0;
}
}
}
if (fe.length > 0) {
const _ = concatUInt8Array(fe), ee = _.byteLength, ne = await wrappedDeflate(_, {
consume: true,
level: 8
});
Logger(`Packing Journal: Compressed ${ee} bytes to ${ne.byteLength} bytes (${0 != ee ? Math.ceil(ne.byteLength / ee * 100) : "--"}%)`, LOG_LEVEL_VERBOSE);
this.trench.queuePermanent("upload_queue", ne);
this.notifier.notify();
}
await this.updateCheckPointInfo((_ => ({
..._,
lastLocalSeq: re,
sentIDs: se
})));
ue = re;
if (!ie) {
he = true;
break;
}
} while (false == this.requestedStop && !he);
if (0 != ge) Logger(`Packing Journal: Packaging ${ge}`, ne, ee); else Logger("Packing Journal: No journals to be packed!", ne, ee);
this.notifier.notify();
return true;
} finally {
this.isPacking = false;
this.notifier.notify();
}
}));
}
async sendLocalJournal(_ = false) {
this.updateInfo({
syncStatus: "JOURNAL_SEND"
});
if ((await Promise.all([ this.packAndCompress(_), this.uploadQueued(_) ])).every((_ => _))) if (await this.uploadQueued(_, true)) {
this.updateInfo({
syncStatus: "COMPLETED"
});
return true;
}
this.updateInfo({
syncStatus: "ERRORED"
});
return false;
}
async _getRemoteJournals() {
const _ = [ ...(await this.getCheckpointInfo()).receivedFiles.keys() ].sort(((_, ee) => ee.localeCompare(_, void 0, {
numeric: true
})))[0], ee = (await this.listFiles(_)).filter((_ => !_.startsWith("_")));
if (!ee) return []; else return ee.sort(((_, ee) => _.localeCompare(ee, void 0, {
numeric: true
})));
}
async processDocuments(_) {
let ee = 0, ne = 0;
try {
const ie = [], re = [];
_.forEach((_ => {
if (_._id.startsWith("h:")) ie.push(_); else re.push(_);
}));
try {
const _ = (await this.db.allDocs({
include_docs: true,
keys: [ ...ie.map((_ => _._id)) ]
})).rows.map((_ => {
var ee;
return null != (ee = _.id) ? ee : void 0;
})), ee = new Set(_.filter((_ => void 0 !== _))), ne = ie.filter((_ => !ee.has(_._id))).map((_ => ({
..._,
_rev: void 0
}))), re = await this.db.bulkDocs(ne, {
new_edits: true
}), se = re.filter((_ => "error" in _)).map((_ => _.id));
ne.filter((_ => -1 === se.indexOf(_._id))).forEach((_ => sendValue(`leaf-${_._id}`, _)));
await this.updateCheckPointInfo((_ => ({
..._,
knownIDs: setAllItems(_.knownIDs, ie.map((_ => this.getDocKey(_))))
})));
Logger(`Saved ${re.length} chunks in transferred ${ie.length} chunks (Error:${se.length})`, LOG_LEVEL_VERBOSE);
} catch (_) {
Logger("Applying chunks failed", LOG_LEVEL_INFO);
Logger(_, LOG_LEVEL_VERBOSE);
}
const se = re.map((_ => ({
[_._id]: _._revisions.ids.map(((ee, ne) => `${_._revisions.start - ne}-${ee}`))
}))).reduce(((_, ee) => ({
..._,
...ee
})), {}), oe = await this.db.revsDiff(se), le = re.filter((_ => {
var ee;
return _._id in oe && "missing" in oe[_._id] && ((null == (ee = oe[_._id].missing) ? void 0 : ee.length) || 0) > 0;
}));
Logger(`Applying ${le.length} docs (Total transferred:${re.length}, docs:${_.length})`, LOG_LEVEL_VERBOSE);
await this.db.bulkDocs(le, {
new_edits: false
});
await this.processReplication(le);
await this.updateCheckPointInfo((_ => ({
..._,
knownIDs: setAllItems(_.knownIDs, re.map((_ => this.getDocKey(_))))
})));
ee += le.length;
ne += re.length;
Logger(`Applied ${ee} of ${ne} docs (${ne - ee} skipped)`, LOG_LEVEL_VERBOSE);
return true;
} catch (_) {
Logger("Applying journal failed", LOG_LEVEL_INFO);
Logger(_, LOG_LEVEL_VERBOSE);
return false;
}
}
async processDownloadedJournals(_ = false, ee = false) {
return await shareRunningResult("process_downloaded_journals", (async () => {
const ne = "send_journal", ie = _ ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO, re = "Processing journal:";
let se = 0;
do {
const _ = await this.trench.dequeuePermanentWithCommit("parse_file");
if (!_) {
if (this.isDownloading) {
Logger(`${re} Queue run out, but process is running. wait for the next.`, LOG_LEVEL_VERBOSE);
await Promise.race([ this.notifier.nextNotify, delay(3e3) ]);
continue;
}
if (se) Logger(`${re} ${se} files have been uploaded!`, ie, ne); else if (!ee) Logger(`${re} No files needs to be processed!`, ie, ne);
return true;
}
const {key: oe, value: le, commit: ue, cancel: de, cancelCount: fe, pendingItems: he} = _;
this.updateInfo({
arrived: se,
maxPullSeq: he + se,
lastSyncPullSeq: 1
});
Logger(`${re} ${se} / ${he + se}${0 != fe ? `\nRETRY:${fe}` : ""}`, ie, "processjournal");
if (fe > 3) {
Logger(`${re} Something went wrong on processing queue ${oe}.`, LOG_LEVEL_NOTICE);
return false;
}
const pe = await wrappedInflate(le, {
consume: true
});
if (0 == pe.length) {
await ue();
se++;
Logger(`${re}: ${oe} has been processed`, LOG_LEVEL_INFO);
continue;
}
let ge = 0, me = 0;
const ye = new TextDecoder, ve = [];
do {
me = pe.indexOf(10, ge);
if (-1 == me) break;
const _ = pe.slice(ge, me), ee = ye.decode(_);
if (ee.startsWith("~")) {
const [_, ne] = ee.substring(1).split(UNIT_SPLIT);
ve.push({
_id: _,
data: unescapeNewLineFromString(ne),
type: "leaf",
_rev: ""
});
} else ve.push(JSON.parse(ee));
ge = me + 1;
} while (me > 0);
try {
if (await this.processDocuments(ve)) {
await ue();
se++;
Logger(`${re}: ${oe} has been processed`, LOG_LEVEL_INFO);
} else throw new Error("Could not process downloaded journals");
} catch (_) {
Logger(`${re}: Could not process downloaded journals`, LOG_LEVEL_NOTICE);
Logger(_, LOG_LEVEL_VERBOSE);
Logger(`${re}: ${oe} cancelled for retry`, LOG_LEVEL_VERBOSE);
de();
await delay(1e3);
continue;
}
} while (false == this.requestedStop);
return true;
}));
}
async downloadRemoteJournals(_ = false) {
return await shareRunningResult("downloadRemoteJournals", (async () => {
try {
this.isDownloading = true;
const ee = _ ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO;
Logger("Receiving Journal: Getting list of remote journal", ee, "receivejournal");
const ne = await this._getRemoteJournals();
if (0 == ne.length) {
Logger("Receiving Journal: No journals needs to be downloaded", ee, "receivejournal");
return true;
}
let ie = 0;
for (const _ of ne) {
ie++;
Logger(`Receiving Journal: ${ie} / ${ne.length}`, ee, "receivejournal");
if (this.requestedStop) {
Logger(`Receiving canceled: ${_}`, ee);
return false;
}
if (!this._currentCheckPointInfo.sentFiles.has(_)) try {
const ee = await this.downloadFile(_);
if (false === ee) throw new Error("Download Error");
await this.trench.queuePermanent("parse_file", ee);
await this.updateCheckPointInfo((ee => ({
...ee,
receivedFiles: ee.receivedFiles.add(_)
})));
this.notifier.notify();
} catch (ne) {
Logger(`Could not download ${_}`, ee);
Logger(ne, LOG_LEVEL_DEBUG);
return false;
} else {
Logger(`Receiving Journal: ${_} is own sent file`, LOG_LEVEL_VERBOSE);
await this.updateCheckPointInfo((ee => ({
...ee,
receivedFiles: ee.receivedFiles.add(_)
})));
}
}
} finally {
this.isDownloading = false;
this.notifier.notify();
}
this.notifier.notify();
return true;
}));
}
async receiveRemoteJournal(_ = false) {
this.updateInfo({
syncStatus: "JOURNAL_RECEIVE"
});
this.requestedStop = false;
if ((await Promise.all([ this.downloadRemoteJournals(_), this.processDownloadedJournals(_) ])).every((_ => _))) if (await this.processDownloadedJournals(_, true)) {
this.updateInfo({
syncStatus: "COMPLETED"
});
return true;
}
this.updateInfo({
syncStatus: "ERRORED"
});
return false;
}
async sync(_ = false) {
var ee;
return null != (ee = await shareRunningResult("replicate", (async () => {
this.requestedStop = false;
const ee = await this.receiveRemoteJournal(_);
if (!this.requestedStop) if (ee) return await this.sendLocalJournal(_); else Logger("Could not receive remote journal, so we prevent sending local journals to prevent unwanted mass transfers", _ ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO);
}))) ? ee : false;
}
requestStop() {
this.requestedStop = true;
}
}, JournalSyncMinio = class extends JournalSyncAbstract {
_getClient() {
if (this._instance) return this._instance;
const _ = this.endpoint ? {
endpoint: this.endpoint,
forcePathStyle: true
} : {};
this._instance = new S3({
region: this.region,
..._,
credentials: {
accessKeyId: this.id,
secretAccessKey: this.key
},
maxAttempts: 4,
retryStrategy: new ConfiguredRetryStrategy(4, (_ => 100 + 1e3 * _)),
requestHandler: this.useCustomRequestHandler ? this.env.customFetchHandler() : void 0
});
return this._instance;
}
async resetBucket() {
var _;
const ee = this._getClient();
let ne = [], ie = 0, re = 0;
try {
do {
ne = await this.listFiles("");
if (0 == ne.length) break;
const _ = new DeleteObjectsCommand({
Bucket: this.bucket,
Delete: {
Objects: ne.map((_ => ({
Key: _
})))
}
}), se = await ee.send(_), {Deleted: oe, Errors: le} = se;
ie += (null == oe ? void 0 : oe.length) || 0;
re += (null == le ? void 0 : le.length) || 0;
Logger(`${ie} items has been deleted!${0 != re ? ` (${re} items failed to delete)` : ""}`, LOG_LEVEL_NOTICE, "reset-bucket");
} while (0 == ne.length);
} catch (_) {
Logger("WARNING! Could not delete files. you should try it once or remake the bucket manually", LOG_LEVEL_NOTICE, "reset-bucket");
Logger(_, LOG_LEVEL_VERBOSE);
}
const se = await this._getRemoteJournals();
if (0 == se.length) {
Logger("Nothing to delete!", LOG_LEVEL_NOTICE);
return true;
}
const oe = new DeleteObjectsCommand({
Bucket: this.bucket,
Delete: {
Objects: se.map((_ => ({
Key: _
})))
}
}), le = await ee.send(oe);
Logger(`${(null == (_ = null == le ? void 0 : le.Deleted) ? void 0 : _.length) || 0} items has been deleted!`, LOG_LEVEL_NOTICE);
await this.resetCheckpointInfo();
return true;
}
async uploadJson(_, ee) {
try {
return await this.uploadFile(_, new Blob([ JSON.stringify(ee) ]), "application/json");
} catch (ee) {
Logger(`Could not upload json ${_}`);
Logger(ee, LOG_LEVEL_VERBOSE);
return false;
}
}
async downloadJson(_) {
try {
const ee = await this.downloadFile(_, true);
if (!ee) return false; else return JSON.parse((new TextDecoder).decode(ee));
} catch (ee) {
Logger(`Could not download json ${_}`);
Logger(ee, LOG_LEVEL_VERBOSE);
return false;
}
}
async uploadFile(_, ee, ne) {
try {
let ie = new Uint8Array(await ee.arrayBuffer());
const re = this.env.getSettings();
if (re.encrypt && "" != re.passphrase) ie = await encryptBinary(ie, re.passphrase, re.useDynamicIterationCount);
const se = this._getClient(), oe = new PutObjectCommand({
Bucket: this.bucket,
Key: _,
Body: ie,
ContentType: ne
});
if (await se.send(oe)) return true;
} catch (ee) {
Logger(`Could not upload ${_}`);
Logger(ee, LOG_LEVEL_VERBOSE);
}
return false;
}
async downloadFile(_, ee = false) {
const ne = this._getClient(), ie = new GetObjectCommand({
Bucket: this.bucket,
Key: _,
...ee ? {
ResponseCacheControl: "no-cache"
} : {}
}), re = await ne.send(ie), se = this.env.getSettings();
try {
if (re.Body) {
let _ = await re.Body.transformToByteArray();
if (se.encrypt && "" != se.passphrase) _ = await decryptBinary(_, se.passphrase, se.useDynamicIterationCount);
return _;
}
} catch (ee) {
Logger(`Could not download ${_}`);
Logger(ee, LOG_LEVEL_VERBOSE);
}
return false;
}
async listFiles(_, ee) {
const ne = this._getClient(), ie = await ne.listObjectsV2({
Bucket: this.bucket,
StartAfter: _,
...ee ? {
MaxKeys: ee
} : {}
});
if (!ie.Contents) return []; else return ie.Contents.map((_ => _.Key));
}
async isAvailable() {
const _ = this._getClient(), ee = new HeadBucketCommand({
Bucket: this.bucket
});
try {
await _.send(ee);
return true;
} catch (_) {
Logger("Could not connected to the remote bucket", LOG_LEVEL_NOTICE);
Logger(_, LOG_LEVEL_VERBOSE);
return false;
}
}
}, MILSTONE_DOCID2 = "_00000000-milestone.json", currentVersionRange2 = {
min: 0,
max: 2,
current: 2
}, LiveSyncJournalReplicator = class extends LiveSyncAbstractReplicator {
constructor(_) {
super(_);
this.syncStatus = "NOT_CONNECTED";
this.docArrived = 0;
this.docSent = 0;
this.lastSyncPullSeq = 0;
this.maxPullSeq = 0;
this.lastSyncPushSeq = 0;
this.maxPushSeq = 0;
this.nodeid = "";
this.remoteLocked = false;
this.remoteCleaned = false;
this.remoteLockedAndDeviceNotAccepted = false;
this.updateInfo = () => {
this.env.replicationStat.value = {
sent: this.docSent,
arrived: this.docArrived,
maxPullSeq: this.maxPullSeq,
maxPushSeq: this.maxPushSeq,
lastSyncPullSeq: this.lastSyncPullSeq,
lastSyncPushSeq: this.lastSyncPushSeq,
syncStatus: this.syncStatus
};
};
this.env = _;
this.initializeDatabaseForReplication();
this.env.getDatabase().on("close", (() => {
this.closeReplication();
}));
}
get client() {
return this.setupJournalSyncClient();
}
setupJournalSyncClient() {
const _ = this.env.getSettings(), ee = _.accessKey, ne = _.secretKey, ie = _.bucket, re = _.region, se = _.endpoint, oe = _.useCustomRequestHandler;
if (this._client) this._client.applyNewConfig(ee, ne, se, ie, this.env.simpleStore, this.env, oe, re); else this._client = new JournalSyncMinio(ee, ne, se, ie, this.env.simpleStore, this.env, oe, re);
return this._client;
}
async ensureBucketIsCompatible(_, ee) {
const ne = await this.client.downloadJson(MILSTONE_DOCID2);
return await ensureRemoteIsCompatible(ne, this.env.getSettings(), _, ee, (async _ => {
await this.client.uploadJson(MILSTONE_DOCID2, _);
}));
}
async migrate(_, ee) {
Logger(`Database updated from ${_} to ${ee}`, LOG_LEVEL_NOTICE);
return true;
}
terminateSync() {
this.client.requestStop();
}
async openReplication(_, ee, ne, ie = false) {
if (!await this.checkReplicationConnectivity(false, ie)) return false;
await this.client.sync(ne);
}
async replicateAllToServer(_, ee) {
if (!await this.checkReplicationConnectivity(false)) return false; else return await this.client.sendLocalJournal(ee);
}
async replicateAllFromServer(_, ee) {
if (!await this.checkReplicationConnectivity(false)) return false; else return await this.client.receiveRemoteJournal(ee);
}
async checkReplicationConnectivity(_, ee = false) {
if (!await this.client.isAvailable()) return false;
if (!_) {
this.remoteCleaned = false;
this.remoteLocked = false;
this.remoteLockedAndDeviceNotAccepted = false;
this.tweakSettingsMismatched = false;
const _ = await this.ensureBucketIsCompatible(this.nodeid, currentVersionRange2);
if ("INCOMPATIBLE" == _) {
Logger("The remote database has no compatibility with the running version. Please upgrade the plugin.", LOG_LEVEL_NOTICE);
return false;
} else if ("NODE_LOCKED" == _) {
Logger("The remote database has been rebuilt or corrupted since we have synchronized last time. Fetch rebuilt DB, explicit unlocking or chunk clean-up is required.", LOG_LEVEL_NOTICE);
this.remoteLockedAndDeviceNotAccepted = true;
this.remoteLocked = true;
return false;
} else if ("LOCKED" == _) this.remoteLocked = true; else if ("NODE_CLEANED" == _) if (ee) this.remoteLocked = true; else {
Logger("The remote database has been cleaned up. Fetch rebuilt DB, explicit unlocking or chunk clean-up is required.", LOG_LEVEL_NOTICE);
this.remoteLockedAndDeviceNotAccepted = true;
this.remoteLocked = true;
this.remoteCleaned = true;
return false;
} else if ("MISMATCHED" == _[0]) {
Logger("Configuration mismatching between the clients has been detected. This can be harmful or extra capacity consumption. We have to make these value unified.", LOG_LEVEL_NOTICE);
this.tweakSettingsMismatched = true;
this.mismatchedTweakValues = _[1];
return false;
}
}
return true;
}
async fetchRemoteChunks(_, ee) {
return [];
}
closeReplication() {
this.client.requestStop();
this.syncStatus = "CLOSED";
Logger("Replication closed");
this.updateInfo();
}
async tryResetRemoteDatabase(_) {
this.closeReplication();
try {
await this.client.resetBucket();
Logger("Remote Bucket Cleared", LOG_LEVEL_NOTICE);
await this.tryCreateRemoteDatabase(_);
} catch (_) {
Logger("Something happened on Remote Bucket Clear", LOG_LEVEL_NOTICE);
Logger(_, LOG_LEVEL_NOTICE);
}
}
async tryCreateRemoteDatabase(_) {
this.closeReplication();
Logger("Remote Database Created or Connected", LOG_LEVEL_NOTICE);
}
async markRemoteLocked(_, ee, ne) {
const ie = {
_id: MILSTONE_DOCID2,
type: "milestoneinfo",
created: new Date / 1,
locked: ee,
cleaned: ne,
accepted_nodes: [ this.nodeid ],
node_chunk_info: {
[this.nodeid]: currentVersionRange2
},
tweak_values: {}
}, re = {
...ie,
...await this.client.downloadJson(MILSTONE_DOCID2) || {}
};
re.node_chunk_info = {
...ie.node_chunk_info,
...re.node_chunk_info
};
re.accepted_nodes = [ this.nodeid ];
re.locked = ee;
re.cleaned = re.cleaned || ne;
if (ee) Logger("Lock remote bucket to prevent data corruption", LOG_LEVEL_NOTICE); else Logger("Unlock remote bucket to prevent data corruption", LOG_LEVEL_NOTICE);
await this.client.uploadJson(MILSTONE_DOCID2, re);
}
async markRemoteResolved(_) {
const ee = {
_id: MILSTONE_DOCID2,
type: "milestoneinfo",
created: new Date / 1,
locked: false,
accepted_nodes: [ this.nodeid ],
node_chunk_info: {
[this.nodeid]: currentVersionRange2
},
tweak_values: {}
}, ne = {
...ee,
...await this.client.downloadJson(MILSTONE_DOCID2) || {}
};
ne.node_chunk_info = {
...ee.node_chunk_info,
...ne.node_chunk_info
};
ne.accepted_nodes = Array.from(new Set([ ...ne.accepted_nodes, this.nodeid ]));
Logger("Mark this device as 'resolved'.", LOG_LEVEL_NOTICE);
await this.client.uploadJson(MILSTONE_DOCID2, ne);
}
async tryConnectRemote(_, ee = true) {
const ne = _.accessKey, ie = _.secretKey, re = _.bucket, se = _.region, oe = _.endpoint, le = _.useCustomRequestHandler, ue = new JournalSyncMinio(ne, ie, oe, re, this.env.simpleStore, this.env, le, se);
try {
await ue.listFiles("", 1);
Logger(`Connected to ${oe} successfully!`, LOG_LEVEL_NOTICE);
return true;
} catch (_) {
Logger(`Error! Could not connected to ${oe}\n${_.message}`, LOG_LEVEL_NOTICE);
Logger(_, LOG_LEVEL_NOTICE);
return false;
}
}
async resetRemoteTweakSettings(_) {
try {
const _ = await this.client.downloadJson(MILSTONE_DOCID2);
if (!_) throw new Error("Missing remote milestone");
_.tweak_values = {};
Logger("tweak values on the remote database have been cleared", LOG_LEVEL_VERBOSE);
await this.client.uploadJson(MILSTONE_DOCID2, _);
} catch (_) {
Logger("Could not retrieve remote milestone", LOG_LEVEL_NOTICE);
throw _;
}
}
}, ObsHttpHandler = class extends FetchHttpHandler {
constructor(_, ee) {
super(_);
this.requestTimeoutInMs = void 0 === _ ? void 0 : _.requestTimeout;
this.reverseProxyNoSignUrl = ee;
}
async handle(_, {abortSignal: ee} = {}) {
if (null == ee ? void 0 : ee.aborted) {
const _ = new Error("Request aborted");
_.name = "AbortError";
return Promise.reject(_);
}
let ne = _.path;
if (_.query) {
const ee = buildQueryString(_.query);
if (ee) ne += `?${ee}`;
}
const {port: ie, method: re} = _;
let se = `${_.protocol}//${_.hostname}${ie ? `:${ie}` : ""}${ne}`;
if (void 0 !== this.reverseProxyNoSignUrl && "" !== this.reverseProxyNoSignUrl) {
const _ = new URL(se);
_.host = this.reverseProxyNoSignUrl;
se = _.href;
}
const oe = "GET" === re || "HEAD" === re ? void 0 : _.body, le = {};
for (const ee of Object.keys(_.headers)) {
const ne = ee.toLowerCase();
if ("host" !== ne && "content-length" !== ne) le[ne] = _.headers[ee];
}
let ue;
if (void 0 !== le["content-type"]) ue = le["content-type"];
let de = oe;
if (ArrayBuffer.isView(oe)) de = new Uint8Array(oe.buffer).buffer;
const fe = {
body: de,
headers: le,
method: re,
url: se,
contentType: ue
}, he = [ (0, import_obsidian.requestUrl)(fe).then((_ => {
const ee = _.headers, ne = {};
for (const _ of Object.keys(ee)) ne[_.toLowerCase()] = ee[_];
const ie = new ReadableStream({
start(ee) {
ee.enqueue(new Uint8Array(_.arrayBuffer));
ee.close();
}
});
return {
response: new HttpResponse({
headers: ne,
statusCode: _.status,
body: ie
})
};
})), requestTimeout(this.requestTimeoutInMs) ];
if (ee) he.push(new Promise(((_, ne) => {
ee.onabort = () => {
const _ = new Error("Request aborted");
_.name = "AbortError";
ne(_);
};
})));
return Promise.race(he);
}
}, import_obsidian7 = require("obsidian"), isDebug = false;
setNoticeClass(import_obsidian.Notice);
setGlobalLogFunction(((_, ee, ne) => {
const ie = {
message: _,
level: ee,
key: ne
};
logStore.enqueue(ie);
}));
var recentLogs = [], recentLogProcessor = new QueueProcessor((_ => {
recentLogs = [ ...recentLogs, ..._ ].splice(-200);
logMessages.value = recentLogs;
}), {
batchSize: 25,
delay: 10,
suspended: false,
concurrentLimit: 1
}).resumePipeLine();
async function fetchByAPI(_) {
var ee, ne;
const ie = await (0, import_obsidian.requestUrl)(_);
if (ie.status - ie.status % 100 != 200) {
const _ = new Error(`Request Error:${ie.status}`);
if (ie.json) {
_.message = ie.json.reason;
_.name = `${null != (ee = ie.json.error) ? ee : ""}:${null != (ne = ie.json.message) ? ne : ""}`;
}
_.status = ie.status;
throw _;
}
return ie;
}
var SETTING_HEADER = "````yaml:livesync-setting\n", SETTING_FOOTER = "\n````", ObsidianLiveSyncPlugin = class extends import_obsidian.Plugin {
constructor() {
super(...arguments);
this._suspended = false;
this.deviceAndVaultName = "";
this.isReady = false;
this.packageVersion = "";
this.manifestVersion = "";
this.addOnHiddenFileSync = new HiddenFileSync(this);
this.addOnSetup = new SetupLiveSync(this);
this.addOnConfigSync = new ConfigSync(this);
this.addOns = [ this.addOnHiddenFileSync, this.addOnSetup, this.addOnConfigSync ];
this.periodicSyncProcessor = new PeriodicProcessor(this, (async () => await this.replicate()));
this.last_successful_post = false;
this.vaultAccess = new SerializedFileAccess(this.app);
this._unloaded = false;
this.requestCount = reactiveSource(0);
this.responseCount = reactiveSource(0);
this.processReplication = _ => this.parseReplicationResult(_);
this.replicationStat = reactiveSource({
sent: 0,
arrived: 0,
maxPullSeq: 0,
maxPushSeq: 0,
lastSyncPullSeq: 0,
lastSyncPushSeq: 0,
syncStatus: "CLOSED"
});
this.isRedFlagRaised = () => this.isFlagFileExist(FLAGMD_REDFLAG);
this.isRedFlag2Raised = () => this.isFlagFileExist(FLAGMD_REDFLAG2) || this.isFlagFileExist(FLAGMD_REDFLAG2_HR);
this.isRedFlag3Raised = () => this.isFlagFileExist(FLAGMD_REDFLAG3) || this.isFlagFileExist(FLAGMD_REDFLAG3_HR);
this.simpleStore = {
get: async _ => await this.kvDB.get(`os-${_}`),
set: async (_, ee) => {
await this.kvDB.set(`os-${_}`, ee);
},
delete: async _ => {
await this.kvDB.del(`os-${_}`);
},
keys: async (_, ee, ne) => {
const ie = this.kvDB.keys(IDBKeyRange.bound(`os-${_ || ""}`, `os-${ee || ""}`), ne);
return (await ie).map((_ => _.toString())).filter((_ => _.startsWith("os-"))).map((_ => _.substring(3)));
}
};
this.usedPassphrase = "";
this.vaultManager = new StorageEventManagerObsidian(this);
this.hasFocus = true;
this.isLastHidden = false;
this.pendingFileEventCount = reactiveSource(0);
this.processingFileEventCount = reactiveSource(0);
this.notifies = {};
this.statusLog = reactiveSource("");
this._saveQueuedFiles = throttle((() => {
const _ = this.replicationResultProcessor._queue.filter((_ => null != _)).map((_ => {
var ee;
return null != (ee = null == _ ? void 0 : _._id) ? ee : "";
}));
fireAndForget((() => this.kvDB.set("queued-files", _)));
}), 100);
this.databaseQueueCount = reactiveSource(0);
this.databaseQueuedProcessor = new QueueProcessor((async _ => {
var ee;
const ne = _[0], ie = this.getPath(ne), re = await this.localDatabase.getDBEntryFromMeta({
...ne
}, {}, false, true, true);
if (re) if (isInternalMetadata(re._id) && this.settings.syncInternalFiles) {
const _ = this.getPathWithoutPrefix(re);
this.isTargetFile(_).then((ee => ee ? this.addOnHiddenFileSync.procInternalFile(_) : Logger(`Skipped (Not target:${_})`, LOG_LEVEL_VERBOSE)));
} else if (isValidPath(this.getPath(re))) this.storageApplyingProcessor.enqueue(re); else Logger(`Skipped: ${re._id.substring(0, 8)}`, LOG_LEVEL_VERBOSE); else Logger(`Something went wrong while gathering content of ${ie} (${ne._id.substring(0, 8)}, ${null == (ee = ne._rev) ? void 0 : ee.substring(0, 10)}) `, LOG_LEVEL_NOTICE);
}), {
suspended: true,
batchSize: 1,
concurrentLimit: 10,
yieldThreshold: 1,
delay: 0,
totalRemainingReactiveSource: this.databaseQueueCount
}).replaceEnqueueProcessor(((_, ee) => [ ..._.filter((_ => _._id != ee._id)), ee ])).startPipeline();
this.storageApplyingCount = reactiveSource(0);
this.storageApplyingProcessor = new QueueProcessor((async _ => {
const ee = _[0];
await serialized(ee.path, (async () => {
var _, ne;
const ie = this.getPath(ee);
Logger(`Processing ${ie} (${ee._id.substring(0, 8)}: ${null == (_ = ee._rev) ? void 0 : _.substring(0, 5)}) :Started...`, LOG_LEVEL_VERBOSE);
const re = this.vaultAccess.getAbstractFileByPath(this.getPathWithoutPrefix(ee));
if (re instanceof import_obsidian.TFolder) Logger(`${this.getPath(ee)} is already exist as the folder`); else {
await this.processEntryDoc(ee, re instanceof import_obsidian.TFile ? re : void 0);
Logger(`Processing ${ie} (${ee._id.substring(0, 8)} :${null == (ne = ee._rev) ? void 0 : ne.substring(0, 5)}) : Done`);
}
}));
}), {
suspended: true,
batchSize: 1,
concurrentLimit: 6,
yieldThreshold: 1,
delay: 0,
totalRemainingReactiveSource: this.storageApplyingCount
}).replaceEnqueueProcessor(((_, ee) => [ ..._.filter((_ => _._id != ee._id)), ee ])).startPipeline();
this.replicationResultCount = reactiveSource(0);
this.replicationResultProcessor = new QueueProcessor((async _ => {
if (this.settings.suspendParseReplicationResult) return;
const ee = _[0];
if (ee) if (!isChunk(ee._id)) {
for (const _ of this.addOns) if (await _.parseReplicationResultItem(ee)) return;
if ("versioninfo" != ee.type) {
if (ee._id != SYNCINFO_ID && !ee._id.startsWith("_design")) if (isAnyNote(ee)) {
if (this.databaseQueuedProcessor._isSuspended) Logger(`Processing scheduled: ${ee.path}`, LOG_LEVEL_INFO);
const _ = ee.size;
if (this.isFileSizeExceeded(_)) {
Logger(`Processing ${ee.path} has been skipped due to file size exceeding the limit`, LOG_LEVEL_NOTICE);
return;
}
this.databaseQueuedProcessor.enqueue(ee);
}
} else if (ee.version > VER) {
this.replicator.closeReplication();
Logger("Remote database updated to incompatible version. update your Self-hosted LiveSync plugin.", LOG_LEVEL_NOTICE);
}
} else sendValue(`leaf-${ee._id}`, ee);
}), {
batchSize: 1,
suspended: true,
concurrentLimit: 100,
delay: 0,
totalRemainingReactiveSource: this.replicationResultCount
}).replaceEnqueueProcessor(((_, ee) => [ ..._.filter((_ => _._id != ee._id)), ee ])).startPipeline().onUpdateProgress((() => {
this.saveQueuedFiles();
}));
this.lastMessage = "";
this.conflictProcessQueueCount = reactiveSource(0);
this.conflictResolveQueue = new QueueProcessor((async _ => {
const ee = _[0];
await serialized(`conflict-resolve:${ee}`, (async () => {
const _ = await this.checkConflictAndPerformAutoMerge(ee);
if (_ !== MISSING_OR_ERROR && _ !== NOT_CONFLICTED && _ !== CANCELLED) if (_ !== AUTO_MERGED) {
if (this.settings.showMergeDialogOnlyOnActive) {
const _ = this.getActiveFile();
if (_ && _.path != ee) {
Logger(`${ee} is conflicted. Merging process has been postponed to the file have got opened.`, LOG_LEVEL_NOTICE);
return;
}
}
Logger("conflict:Manual merge required!");
await this.resolveConflictByUI(ee, _);
} else {
if (this.settings.syncAfterMerge && !this.suspended) await shareRunningResult("replication", (() => this.replicate()));
Logger("conflict:Automatically merged, but we have to check it again");
this.conflictCheckQueue.enqueue(ee);
}
}));
}), {
suspended: false,
batchSize: 1,
concurrentLimit: 1,
delay: 10,
keepResultUntilDownstreamConnected: false
}).replaceEnqueueProcessor(((_, ee) => {
sendValue("cancel-resolve-conflict:" + ee, true);
return [ ...[ ..._ ].filter((_ => _ != ee)), ee ];
}));
this.conflictCheckQueue = new QueueProcessor((_ => {
const ee = _[0];
if (this.vaultAccess.getAbstractFileByPath(ee) instanceof import_obsidian.TFolder) return []; else return [ ee ];
}), {
suspended: false,
batchSize: 1,
concurrentLimit: 5,
delay: 10,
keepResultUntilDownstreamConnected: true,
pipeTo: this.conflictResolveQueue,
totalRemainingReactiveSource: this.conflictProcessQueueCount
});
this.ignoreFileCache = new LRUCache(300, 25e4, true);
this.ignoreFiles = [];
}
customFetchHandler() {
if (!this._customHandler) this._customHandler = new ObsHttpHandler(void 0, void 0);
return this._customHandler;
}
get suspended() {
var _;
return this._suspended || !(null == (_ = this.settings) ? void 0 : _.isConfigured);
}
set suspended(_) {
this._suspended = _;
}
get shouldBatchSave() {
var _, ee;
return (null == (_ = this.settings) ? void 0 : _.batchSave) && true != (null == (ee = this.settings) ? void 0 : ee.liveSync);
}
get batchSaveMinimumDelay() {
var _, ee;
return null != (ee = null == (_ = this.settings) ? void 0 : _.batchSaveMinimumDelay) ? ee : DEFAULT_SETTINGS.batchSaveMinimumDelay;
}
get batchSaveMaximumDelay() {
var _, ee;
return null != (ee = null == (_ = this.settings) ? void 0 : _.batchSaveMaximumDelay) ? ee : DEFAULT_SETTINGS.batchSaveMaximumDelay;
}
getLastPostFailedBySize() {
return !this.last_successful_post;
}
getDatabase() {
return this.localDatabase.localDatabase;
}
getSettings() {
return this.settings;
}
getIsMobile() {
return this.isMobile;
}
async connectRemoteCouchDB(_, ee, ne, ie, re, se, oe, le) {
if (!isValidRemoteCouchDBURI(_)) return "Remote URI is not valid";
if (_.toLowerCase() != _) return "Remote URI and database name could not contain capital letters.";
if (-1 !== _.indexOf(" ")) return "Remote URI and database name could not contain spaces.";
let ue = "";
if (ee.username && ee.password) {
const _ = String.fromCharCode.apply(null, [ ...writeString(`${ee.username}:${ee.password}`) ]), ne = window.btoa(_);
ue = "Basic " + ne;
} else ue = "";
const de = new index_es_default(_, {
adapter: "http",
auth: ee,
skip_setup: !se,
fetch: async (ee, ie) => {
var re, se;
let oe = "";
const le = ee.toString().substring(_.length), de = null != (re = null == ie ? void 0 : ie.method) ? re : "GET";
if (null == ie ? void 0 : ie.body) {
const ee = ie.body.toString().length;
if (ee > 1e7) if (isCloudantURI(_)) {
this.last_successful_post = false;
Logger("This request should fail on IBM Cloudant.", LOG_LEVEL_VERBOSE);
throw new Error("This request should fail on IBM Cloudant.");
}
oe = ` (${ee})`;
}
if (!ne && "string" == typeof ee && "string" == typeof (null != (se = null == ie ? void 0 : ie.body) ? se : "")) {
const _ = null == ie ? void 0 : ie.body, ne = {
...null == ie ? void 0 : ie.headers
};
if ("" != ue) ne["authorization"] = ue;
delete ne["host"];
delete ne["Host"];
delete ne["content-length"];
delete ne["Content-Length"];
const re = {
url: ee,
method: null == ie ? void 0 : ie.method,
body: _,
headers: ne,
contentType: "application/json"
};
try {
this.requestCount.value = this.requestCount.value + 1;
const _ = await fetchByAPI(re);
if ("POST" == de || "PUT" == de) this.last_successful_post = _.status - _.status % 100 == 200; else this.last_successful_post = true;
Logger(`HTTP:${de}${oe} to:${le} -> ${_.status}`, LOG_LEVEL_DEBUG);
return new Response(_.arrayBuffer, {
headers: _.headers,
status: _.status,
statusText: `${_.status}`
});
} catch (_) {
Logger(`HTTP:${de}${oe} to:${le} -> failed`, LOG_LEVEL_VERBOSE);
if (-1 !== ee.toString().indexOf("_bulk_docs")) this.last_successful_post = false;
Logger(_);
throw _;
} finally {
this.responseCount.value = this.responseCount.value + 1;
}
}
try {
this.requestCount.value = this.requestCount.value + 1;
const _ = await fetch(ee, ie);
if ("POST" == de || "PUT" == de) this.last_successful_post = _.ok; else this.last_successful_post = true;
Logger(`HTTP:${de}${oe} to:${le} -> ${_.status}`, LOG_LEVEL_DEBUG);
if (2 !== Math.floor(_.status / 100)) if ("GET" != de && -1 === le.indexOf("/_local/") && !le.endsWith("/")) {
const ee = _.clone();
Logger(`The request may have failed. The reason sent by the server: ${ee.status}: ${ee.statusText}`);
try {
Logger(await (await ee.blob()).text(), LOG_LEVEL_VERBOSE);
} catch (_) {
Logger("Cloud not parse response", LOG_LEVEL_VERBOSE);
}
} else Logger("Just checkpoint or some server information has been missing. The 404 error shown above is not an error.", LOG_LEVEL_VERBOSE);
return _;
} catch (_) {
Logger(`HTTP:${de}${oe} to:${le} -> failed`, LOG_LEVEL_VERBOSE);
if (-1 !== ee.toString().indexOf("_bulk_docs")) this.last_successful_post = false;
Logger(_);
throw _;
} finally {
this.responseCount.value = this.responseCount.value + 1;
}
}
});
enableCompression(de, le);
if ("false" !== ie && "string" == typeof ie) enableEncryption(de, ie, re, false);
if (oe) return {
db: de,
info: {
db_name: "",
doc_count: 0,
update_seq: ""
}
};
try {
const _ = await de.info();
return {
db: de,
info: _
};
} catch (_) {
let ee = `${null == _ ? void 0 : _.name}:${null == _ ? void 0 : _.message}`;
if ("TypeError" == (null == _ ? void 0 : _.name) && "Failed to fetch" == (null == _ ? void 0 : _.message)) ee += "\n**Note** This error caused by many reasons. The only sure thing is you didn't touch the server.\nTo check details, open inspector.";
Logger(_, LOG_LEVEL_VERBOSE);
return ee;
}
}
get isMobile() {
return this.app.isMobile;
}
get vaultName() {
return this.app.vault.getName();
}
getActiveFile() {
return this.app.workspace.getActiveFile();
}
get appId() {
return `${"appId" in this.app ? this.app.appId : ""}`;
}
id2path(_, ee, ne) {
const ie = id2path(_, ee);
if (ne && isInternalMetadata(ie)) return stripInternalMetadataPrefix(ie); else return ie;
}
getPath(_) {
return getPath2(_);
}
getPathWithoutPrefix(_) {
return getPathWithoutPrefix(_);
}
async path2id(_, ee) {
const ne = addPrefix(_, null != ee ? ee : "");
return await path2id(ne, this.settings.usePathObfuscation ? this.settings.passphrase : "");
}
createPouchDBInstance(_, ee) {
const ne = null != ee ? ee : {};
if (this.settings.useIndexedDBAdapter) {
ne.adapter = "indexeddb";
ne.purged_infos_limit = 1;
return new index_es_default(_ + "-indexeddb", ne);
}
return new index_es_default(_, ne);
}
beforeOnUnload(_) {
this.kvDB.close();
}
onClose(_) {
this.kvDB.close();
}
getNewReplicator(_ = {}) {
if ({
...this.settings,
..._
}.remoteType == REMOTE_MINIO) return new LiveSyncJournalReplicator(this); else return new LiveSyncCouchDBReplicator(this);
}
async onInitializeDatabase(_) {
this.kvDB = await OpenKeyValueDatabase(_.dbname + "-livesync-kv");
this.replicator = this.getNewReplicator();
}
async onResetDatabase(_) {
this.kvDB.del("queued-files");
await this.kvDB.destroy();
this.kvDB = await OpenKeyValueDatabase(_.dbname + "-livesync-kv");
this.replicator = this.getNewReplicator();
}
getReplicator() {
return this.replicator;
}
getVaultName() {
var _;
return this.vaultName + ((null == (_ = this.settings) ? void 0 : _.additionalSuffixOfDatabaseName) ? "-" + this.settings.additionalSuffixOfDatabaseName : "");
}
isFlagFileExist(_) {
const ee = this.vaultAccess.getAbstractFileByPath(normalizePath(_));
if (null != ee && ee instanceof import_obsidian.TFile) return true; else return false;
}
async deleteFlagFile(_) {
try {
const ee = this.vaultAccess.getAbstractFileByPath(normalizePath(_));
if (null != ee && ee instanceof import_obsidian.TFile) await this.vaultAccess.delete(ee, true);
} catch (ee) {
Logger(`Could not delete ${_}`);
Logger(ee, LOG_LEVEL_VERBOSE);
}
}
async deleteRedFlag2() {
await this.deleteFlagFile(FLAGMD_REDFLAG2);
await this.deleteFlagFile(FLAGMD_REDFLAG2_HR);
}
async deleteRedFlag3() {
await this.deleteFlagFile(FLAGMD_REDFLAG3);
await this.deleteFlagFile(FLAGMD_REDFLAG3_HR);
}
showHistory(_, ee) {
new DocumentHistoryModal(this.app, this, _, ee).open();
}
async fileHistory() {
const _ = [];
for await (const ee of this.localDatabase.findAllDocs()) _.push({
id: ee._id,
path: this.getPath(ee),
dispPath: this.getPathWithoutPrefix(ee),
mtime: ee.mtime
});
_.sort(((_, ee) => ee.mtime - _.mtime));
const ee = _.map((_ => _.dispPath)), ne = await this.askSelectString("File to view History", ee);
if (ne) {
const ee = _.find((_ => _.dispPath == ne));
this.showHistory(ee.path, ee.id);
}
}
async pickFileForResolve() {
const _ = [];
for await (const ee of this.localDatabase.findAllDocs({
conflicts: true
})) if ("_conflicts" in ee) _.push({
id: ee._id,
path: this.getPath(ee),
dispPath: this.getPathWithoutPrefix(ee),
mtime: ee.mtime
});
_.sort(((_, ee) => ee.mtime - _.mtime));
const ee = _.map((_ => _.dispPath));
if (0 == ee.length) {
Logger("There are no conflicted documents", LOG_LEVEL_NOTICE);
return false;
}
const ne = await this.askSelectString("File to resolve conflict", ee);
if (ne) {
const ee = _.find((_ => _.dispPath == ne));
this.resolveConflicted(ee.path);
await this.conflictCheckQueue.waitForAllProcessed();
return true;
}
return false;
}
async resolveConflicted(_) {
if (isInternalMetadata(_)) this.addOnHiddenFileSync.queueConflictCheck(_); else if (isPluginMetadata(_)) await this.resolveConflictByNewerEntry(_); else if (isCustomisationSyncMetadata(_)) await this.resolveConflictByNewerEntry(_); else this.queueConflictCheck(_);
}
async collectDeletedFiles() {
const _ = this.settings.automaticallyDeleteMetadataOfDeletedFiles;
if (_ <= 0) return;
Logger("Checking expired file history");
const ee = Date.now() - 864e5 * _, ne = [];
for await (const _ of this.localDatabase.findAllDocs({
conflicts: true
})) if (isAnyNote(_)) if (_.deleted && _.mtime - ee < 0) ne.push({
path: this.getPath(_),
mtime: _.mtime,
ttl: (_.mtime - ee) / 1e3 / 86400,
doc: _
});
if (0 != ne.length) {
for (const _ of ne) {
Logger(`Deletion history expired: ${_.path}`);
const ee = _.doc;
ee._deleted = true;
await this.localDatabase.putRaw(ee);
}
Logger("Checking expired file history done");
} else {
Logger("There are no old documents");
Logger("Checking expired file history done");
}
}
getMinioJournalSyncClient() {
const _ = this.settings.accessKey, ee = this.settings.secretKey, ne = this.settings.bucket, ie = this.settings.region, re = this.settings.endpoint, se = this.settings.useCustomRequestHandler;
return new JournalSyncMinio(_, ee, re, ne, this.simpleStore, this, se, ie);
}
async resetRemoteBucket() {
const _ = this.getMinioJournalSyncClient();
await _.resetBucket();
}
async resetJournalSync() {
const _ = this.getMinioJournalSyncClient();
await _.resetCheckpointInfo();
}
async journalSendTest() {
const _ = this.getMinioJournalSyncClient();
await _.sendLocalJournal();
}
async journalFetchTest() {
const _ = this.getMinioJournalSyncClient();
await _.receiveRemoteJournal();
}
async journalSyncTest() {
const _ = this.getMinioJournalSyncClient();
await _.sync();
}
async onLayoutReady() {
this.registerFileWatchEvents();
if (this.localDatabase.isReady) if (this.settings.isConfigured) try {
if (this.isRedFlagRaised() || this.isRedFlag2Raised() || this.isRedFlag3Raised()) {
this.settings.batchSave = false;
this.addOnSetup.suspendAllSync();
this.addOnSetup.suspendExtraSync();
this.settings.suspendFileWatching = true;
await this.saveSettings();
if (this.isRedFlag2Raised()) {
Logger(`${FLAGMD_REDFLAG2} or ${FLAGMD_REDFLAG2_HR} has been detected! Self-hosted LiveSync suspends all sync and rebuild everything.`, LOG_LEVEL_NOTICE);
await this.addOnSetup.rebuildEverything();
await this.deleteRedFlag2();
if ("yes" == await this.askYesNo("Do you want to disable Suspend file watching and restart obsidian now?")) {
this.settings.suspendFileWatching = false;
await this.saveSettings();
this.performAppReload();
}
} else if (this.isRedFlag3Raised()) {
Logger(`${FLAGMD_REDFLAG3} or ${FLAGMD_REDFLAG3_HR} has been detected! Self-hosted LiveSync will discard the local database and fetch everything from the remote once again.`, LOG_LEVEL_NOTICE);
await this.addOnSetup.fetchLocal();
await this.deleteRedFlag3();
if (this.settings.suspendFileWatching) if ("yes" == await this.askYesNo("Do you want to disable Suspend file watching and restart obsidian now?")) {
this.settings.suspendFileWatching = false;
await this.saveSettings();
this.performAppReload();
}
} else {
this.settings.writeLogToTheFile = true;
await this.openDatabase();
Logger("The red flag is raised! The whole initialize steps are skipped, and any file changes are not captured.", LOG_LEVEL_NOTICE);
}
} else {
if (this.settings.suspendFileWatching) Logger("'Suspend file watching' turned on. Are you sure this is what you intended? Every modification on the vault will be ignored.", LOG_LEVEL_NOTICE);
if (this.settings.suspendParseReplicationResult) Logger("'Suspend database reflecting' turned on. Are you sure this is what you intended? Every replicated change will be postponed until disabling this option.", LOG_LEVEL_NOTICE);
if (!await this.initializeDatabase(false, false)) return false;
}
this.registerWatchEvents();
await this.realizeSettingSyncMode();
this.swapSaveCommand();
if (!this.settings.liveSync && this.settings.syncOnStart) this.replicator.openReplication(this.settings, false, false, false);
this.scanStat();
} catch (_) {
Logger("Error while loading Self-hosted LiveSync", LOG_LEVEL_NOTICE);
Logger(_, LOG_LEVEL_VERBOSE);
} else {
const _ = "Hello and welcome to Self-hosted LiveSync.\n\nYour device seems to **not be configured yet**. Please finish the setup and synchronise your vaults!\n\nClick anywhere to stop counting down.\n\n## At the first device\n- With Setup URI -> Use `Use the copied setup URI`. \n If you have configured it automatically, you should have one.\n- Without Setup URI -> Use `Setup wizard` in setting dialogue. **`Minimal setup` is recommended**.\n- What is the Setup URI? -> Do not worry! We have [some docs](https://github.com/vrtmrz/obsidian-livesync/blob/main/README.md#how-to-use) now. Please refer to them once.\n\n## At the subsequent device\n- With Setup URI -> Use `Use the copied setup URI`. \n If you do not have it yet, you can copy it on the first device.\n- Without Setup URI -> Use `Setup wizard` in setting dialogue, but **strongly recommends using setup URI**.\n", ee = "Open setting dialog", ne = "Use the copied setup URI", ie = "Dismiss", re = await confirmWithMessage(this, "Welcome to Self-hosted LiveSync", _, [ ne, ee, ie ], ie, 40);
if (re === ee) try {
this.openSetting();
} catch (_) {
Logger("Something went wrong on opening setting dialog, please open it manually", LOG_LEVEL_NOTICE);
} else if (re == ne) fireAndForget(this.addOnSetup.command_openSetupURI());
} else Logger("Something went wrong! The local database is not ready", LOG_LEVEL_NOTICE);
}
async scanStat() {
const _ = [];
Logger("Additional safety scan..", LOG_LEVEL_VERBOSE);
for await (const ee of this.localDatabase.findAllDocs({
conflicts: true
})) if ("_conflicts" in ee) _.push({
path: this.getPath(ee),
mtime: ee.mtime
});
if (_.length > 0) {
this.askInPopup("conflicting-detected-on-safety", 'Some files have been left conflicted! Press {HERE} to resolve them, or you can do it later by "Pick a file to resolve conflict', (_ => {
_.text = "HERE";
_.addEventListener("click", (() => {
this.performCommand("obsidian-livesync:livesync-all-conflictcheck");
}));
}));
Logger('Some files have been left conflicted! Please resolve them by "Pick a file to resolve conflict". The list is written in the log.', LOG_LEVEL_VERBOSE);
for (const ee of _) Logger(`Conflicted: ${ee.path}`);
} else Logger("There are no conflicted files", LOG_LEVEL_VERBOSE);
Logger("Additional safety scan done", LOG_LEVEL_VERBOSE);
}
async askEnableV2() {
const _ = "Keep v1";
return await confirmWithMessage(this, "binary and encryption", "Since v0.20.0, Self-hosted LiveSync uses a new format for binary files and encrypted things. In the new format, files are split at meaningful delimitations, increasing the effectiveness of deduplication.\nHowever, the new format lacks compatibility with LiveSync before v0.20.0 and related projects. Basically enabling V2 is recommended. but If you are using some related products, stay in a while, please!\nNote: We can always able to read V1 format. It will be progressively converted. And, we can change this toggle later.", [ "Enable v2", _ ], _, 40) == _;
}
addUIs() {
(0, import_obsidian.addIcon)("replicate", '\n \n \n \n \n ');
(0, import_obsidian.addIcon)("view-log", '\n \n \n ');
(0, import_obsidian.addIcon)("custom-sync", '\n \n ');
this.addRibbonIcon("replicate", "Replicate", (async () => {
await this.replicate(true);
})).addClass("livesync-ribbon-replicate");
this.addRibbonIcon("view-log", "Show log", (() => {
this.showView(VIEW_TYPE_LOG);
})).addClass("livesync-ribbon-showlog");
this.addRibbonIcon("custom-sync", "Show Customization sync", (() => {
this.addOnConfigSync.showPluginSyncModal();
})).addClass("livesync-ribbon-showcustom");
this.addCommand({
id: "view-log",
name: "Show log",
callback: () => {
this.showView(VIEW_TYPE_LOG);
}
});
this.addCommand({
id: "livesync-replicate",
name: "Replicate now",
callback: async () => {
await this.replicate();
}
});
this.addCommand({
id: "livesync-dump",
name: "Dump information of this doc ",
callback: () => {
const _ = this.getActiveFile();
if (_) this.localDatabase.getDBEntry(getPathFromTFile(_), {}, true, false);
}
});
this.addCommand({
id: "livesync-checkdoc-conflicted",
name: "Resolve if conflicted.",
editorCallback: (_, ee) => {
const ne = ee.file;
if (ne) this.queueConflictCheck(ne);
}
});
this.addCommand({
id: "livesync-toggle",
name: "Toggle LiveSync",
callback: async () => {
if (this.settings.liveSync) {
this.settings.liveSync = false;
Logger("LiveSync Disabled.", LOG_LEVEL_NOTICE);
} else {
this.settings.liveSync = true;
Logger("LiveSync Enabled.", LOG_LEVEL_NOTICE);
}
await this.realizeSettingSyncMode();
this.saveSettings();
}
});
this.addCommand({
id: "livesync-suspendall",
name: "Toggle All Sync.",
callback: async () => {
if (this.suspended) {
this.suspended = false;
Logger("Self-hosted LiveSync resumed", LOG_LEVEL_NOTICE);
} else {
this.suspended = true;
Logger("Self-hosted LiveSync suspended", LOG_LEVEL_NOTICE);
}
await this.realizeSettingSyncMode();
this.saveSettings();
}
});
this.addCommand({
id: "livesync-history",
name: "Show history",
callback: () => {
const _ = this.getActiveFile();
if (_) this.showHistory(_, void 0);
}
});
this.addCommand({
id: "livesync-scan-files",
name: "Scan storage and database again",
callback: async () => {
await this.syncAllFiles(true);
}
});
this.addCommand({
id: "livesync-filehistory",
name: "Pick a file to show history",
callback: () => {
this.fileHistory();
}
});
this.addCommand({
id: "livesync-conflictcheck",
name: "Pick a file to resolve conflict",
callback: () => {
this.pickFileForResolve();
}
});
this.addCommand({
id: "livesync-all-conflictcheck",
name: "Resolve all conflicted files",
callback: async () => {
for (;await this.pickFileForResolve(); ) ;
}
});
this.addCommand({
id: "livesync-runbatch",
name: "Run pended batch processes",
callback: async () => {
await this.applyBatchChange();
}
});
this.addCommand({
id: "livesync-abortsync",
name: "Abort synchronization immediately",
callback: () => {
this.replicator.terminateSync();
}
});
this.addCommand({
id: "livesync-global-history",
name: "Show vault history",
callback: () => {
this.showGlobalHistory();
}
});
this.addCommand({
id: "livesync-export-config",
name: "Write setting markdown manually",
checkCallback: _ => {
if (_) return "" != this.settings.settingSyncFile;
this.saveSettingData();
}
});
this.addCommand({
id: "livesync-import-config",
name: "Parse setting file",
editorCheckCallback: (_, ee, ne) => {
if (_) {
const _ = ee.getValue();
return "" != this.extractSettingFromWholeText(_).body;
}
if (ne.file) this.checkAndApplySettingFromMarkdown(ne.file.path, false);
}
});
this.registerView(VIEW_TYPE_GLOBAL_HISTORY, (_ => new GlobalHistoryView(_, this)));
this.registerView(VIEW_TYPE_LOG, (_ => new LogPaneView(_, this)));
}
async onload() {
logStore.pipeTo(new QueueProcessor((_ => _.forEach((_ => this.addLog(_.message, _.level, _.key)))), {
suspended: false,
batchSize: 20,
concurrentLimit: 1,
delay: 0
})).startPipeline();
Logger("loading plugin");
__onMissingTranslation((() => {}));
this.settingTab = new ObsidianLiveSyncSettingTab(this.app, this);
this.addSettingTab(this.settingTab);
this.addUIs();
const _ = "0.23.14", ee = "0.23.14";
this.manifestVersion = _;
this.packageVersion = ee;
Logger($f`Self-hosted LiveSync${" v"}${_} ${ee}`);
await this.loadSettings();
const ne = "obsidian-live-sync-ver" + this.getVaultName(), ie = localStorage.getItem(ne);
this.observeForLogs();
if (this.settings.showStatusOnStatusbar) {
this.statusBar = this.addStatusBarItem();
this.statusBar.addClass("syncstatusbar");
}
if (~~(versionNumberString2Number(_) / 1e3) > this.settings.lastReadUpdates && this.settings.isConfigured) Logger($f`Self-hosted LiveSync has undergone a major upgrade. Please open the setting dialog, and check the information pane.`, LOG_LEVEL_NOTICE);
if (this.isMobile) this.settings.disableRequestURI = true;
if (ie && Number(ie) < VER) {
this.settings.liveSync = false;
this.settings.syncOnSave = false;
this.settings.syncOnEditorSave = false;
this.settings.syncOnStart = false;
this.settings.syncOnFileOpen = false;
this.settings.syncAfterMerge = false;
this.settings.periodicReplication = false;
this.settings.versionUpFlash = $f`Self-hosted LiveSync has been upgraded and some behaviors have changed incompatibly. All automatic synchronization is now disabled temporary. Ensure that other devices are also upgraded, and enable synchronization again.`;
this.saveSettings();
}
localStorage.setItem(ne, `${VER}`);
await this.openDatabase();
this.watchWorkspaceOpen = this.watchWorkspaceOpen.bind(this);
this.watchEditorChange = this.watchEditorChange.bind(this);
this.watchWindowVisibility = this.watchWindowVisibility.bind(this);
this.watchOnline = this.watchOnline.bind(this);
this.realizeSettingSyncMode = this.realizeSettingSyncMode.bind(this);
this.parseReplicationResult = this.parseReplicationResult.bind(this);
this.loadQueuedFiles = this.loadQueuedFiles.bind(this);
await Promise.all(this.addOns.map((_ => _.onload())));
this.app.workspace.onLayoutReady(this.onLayoutReady.bind(this));
}
async showView(_) {
const ee = this.app.workspace.getLeavesOfType(_);
if (0 == ee.length) await this.app.workspace.getLeaf(true).setViewState({
type: _,
active: true
}); else ee[0].setViewState({
type: _,
active: true
});
if (ee.length > 0) this.app.workspace.revealLeaf(ee[0]);
}
showGlobalHistory() {
this.showView(VIEW_TYPE_GLOBAL_HISTORY);
}
onunload() {
var _;
terminateWorker();
cancelAllPeriodicTask();
cancelAllTasks();
stopAllRunningProcessors();
this._unloaded = true;
for (const _ of this.addOns) _.onunload();
if (null != this.localDatabase) this.localDatabase.onunload();
null == (_ = this.periodicSyncProcessor) || _.disable();
if (null != this.localDatabase) {
this.replicator.closeReplication();
this.localDatabase.close();
}
Logger($f`unloading plugin`);
}
async openDatabase() {
if (null != this.localDatabase) await this.localDatabase.close();
const _ = this.getVaultName();
Logger($f`Waiting for ready...`);
this.localDatabase = new LiveSyncLocalDB(_, this);
initializeStores(_);
return await this.localDatabase.initializeDatabase();
}
getPassphrase(_) {
const ee = {
"": () => Promise.resolve("*"),
LOCALSTORAGE: () => {
var _;
return Promise.resolve(null != (_ = localStorage.getItem("ls-setting-passphrase")) ? _ : false);
},
ASK_AT_LAUNCH: () => askString(this.app, "Passphrase", "passphrase", "")
}, ne = _.configPassphraseStore;
return (ne in ee ? ee[ne] : ee[""])();
}
async decryptConfigurationItem(_, ee) {
const ne = await tryDecrypt(_, ee + SALT_OF_PASSPHRASE, false);
if (ne) {
this.usedPassphrase = ee;
return ne;
}
return false;
}
tryDecodeJson(_) {
try {
if (!_) return false; else return JSON.parse(_);
} catch (_) {
return false;
}
}
async encryptConfigurationItem(_, ee) {
if ("" != this.usedPassphrase) return await encrypt(_, this.usedPassphrase + SALT_OF_PASSPHRASE, false);
const ne = await this.getPassphrase(ee);
if (false === ne) {
Logger("Could not determine passphrase to save data.json! You probably make the configuration sure again!", LOG_LEVEL_URGENT);
return "";
}
const ie = await encrypt(_, ne + SALT_OF_PASSPHRASE, false);
if (ie) {
this.usedPassphrase = ne;
return ie;
}
return "";
}
async loadSettings() {
const _ = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
if ("undefined" == typeof _.isConfigured) if (JSON.stringify(_) !== JSON.stringify(DEFAULT_SETTINGS)) _.isConfigured = true; else {
_.additionalSuffixOfDatabaseName = this.appId;
_.isConfigured = false;
}
const ee = await this.getPassphrase(_);
if (false === ee) Logger("Could not determine passphrase for reading data.json! DO NOT synchronize with the remote before making sure your configuration is!", LOG_LEVEL_URGENT); else {
if (_.encryptedCouchDBConnection) {
const ne = [ "couchDB_URI", "couchDB_USER", "couchDB_PASSWORD", "couchDB_DBNAME", "accessKey", "bucket", "endpoint", "region", "secretKey" ], ie = this.tryDecodeJson(await this.decryptConfigurationItem(_.encryptedCouchDBConnection, ee));
if (ie) {
for (const ee of ne) if (ee in ie) _[ee] = ie[ee];
} else {
Logger("Could not decrypt passphrase for reading data.json! DO NOT synchronize with the remote before making sure your configuration is!", LOG_LEVEL_URGENT);
for (const ee of ne) _[ee] = "";
}
}
if (_.encrypt && _.encryptedPassphrase) {
const ne = _.encryptedPassphrase, ie = await this.decryptConfigurationItem(ne, ee);
if (ie) _.passphrase = ie; else {
Logger("Could not decrypt passphrase for reading data.json! DO NOT synchronize with the remote before making sure your configuration is!", LOG_LEVEL_URGENT);
_.passphrase = "";
}
}
}
this.settings = _;
setLang(this.settings.displayLanguage);
if ("workingEncrypt" in this.settings) delete this.settings.workingEncrypt;
if ("workingPassphrase" in this.settings) delete this.settings.workingPassphrase;
this.settings.disableRequestURI = true;
this.settings.gcDelay = 0;
this.settings.useHistory = true;
const ne = "obsidian-live-sync-vaultanddevicename-" + this.getVaultName();
if ("" != this.settings.deviceAndVaultName) if (!localStorage.getItem(ne)) {
this.deviceAndVaultName = this.settings.deviceAndVaultName;
localStorage.setItem(ne, this.deviceAndVaultName);
this.settings.deviceAndVaultName = "";
}
if (isCloudantURI(this.settings.couchDB_URI) && 0 != this.settings.customChunkSize) {
Logger("Configuration verification founds problems with your configuration. This has been fixed automatically. But you may already have data that cannot be synchronised. If this is the case, please rebuild everything.", LOG_LEVEL_NOTICE);
this.settings.customChunkSize = 0;
}
this.deviceAndVaultName = localStorage.getItem(ne) || "";
this.ignoreFiles = this.settings.ignoreFiles.split(",").map((_ => _.trim()));
this.settingTab.requestReload();
}
saveDeviceAndVaultName() {
const _ = "obsidian-live-sync-vaultanddevicename-" + this.getVaultName();
localStorage.setItem(_, this.deviceAndVaultName || "");
}
async saveSettingData() {
this.saveDeviceAndVaultName();
const _ = {
...this.settings
};
_.deviceAndVaultName = "";
if ("" == this.usedPassphrase && !await this.getPassphrase(_)) Logger("Could not determine passphrase for saving data.json! Our data.json have insecure items!", LOG_LEVEL_NOTICE); else {
if ("" != _.couchDB_PASSWORD || "" != _.couchDB_URI || "" != _.couchDB_USER || _.couchDB_DBNAME) {
const ee = {
couchDB_DBNAME: _.couchDB_DBNAME,
couchDB_PASSWORD: _.couchDB_PASSWORD,
couchDB_URI: _.couchDB_URI,
couchDB_USER: _.couchDB_USER,
accessKey: _.accessKey,
bucket: _.bucket,
endpoint: _.endpoint,
region: _.region,
secretKey: _.secretKey,
useCustomRequestHandler: _.useCustomRequestHandler
};
_.encryptedCouchDBConnection = await this.encryptConfigurationItem(JSON.stringify(ee), _);
_.couchDB_PASSWORD = "";
_.couchDB_DBNAME = "";
_.couchDB_URI = "";
_.couchDB_USER = "";
_.accessKey = "";
_.bucket = "";
_.region = "";
_.secretKey = "";
_.endpoint = "";
}
if (_.encrypt && "" != _.passphrase) {
_.encryptedPassphrase = await this.encryptConfigurationItem(_.passphrase, _);
_.passphrase = "";
}
}
await this.saveData(_);
this.localDatabase.settings = this.settings;
setLang(this.settings.displayLanguage);
this.settingTab.requestReload();
this.ignoreFiles = this.settings.ignoreFiles.split(",").map((_ => _.trim()));
if ("" != this.settings.settingSyncFile) fireAndForget((() => this.saveSettingToMarkdown(this.settings.settingSyncFile)));
}
extractSettingFromWholeText(_) {
if (-1 === _.indexOf(SETTING_HEADER)) return {
preamble: _,
body: "",
postscript: ""
};
const ee = _.indexOf(SETTING_HEADER), ne = -1 == ee ? _.length : ee, ie = -1 == ee ? _.length : _.indexOf(SETTING_FOOTER, ne), re = -1 == ie ? _.length : ie, se = _.substring(ne + SETTING_HEADER.length, re);
return {
preamble: _.substring(0, ne),
body: se,
postscript: _.substring(re + SETTING_FOOTER.length + 1)
};
}
async parseSettingFromMarkdown(_, ee) {
const ne = this.vaultAccess.getAbstractFileByPath(_);
if (!(ne instanceof import_obsidian.TFile)) return {
preamble: "",
body: "",
postscript: ""
};
if (ee) return this.extractSettingFromWholeText(ee);
const ie = null != ee ? ee : await this.vaultAccess.vaultRead(ne);
return this.extractSettingFromWholeText(ie);
}
async checkAndApplySettingFromMarkdown(_, ee) {
if (ee && !this.settings.notifyAllSettingSyncFile) if (!this.settings.settingSyncFile || this.settings.settingSyncFile != _) {
Logger(`Setting file (${_}) is not matched to the current configuration. skipped.`, LOG_LEVEL_DEBUG);
return;
}
const {body: ne} = await this.parseSettingFromMarkdown(_);
let ie = {};
try {
ie = (0, import_obsidian.parseYaml)(ne);
} catch (_) {
Logger("Could not parse YAML", LOG_LEVEL_NOTICE);
Logger(_, LOG_LEVEL_VERBOSE);
return;
}
if ("settingSyncFile" in ie && ie.settingSyncFile != _) {
Logger("This setting file seems to backed up one. Please fix the filename or settingSyncFile value.", ee ? LOG_LEVEL_INFO : LOG_LEVEL_NOTICE);
return;
}
let re = {
...DEFAULT_SETTINGS
};
re = {
...re,
...ie
};
if (!(null == re ? void 0 : re.writeCredentialsForSettingSync)) {
re.couchDB_USER = this.settings.couchDB_USER;
re.couchDB_PASSWORD = this.settings.couchDB_PASSWORD;
re.passphrase = this.settings.passphrase;
}
if (!isObjectDifferent(this.generateSettingForMarkdown(this.settings, re.writeCredentialsForSettingSync), this.generateSettingForMarkdown(re))) {
Logger("Setting markdown has been detected, but not changed.", ee ? LOG_LEVEL_INFO : LOG_LEVEL_NOTICE);
return;
}
const se = this.settings.settingSyncFile != _ ? " (This is not-active file)" : "";
this.askInPopup("apply-setting-from-md", `Setting markdown ${_}${se} has been detected. Apply this from {HERE}.`, (_ => {
_.text = "HERE";
_.addEventListener("click", (async () => {
const _ = "Apply settings", ee = "Apply settings and restart obsidian", ne = "Apply settings and restart obsidian with red_flag_rebuild.md", ie = "Apply settings and restart obsidian with red_flag_fetch.md", se = await this.askSelectString("Ready for apply the setting.", [ ee, _, ie, ne, "Cancel" ]);
if (se == _ || se == ee || se == ne || se == ie) {
this.settings = re;
await this.saveSettingData();
if (se == _) {
Logger("Loaded settings have been applied!", LOG_LEVEL_NOTICE);
return;
}
if (se == ne) await this.vaultAccess.vaultCreate(FLAGMD_REDFLAG2_HR, "");
if (se == ie) await this.vaultAccess.vaultCreate(FLAGMD_REDFLAG3_HR, "");
this.performAppReload();
}
}));
}));
}
generateSettingForMarkdown(_, ee) {
const ne = {
..._ ? _ : this.settings
};
delete ne.encryptedCouchDBConnection;
delete ne.encryptedPassphrase;
if (!ne.writeCredentialsForSettingSync && !ee) {
delete ne.couchDB_USER;
delete ne.couchDB_PASSWORD;
delete ne.passphrase;
}
return ne;
}
async saveSettingToMarkdown(_) {
const ee = this.generateSettingForMarkdown();
let ne = this.vaultAccess.getAbstractFileByPath(_);
if (!ne) {
await this.vaultAccess.ensureDirectory(_);
const ee = 'This file contains Self-hosted LiveSync settings as YAML.\nExcept for the `livesync-setting` code block, we can add a note for free.\n\nIf the name of this file matches the value of the "settingSyncFile" setting inside the `livesync-setting` block, LiveSync will tell us whenever the settings change. We can decide to accept or decline the remote setting. (In other words, we can back up this file by renaming it to another name).\n\nWe can perform a command in this file.\n- `Parse setting file` : load the setting from the file.\n\n**Note** Please handle it with all of your care if you have configured to write credentials in.\n\n\n';
ne = await this.vaultAccess.vaultCreate(_, ee + SETTING_HEADER + "\n" + SETTING_FOOTER);
}
if (!(ne instanceof import_obsidian.TFile)) {
Logger(`Markdown Setting: ${_} already exists as a folder`, LOG_LEVEL_NOTICE);
return;
}
const ie = await this.vaultAccess.vaultRead(ne), {preamble: re, body: se, postscript: oe} = this.extractSettingFromWholeText(ie), le = (0,
import_obsidian.stringifyYaml)(ee);
if (le == se) Logger("Markdown setting: Nothing had been changed", LOG_LEVEL_VERBOSE); else {
await this.vaultAccess.vaultModify(ne, re + SETTING_HEADER + le + SETTING_FOOTER + oe);
Logger(`Markdown setting: ${_} has been updated!`, LOG_LEVEL_VERBOSE);
}
}
async saveSettings() {
await this.saveSettingData();
fireAndForget((() => this.realizeSettingSyncMode()));
}
registerFileWatchEvents() {
this.vaultManager.beginWatch();
this.registerEvent(this.app.workspace.on("editor-change", this.watchEditorChange));
}
swapSaveCommand() {
var _, ee;
Logger("Modifying callback of the save command", LOG_LEVEL_VERBOSE);
const ne = null == (ee = null == (_ = this.app.commands) ? void 0 : _.commands) ? void 0 : ee["editor:save-file"], ie = null == ne ? void 0 : ne.callback;
if ("function" == typeof ie) {
this._initialCallback = ie;
ne.callback = () => {
scheduleTask("syncOnEditorSave", 250, (() => {
if (this._unloaded) {
Logger("Unload and remove the handler.", LOG_LEVEL_VERBOSE);
ne.callback = this._initialCallback;
this._initialCallback = void 0;
} else if (this.settings.syncOnEditorSave) {
Logger("Sync on Editor Save.", LOG_LEVEL_VERBOSE);
this.replicate();
}
}));
ie();
};
}
const re = this;
window.CodeMirrorAdapter.commands.save = () => {
re.performCommand("editor:save-file");
};
}
registerWatchEvents() {
this.registerEvent(this.app.workspace.on("file-open", this.watchWorkspaceOpen));
this.registerDomEvent(document, "visibilitychange", this.watchWindowVisibility);
this.registerDomEvent(window, "focus", (() => this.setHasFocus(true)));
this.registerDomEvent(window, "blur", (() => this.setHasFocus(false)));
this.registerDomEvent(window, "online", this.watchOnline);
this.registerDomEvent(window, "offline", this.watchOnline);
}
watchOnline() {
scheduleTask("watch-online", 500, (() => fireAndForget((() => this.watchOnlineAsync()))));
}
async watchOnlineAsync() {
if (navigator.onLine && this.localDatabase.needScanning) {
this.localDatabase.needScanning = false;
await this.syncAllFiles();
}
}
setHasFocus(_) {
this.hasFocus = _;
this.watchWindowVisibility();
}
watchWindowVisibility() {
scheduleTask("watch-window-visibility", 100, (() => fireAndForget((() => this.watchWindowVisibilityAsync()))));
}
async watchWindowVisibilityAsync() {
var _;
if (this.settings.suspendFileWatching) return;
if (!this.settings.isConfigured) return;
if (!this.isReady) return;
if (this.isLastHidden && !this.hasFocus) return;
const ee = document.hidden;
if (this.isLastHidden !== ee) {
this.isLastHidden = ee;
await this.applyBatchChange();
if (ee) {
this.replicator.closeReplication();
null == (_ = this.periodicSyncProcessor) || _.disable();
} else {
if (this.suspended) return;
if (!this.hasFocus) return;
await Promise.all(this.addOns.map((_ => _.onResume())));
if (this.settings.remoteType == REMOTE_COUCHDB) if (this.settings.liveSync) this.replicator.openReplication(this.settings, true, false, false);
if (!this.settings.liveSync && this.settings.syncOnStart) this.replicator.openReplication(this.settings, false, false, false);
this.periodicSyncProcessor.enable(this.settings.periodicReplication ? 1e3 * this.settings.periodicReplicationInterval : 0);
}
}
}
cancelRelativeEvent(_) {
this.vaultManager.cancelQueue(_.key);
}
async handleFileEvent(_) {
const ee = _.args.file, ne = `handleFile:${ee.path}`;
return await serialized(ne, (async () => {
const ne = `file-last-proc-${_.type}-${ee.path}`, ie = Number(await this.kvDB.get(ne) || 0);
let re = ee.mtime;
if ("DELETE" == _.type) {
await this.deleteFromDBbyPath(ee.path);
re = ee.mtime - 1;
const _ = `file-last-proc-CREATE-${ee.path}`, ne = `file-last-proc-CHANGED-${ee.path}`;
await this.kvDB.set(_, re);
await this.kvDB.set(ne, re);
} else if ("INTERNAL" == _.type) {
await this.addOnHiddenFileSync.watchVaultRawEventsAsync(ee.path);
await this.addOnConfigSync.watchVaultRawEventsAsync(ee.path);
} else {
const ne = this.vaultAccess.getAbstractFileByPath(ee.path);
if (!(ne instanceof import_obsidian.TFile)) {
Logger(`Target file was not found: ${ee.path}`, LOG_LEVEL_INFO);
return;
}
if (ee.mtime == ie) {
Logger(`File has been already scanned on ${_.type}, skip: ${ee.path}`, LOG_LEVEL_VERBOSE);
return;
}
if ("CREATE" == _.type || "CHANGED" == _.type) {
fireAndForget((() => this.checkAndApplySettingFromMarkdown(_.args.file.path, true)));
const ie = `file-last-proc-DELETED-${ee.path}`;
await this.kvDB.set(ie, re);
if (!await this.updateIntoDB(ne, void 0)) {
Logger(`STORAGE -> DB: failed, cancel the relative operations: ${ne.path}`, LOG_LEVEL_INFO);
this.cancelRelativeEvent(_);
return;
}
}
if ("RENAME" == _.type) await this.watchVaultRenameAsync(ne, _.args.oldPath);
}
await this.kvDB.set(ne, re);
}));
}
watchWorkspaceOpen(_) {
if (!this.settings.suspendFileWatching) if (this.settings.isConfigured) if (this.isReady) if (_) scheduleTask("watch-workspace-open", 500, (() => fireAndForget((() => this.watchWorkspaceOpenAsync(_)))));
}
flushFileEventQueue() {
return this.vaultManager.flushQueue();
}
watchEditorChange(_, ee) {
if (!("path" in ee)) return;
if (!this.shouldBatchSave) return;
const ne = null == ee ? void 0 : ee.file;
if (!ne) return;
if (!this.vaultManager.isWaiting(ne.path)) return;
const ie = {
type: "CHANGED",
file: ne,
cachedData: null == ee ? void 0 : ee.data
};
this.vaultManager.appendQueue([ ie ]);
}
async watchWorkspaceOpenAsync(_) {
if (!this.settings.suspendFileWatching) if (this.settings.isConfigured) if (this.isReady) {
await this.applyBatchChange();
if (null != _) {
if (this.settings.syncOnFileOpen && !this.suspended) await this.replicate();
this.queueConflictCheck(_);
}
}
}
async applyBatchChange() {
if (this.settings.batchSave && !this.settings.liveSync) return await this.flushFileEventQueue();
}
getFilePath(_) {
if (_ instanceof import_obsidian.TFolder) if (_.isRoot()) return ""; else return this.getFilePath(_.parent) + "/" + _.name;
if (_ instanceof import_obsidian.TFile) return this.getFilePath(_.parent) + "/" + _.name; else return this.getFilePath(_.parent) + "/" + _.name;
}
async watchVaultRenameAsync(_, ee, ne) {
Logger(`${ee} renamed to ${_.path}`, LOG_LEVEL_VERBOSE);
if (_ instanceof import_obsidian.TFile) try {
if (await this.updateIntoDB(_, ne)) await this.deleteFromDBbyPath(ee); else Logger(`Could not save new file: ${_.path} `, LOG_LEVEL_NOTICE);
} catch (_) {
Logger(_);
}
}
async addLog(_, ee = LOG_LEVEL_INFO, ne = "") {
var ie, re, se;
if (ee == LOG_LEVEL_DEBUG && !isDebug) return;
if (ee < LOG_LEVEL_INFO && this.settings && this.settings.lessInformationInLog) return;
if (this.settings && !this.settings.showVerboseLog && ee == LOG_LEVEL_VERBOSE) return;
const oe = this.getVaultName(), le = new Date, ue = le.toLocaleString(), de = "string" == typeof _ ? _ : _ instanceof Error ? `${_.name}:${_.message}` : JSON.stringify(_, null, 2);
if (_ instanceof Error) console.dir(_.stack);
const fe = ue + "->" + de;
console.log(oe + ":" + fe);
if (!(null == (ie = this.settings) ? void 0 : ie.showOnlyIconsOnEditor)) this.statusLog.value = de;
if (null == (re = this.settings) ? void 0 : re.writeLogToTheFile) {
const _ = le.toISOString().split("T")[0], ee = `${PREFIXMD_LOGFILE}${_}.md`;
if (!this.vaultAccess.getAbstractFileByPath(normalizePath(ee))) this.vaultAccess.adapterAppend(normalizePath(ee), "```\n");
this.vaultAccess.adapterAppend(normalizePath(ee), oe + ":" + fe + "\n");
}
recentLogProcessor.enqueue(fe);
if (ee >= LOG_LEVEL_NOTICE) {
if (!ne) ne = de;
if (ne in this.notifies) {
if (!(null == (se = this.notifies[ne].notice.noticeEl) ? void 0 : se.isShown())) this.notifies[ne].notice = new import_obsidian.Notice(de, 0);
cancelTask(`notify-${ne}`);
if (ne == de) {
this.notifies[ne].count++;
this.notifies[ne].notice.setMessage(`(${this.notifies[ne].count}):${de}`);
} else this.notifies[ne].notice.setMessage(`${de}`);
} else {
const _ = new import_obsidian.Notice(de, 0);
this.notifies[ne] = {
count: 0,
notice: _
};
}
scheduleTask(`notify-${ne}`, 5e3, (() => {
const _ = this.notifies[ne].notice;
delete this.notifies[ne];
try {
_.hide();
} catch (_) {}
}));
}
}
async processEntryDoc(_, ee, ne) {
const ie = null == ee ? "create" : "modify", re = this.getPath(_);
if (shouldBeIgnored(re)) return;
if (!await this.isTargetFile(re)) return;
const se = await this.localDatabase.getDBEntry(re, {
conflicts: true
}), oe = `STORAGE <- DB (${ie}${ne ? ",force" : ""},${se ? null == se ? void 0 : se.datatype : "--"}) `;
if (se && se._conflicts) if (this.settings.writeDocumentsIfConflicted) {
Logger(`Processing: ${re}: Conflicted revision has been deleted, but there were more conflicts. `, LOG_LEVEL_INFO);
await this.processEntryDoc(_, ee, true);
return;
} else if (true != ne) {
Logger(`Processing: ${re}: Conflicted revision has been deleted, but there were more conflicts...`);
this.queueConflictCheck(re);
return;
}
if (_._deleted || _.deleted || false === se) {
if (!ee) {
Logger(`delete skipped: ${re} :Already not exist on storage`, LOG_LEVEL_VERBOSE);
return;
}
if (ee.path != re) {
Logger(`delete skipped: ${re} :Not exactly matched`, LOG_LEVEL_VERBOSE);
return;
}
if (false === se) await this.deleteVaultItem(ee); else await this.pullFile(re, void 0, true);
return;
}
const le = compareFileFreshness(ee, _), ue = se;
if (!isAnyNote(ue)) {
Logger(oe + "ERROR, Invalid type: " + re + "(" + (null == ue ? void 0 : ue.type) || "type missing)", LOG_LEVEL_NOTICE);
return;
}
if (!ne && (le == BASE_IS_NEW || le == EVEN)) return;
if (!isValidPath(re)) {
Logger(oe + "ERROR, invalid path: " + re, LOG_LEVEL_NOTICE);
return;
}
const de = readContent(ue);
await this.vaultAccess.ensureDirectory(re);
try {
let _, ne = true;
if (!ee) {
const ee = normalizePath(re);
await this.vaultAccess.vaultCreate(ee, de, {
ctime: ue.ctime,
mtime: ue.mtime
});
_ = this.vaultAccess.getAbstractFileByPath(ee);
} else {
ne = await this.vaultAccess.vaultModify(ee, de, {
ctime: ue.ctime,
mtime: ue.mtime
});
_ = this.vaultAccess.getAbstractFileByPath(getPathFromTFile(ee));
}
if (ne) {
Logger(oe + re);
this.vaultAccess.touch(_);
this.vaultAccess.trigger(ie, _);
} else Logger(oe + "Skipped, the file is the same: " + re, LOG_LEVEL_VERBOSE);
} catch (_) {
Logger(oe + "ERROR, Could not write: " + re, LOG_LEVEL_NOTICE);
Logger(_, LOG_LEVEL_VERBOSE);
}
}
async deleteVaultItem(_) {
if (_ instanceof import_obsidian.TFile) if (!await this.isTargetFile(_)) return;
const ee = _.parent;
if (this.settings.trashInsteadDelete) await this.vaultAccess.trash(_, false); else await this.vaultAccess.delete(_, true);
Logger(`xxx <- STORAGE (deleted) ${_.path}`);
if (ee) {
Logger(`files: ${ee.children.length}`);
if (0 == ee.children.length) if (!this.settings.doNotDeleteFolder) {
Logger(`All files under the parent directory (${ee.path}) have been deleted, so delete this one.`);
await this.deleteVaultItem(ee);
}
}
}
queueConflictCheck(_) {
const ee = _ instanceof import_obsidian.TFile ? getPathFromTFile(_) : _;
if (this.settings.checkConflictOnlyOnOpen) {
const ne = this.getActiveFile();
if (ne && ne.path != ee) {
Logger(`${_} is conflicted, merging process has been postponed.`, LOG_LEVEL_NOTICE);
return;
}
}
this.conflictCheckQueue.enqueue(ee);
}
saveQueuedFiles() {
this._saveQueuedFiles();
}
async loadQueuedFiles() {
var _;
if (this.settings.suspendParseReplicationResult) return;
if (!this.settings.isConfigured) return;
const ee = arrayToChunkedArray([ ...new Set(null != (_ = await this.kvDB.get("queued-files")) ? _ : []) ], 100);
for await (const _ of ee) {
const ee = await this.localDatabase.allDocsRaw({
keys: _,
include_docs: true,
limit: 100
}), ne = ee.rows.filter((_ => _.doc)).map((_ => _.doc)), ie = ee.rows.filter((_ => !_.doc && !_.value.deleted));
if (ie.length > 0) {
Logger("Some queued processes were not resurrected");
Logger(JSON.stringify(ie), LOG_LEVEL_VERBOSE);
}
this.replicationResultProcessor.enqueueAll(ne);
await this.replicationResultProcessor.waitForAllProcessed();
}
}
parseReplicationResult(_) {
if (this.settings.suspendParseReplicationResult && !this.replicationResultProcessor.isSuspended) this.replicationResultProcessor.suspend();
this.replicationResultProcessor.enqueueAll(_);
if (!this.settings.suspendParseReplicationResult && this.replicationResultProcessor.isSuspended) this.replicationResultProcessor.resume();
}
async realizeSettingSyncMode() {
var _;
this.replicator.closeReplication();
null == (_ = this.periodicSyncProcessor) || _.disable();
this.localDatabase.refreshSettings();
await this.applyBatchChange();
await Promise.all(this.addOns.map((_ => _.realizeSettingSyncMode())));
if (this.suspended) return;
await Promise.all(this.addOns.map((_ => _.onResume())));
if (this.settings.remoteType == REMOTE_COUCHDB) if (this.settings.liveSync) this.replicator.openReplication(this.settings, true, false, false);
const ee = activeDocument.querySelector(".livesync-ribbon-showcustom");
null == ee || ee.toggleClass("sls-hidden", !this.settings.usePluginSync);
this.periodicSyncProcessor.enable(this.settings.periodicReplication ? 1e3 * this.settings.periodicReplicationInterval : 0);
}
observeForLogs() {
const _ = " ".repeat(10);
function padLeftSpComputed(ee, ne) {
const ie = reactiveSource("");
let re, se = 1;
ee.onChanged((ee => {
const oe = ee.value, le = `${Math.abs(oe)}`.length + 1;
se = se < le ? le : se;
if (re) clearTimeout(re);
if (0 == oe) re = setTimeout((() => {
ie.value = "";
se = 1;
}), 3e3);
ie.value = ` ${ne}${`${_}${oe}`.slice(-se)}`;
}));
return computed((() => ie.value));
}
const ee = padLeftSpComputed(this.replicationResultCount, "📥"), ne = padLeftSpComputed(this.databaseQueueCount, "📄"), ie = padLeftSpComputed(this.storageApplyingCount, "💾"), re = padLeftSpComputed(collectingChunks, "🧩"), se = padLeftSpComputed(pluginScanningCount, "🔌"), oe = padLeftSpComputed(this.conflictProcessQueueCount, "🔩"), le = padLeftSpComputed(reactive((() => hiddenFilesEventCount.value + hiddenFilesProcessingCount.value)), "⚙️"), ue = reactive((() => `${ee()}${ne()}${ie()}${re()}${se()}${le()}${oe()}`)), de = computed((() => 0 != this.requestCount.value - this.responseCount.value ? "📲 " : "")), fe = computed((() => {
const _ = this.replicationStat.value, ee = _.sent, ne = _.arrived, ie = _.maxPullSeq, re = _.maxPushSeq, se = _.lastSyncPullSeq, oe = _.lastSyncPushSeq;
let le = "", ue = "", de = "";
const fe = {
CONNECTED: "⚡",
JOURNAL_SEND: "📦↑",
JOURNAL_RECEIVE: "📦↓"
};
switch (_.syncStatus) {
case "CLOSED":
case "COMPLETED":
case "NOT_CONNECTED":
de = "⏹";
break;
case "STARTED":
de = "🌀";
break;
case "PAUSED":
de = "💤";
break;
case "CONNECTED":
case "JOURNAL_SEND":
case "JOURNAL_RECEIVE":
de = fe[_.syncStatus] || "⚡";
le = 0 == oe ? "" : oe >= re ? " (LIVE)" : ` (${re - oe})`;
ue = 0 == se ? "" : se >= ie ? " (LIVE)" : ` (${ie - se})`;
break;
case "ERRORED":
de = "⚠";
break;
default:
de = "?";
}
return {
w: de,
sent: ee,
pushLast: le,
arrived: ne,
pullLast: ue
};
})), he = padLeftSpComputed(this.vaultManager.processing, "⏳"), pe = padLeftSpComputed(this.vaultManager.totalQueued, "🛫"), ge = padLeftSpComputed(this.vaultManager.batched, "📬"), me = computed((() => `${he()}${pe()}${ge()}`)), ye = computed((() => {
const {w: _, sent: ee, pushLast: ne, arrived: ie, pullLast: re} = fe(), se = ue.value, oe = me();
return {
message: `${de()}Sync: ${_} ↑ ${ee}${ne} ↓ ${ie}${re}${oe}${se}`
};
})), ve = reactive((() => {
const _ = this.isReloadingScheduled ? "WARNING! RESTARTING OBSIDIAN IS SCHEDULED!\n" : "", {message: ee} = ye();
return {
message: ee,
status: _ + this.statusLog.value
};
})), Se = throttle((_ => {
const ee = _;
this.applyStatusBarText(ee.message, ee.status);
}), 20);
ve.onChanged((_ => Se(_.value)));
}
applyStatusBarText(_, ee) {
var ne;
const ie = _.replace(/\n/g, "\\A "), re = ee.replace(/\n/g, "\\A ");
null == (ne = this.statusBar) || ne.setText(ie.split("\n")[0]);
if (this.settings.showStatusOnEditor) activeDocument.documentElement.style.setProperty("--sls-log-text", "'" + ie + "\\A " + re + "'");
scheduleTask("log-hide", 3e3, (() => {
this.statusLog.value = "";
}));
}
async askResolvingMismatchedTweaks() {
if (!this.replicator.tweakSettingsMismatched) return "OK";
const _ = this.replicator.mismatchedTweakValues.map((_ => extractObject(TweakValuesShouldMatchedTemplate, _))), ee = Object.entries(TweakValuesShouldMatchedTemplate);
let ne = `| Value name | Ours | ${_.map(((_, ee) => `Remote ${ee + 1} |`)).join("")}\n|: --- |: --- :${"|: --- :".repeat(_.length)}|\n`;
for (const ie of ee) {
const ee = ie[0], re = _.map((_ => _[ee]));
ne += `| ${confName(ee)} | ${escapeMarkdownValue(this.settings[ee])} | ${re.map((_ => `${escapeMarkdownValue(_)} |`)).join("")}\n`;
}
const ie = `\nConfiguration mismatching between the clients has been detected.\nThis can be harmful or extra capacity consumption. We have to make these value unified.\n\nConfigured values:\n\n${ne}\n\nPlease select a unification method.\n\nHowever, even if we answer that you will \`Use mine\`, we will be prompted to accept it again on the other device and have to decide accept or not.`, re = "Dismiss", se = [ ..._.map(((_, ee) => [ `Use Remote ${ee + 1}`, _ ])), [ "Use ours", true ], [ re, false ] ], oe = Object.fromEntries(se), le = await confirmWithMessage(this, "Locked", ie, Object.keys(oe), re, 60);
if (!le) return "IGNORE";
const ue = oe[le];
if (true === ue) {
await this.replicator.resetRemoteTweakSettings(this.settings);
Logger("Tweak values on the remote server have been cleared, and will be overwritten in next synchronisation.", LOG_LEVEL_NOTICE);
return "OK";
}
if (ue) {
this.settings = {
...this.settings,
...ue
};
await this.saveSettingData();
Logger("Tweak Values have been overwritten by the chosen one.", LOG_LEVEL_NOTICE);
return "CHECKAGAIN";
}
return "IGNORE";
}
async replicate(_ = false) {
var ee;
if (!this.isReady) return;
if (isLockAcquired("cleanup")) {
Logger("Database cleaning up is in process. replication has been cancelled", LOG_LEVEL_NOTICE);
return;
}
if ("" != this.settings.versionUpFlash) {
Logger("Open settings and check message, please. replication has been cancelled.", LOG_LEVEL_NOTICE);
return;
}
await this.applyBatchChange();
await Promise.all(this.addOns.map((ee => ee.beforeReplicate(_))));
await this.loadQueuedFiles();
const ne = await this.replicator.openReplication(this.settings, false, _, false);
if (!ne) if (this.replicator.tweakSettingsMismatched) await this.askResolvingMismatchedTweaks(); else if (null == (ee = this.replicator) ? void 0 : ee.remoteLockedAndDeviceNotAccepted) if (this.replicator.remoteCleaned && this.settings.useIndexedDBAdapter) {
Logger("The remote database has been cleaned.", _ ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO);
await skipIfDuplicated("cleanup", (async () => {
const ee = `The remote database has been cleaned up.\nTo synchronize, this device must be also cleaned up. ${await purgeUnreferencedChunks(this.localDatabase.localDatabase, true)} chunk(s) will be erased from this device.\nHowever, If there are many chunks to be deleted, maybe fetching again is faster.\nWe will lose the history of this device if we fetch the remote database again.\nEven if you choose to clean up, you will see this option again if you exit Obsidian and then synchronise again.`, ne = "Fetch again", ie = "Cleanup", re = "Dismiss", se = await confirmWithMessage(this, "Cleaned", ee, [ ne, ie, re ], re, 30);
if (se == ne) await performRebuildDB(this, "localOnly");
if (se == ie) {
const ee = this.getReplicator();
if (!(ee instanceof LiveSyncCouchDBReplicator)) return;
const ne = await ee.connectRemoteCouchDBWithSetting(this.settings, this.getIsMobile(), true);
if ("string" == typeof ne) {
Logger(ne, LOG_LEVEL_NOTICE);
return false;
}
await purgeUnreferencedChunks(this.localDatabase.localDatabase, false);
this.localDatabase.hashCaches.clear();
if (await this.replicator.openReplication(this.settings, false, _, true)) {
await balanceChunkPurgedDBs(this.localDatabase.localDatabase, ne.db);
await purgeUnreferencedChunks(this.localDatabase.localDatabase, false);
this.localDatabase.hashCaches.clear();
await this.getReplicator().markRemoteResolved(this.settings);
Logger("The local database has been cleaned up.", _ ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO);
} else Logger("Replication has been cancelled. Please try it again.", _ ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO);
}
}));
} else {
const _ = "\nThe remote database has been rebuilt.\nTo synchronize, this device must fetch everything again once.\nOr if you are sure know what had been happened, we can unlock the database from the setting dialog.\n ", ee = "Fetch again", ne = "Dismiss";
if (await confirmWithMessage(this, "Locked", _, [ ee, ne ], ne, 10) == ee) await performRebuildDB(this, "localOnly");
}
return ne;
}
async initializeDatabase(_ = false, ee = true) {
this.isReady = false;
if (!ee || await this.openDatabase()) {
if (this.localDatabase.isReady) await this.syncAllFiles(_);
await Promise.all(this.addOns.map((ee => ee.onInitializeDatabase(_))));
this.isReady = true;
await this.flushFileEventQueue();
return true;
} else {
this.isReady = false;
return false;
}
}
async replicateAllToServer(_ = false) {
if (!this.isReady) return false;
await Promise.all(this.addOns.map((ee => ee.beforeReplicate(_))));
const ee = await this.replicator.replicateAllToServer(this.settings, _);
if (ee) return true;
if (this.replicator.tweakSettingsMismatched) {
const ee = await this.askResolvingMismatchedTweaks();
if ("OK" == ee) return true;
if ("CHECKAGAIN" == ee) return await this.replicateAllToServer(_);
if ("IGNORE" == ee) return false;
}
return ee;
}
async replicateAllFromServer(_ = false) {
if (!this.isReady) return false;
const ee = await this.replicator.replicateAllFromServer(this.settings, _);
if (ee) return true;
if (this.replicator.tweakSettingsMismatched) {
const ee = await this.askResolvingMismatchedTweaks();
if ("OK" == ee) return true;
if ("CHECKAGAIN" == ee) return await this.replicateAllFromServer(_);
if ("IGNORE" == ee) return false;
}
return ee;
}
async markRemoteLocked(_ = false) {
return await this.replicator.markRemoteLocked(this.settings, true, _);
}
async markRemoteUnlocked() {
return await this.replicator.markRemoteLocked(this.settings, false, false);
}
async markRemoteResolved() {
return await this.replicator.markRemoteResolved(this.settings);
}
isFileSizeExceeded(_) {
if (this.settings.syncMaxSizeInMB > 0 && _ > 0) if (1024 * this.settings.syncMaxSizeInMB * 1024 < _) return true;
return false;
}
async syncAllFiles(_) {
if (!this.settings.isConfigured) {
if (_) Logger("LiveSync is not configured yet. Synchronising between the storage and the local database is now prevented.", LOG_LEVEL_NOTICE, "syncAll");
return;
}
if (_) Logger("Initializing", LOG_LEVEL_NOTICE, "syncAll");
Logger("Initialize and checking database files");
Logger("Checking deleted files");
await this.collectDeletedFiles();
Logger("Collecting local files on the storage", LOG_LEVEL_VERBOSE);
const ee = this.vaultAccess.getFiles(), ne = [];
for (const _ of ee) if (await this.isTargetFile(_.path)) ne.push(_);
const ie = ne.map((_ => _.path));
Logger("Collecting local files on the DB", LOG_LEVEL_VERBOSE);
const re = [];
let se = 0;
for await (const ee of this.localDatabase.findAllNormalDocs()) {
se++;
if (se % 25 == 0) Logger(`Collecting local files on the DB: ${se}`, _ ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO, "syncAll");
const ne = getPath2(ee);
if (isValidPath(ne) && await this.isTargetFile(ne)) re.push(ne);
}
Logger("Opening the key-value database", LOG_LEVEL_VERBOSE);
const oe = await this.kvDB.get("initialized") || false, le = ne.filter((_ => -1 == re.indexOf(getPathFromTFile(_)))), ue = re.filter((_ => -1 == ie.indexOf(_))), de = le.map((_ => _.path)), fe = ne.filter((_ => -1 == de.indexOf(_.path)));
Logger("Updating database by new files");
const he = {}, pe = _ ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO, ge = throttle(((_, ee) => {
he[_] = ee;
Logger(Object.values(he).join("\n"), pe, "syncAll");
}), 25), me = [], runAll = async (_, ee, ne) => {
if (0 == ee.length) {
Logger(`${_}: Nothing to do`);
return;
}
Logger(_);
if (!this.localDatabase.isReady) throw Error("Database is not ready!");
let ie = 0, re = 0;
const se = new QueueProcessor((async ee => {
try {
await ne(ee[0]);
ie++;
} catch (ee) {
Logger(`Error while ${_}`, LOG_LEVEL_NOTICE);
Logger(ee, LOG_LEVEL_VERBOSE);
re++;
}
if ((ie + re) % 10 == 0) {
const ee = `${_}: DONE:${ie}, FAILED:${re}, LAST:${se._queue.length}`;
ge(_, ee);
}
}), {
batchSize: 1,
concurrentLimit: 10,
delay: 0,
suspended: true
}, ee);
await se.waitForAllDoneAndTerminate();
ge(_, `${_} All done: DONE:${ie}, FAILED:${re}`);
};
me.push(runAll("UPDATE DATABASE", le, (async _ => {
if (!this.isFileSizeExceeded(_.stat.size)) {
await this.updateIntoDB(_);
fireAndForget((() => this.checkAndApplySettingFromMarkdown(_.path, true)));
} else Logger(`UPDATE DATABASE: ${_.path} has been skipped due to file size exceeding the limit`, pe);
})));
me.push(runAll("UPDATE STORAGE", ue, (async _ => {
const ee = await this.localDatabase.getDBEntryMeta(_, {}, true);
if (ee && !(ee.deleted || ee._deleted)) if (!this.isFileSizeExceeded(ee.size)) {
await this.pullFile(_, ne, false, void 0, false);
fireAndForget((() => this.checkAndApplySettingFromMarkdown(_, true)));
Logger(`Check or pull from db:${_} OK`);
} else Logger(`UPDATE STORAGE: ${_} has been skipped due to file size exceeding the limit`, pe); else if (ee) Logger(`Deletion history skipped: ${_}`, LOG_LEVEL_VERBOSE); else Logger(`entry not found: ${_}`);
})));
const ye = new QueueProcessor((async _ => {
const ee = _[0];
return [ {
file: ee,
id: await this.path2id(getPathFromTFile(ee))
} ];
}), {
batchSize: 1,
concurrentLimit: 10,
delay: 0,
suspended: true
}, fe);
ye.pipeTo(new QueueProcessor((async _ => {
const ee = await this.localDatabase.allDocsRaw({
keys: _.map((_ => _.id)),
include_docs: true
}), ne = Object.fromEntries(ee.rows.map((_ => [ _.id, _.doc ])));
return _.map((_ => ({
file: _.file,
doc: ne[_.id]
})));
}), {
batchSize: 10,
concurrentLimit: 5,
delay: 10,
suspended: false
})).pipeTo(new QueueProcessor((async _ => {
const ee = _[0];
await this.syncFileBetweenDBandStorage(ee.file, ee.doc);
}), {
batchSize: 1,
concurrentLimit: 5,
delay: 10,
suspended: false
}));
const ve = fe.length;
let Se = ve;
ye.startPipeline().onUpdateProgress((() => (_ => {
if (Se - _ > 25) {
ge("sync", ` CHECK AND SYNC: ${ve - _} / ${ve}`);
Se = _;
}
})(ye.totalRemaining + ye.nowProcessing)));
me.push(ye.waitForAllDoneAndTerminate());
await Promise.all(me);
Logger("Initialized, NOW TRACKING!");
if (!oe) await this.kvDB.set("initialized", true);
if (_) Logger("Initialize done!", LOG_LEVEL_NOTICE, "syncAll");
}
async getConflictedDoc(_, ee) {
try {
const ne = await this.localDatabase.getDBEntry(_, {
rev: ee
}, false, false, true);
if (false === ne) return false;
let ie = getDocData(ne.data);
if ("newnote" == ne.datatype) ie = readString(new Uint8Array(decodeBinary(ne.data))); else if ("plain" == ne.datatype) ;
return {
deleted: ne.deleted || ne._deleted,
ctime: ne.ctime,
mtime: ne.mtime,
rev: ee,
data: ie
};
} catch (_) {
if (isErrorOfMissingDoc(_)) return false;
}
return false;
}
async mergeSensibly(_, ee, ne, ie) {
var re, se, oe, le;
const ue = await this.getConflictedDoc(_, ee), de = await this.getConflictedDoc(_, ne), fe = await this.getConflictedDoc(_, ie);
let he = false;
if (false == ue || false == de || false == fe) return false;
if (de.deleted && fe.deleted) return false;
const pe = new import_diff_match_patch.diff_match_patch, ge = pe.diff_linesToChars_(ue.data, de.data), me = pe.diff_main(ge.chars1, ge.chars2, false);
pe.diff_charsToLines_(me, ge.lineArray);
const ye = pe.diff_linesToChars_(ue.data, fe.data), ve = pe.diff_main(ye.chars1, ye.chars2, false);
pe.diff_charsToLines_(ve, ye.lineArray);
function splitDiffPiece(_) {
const ee = [];
do {
const ne = _.shift();
if (void 0 === ne) return ee;
const ie = ne[1].split(/([^\n]*\n)/).filter((_ => "" != _));
if ("undefined" == typeof ne) break;
if (ne[0] != import_diff_match_patch.DIFF_DELETE) ee.push(...ie.map((_ => [ ne[0], _ ])));
if (ne[0] == import_diff_match_patch.DIFF_DELETE) {
const re = _.shift();
if ("undefined" != typeof re) {
const _ = re[1].split(/([^\n]*\n)/).filter((_ => "" != _));
if (re[0] == import_diff_match_patch.DIFF_INSERT) {
for (const re of ie) {
ee.push([ ne[0], re ]);
const ie = _.shift();
if ("undefined" != typeof ie) ee.push([ import_diff_match_patch.DIFF_INSERT, ie ]);
}
ee.push(..._.map((_ => [ re[0], _ ])));
} else {
ee.push(...ie.map((_ => [ ne[0], _ ])));
ee.push(..._.map((_ => [ re[0], _ ])));
}
} else ee.push(...ie.map((_ => [ 0, _ ])));
}
} while (_.length > 0);
return ee;
}
const Se = splitDiffPiece(me), Ee = splitDiffPiece(ve);
let Ce = 0, we = 0;
const Oe = [];
he = true;
e: do {
if (we >= Se.length && Ce >= Ee.length) break e;
const _ = null != (re = Se[we]) ? re : [ 0, "" ], ee = null != (se = Ee[Ce]) ? se : [ 0, "" ];
we++;
Ce++;
if (_[0] != import_diff_match_patch.DIFF_EQUAL || ee[0] != import_diff_match_patch.DIFF_EQUAL || _[1] != ee[1]) {
if (_[0] == import_diff_match_patch.DIFF_DELETE && ee[0] == import_diff_match_patch.DIFF_DELETE && _[1] == ee[1]) {
const ee = we, ne = Ce, [ie, re] = [ null != (oe = Se[ee]) ? oe : [ 0, "" ], null != (le = Ee[ne]) ? le : [ 0, "" ] ];
if (ie[0] == import_diff_match_patch.DIFF_INSERT && re[0] == import_diff_match_patch.DIFF_INSERT && ie[1] != re[1]) {
he = false;
break;
} else {
Oe.push(_);
continue;
}
}
if (_[0] == import_diff_match_patch.DIFF_INSERT && ee[0] == import_diff_match_patch.DIFF_INSERT) if (_[1] == ee[1]) {
Oe.push(_);
continue;
} else if (de.mtime <= fe.mtime) {
Oe.push(_);
Oe.push(ee);
continue;
} else {
Oe.push(ee);
Oe.push(_);
continue;
}
if (_[0] != import_diff_match_patch.DIFF_INSERT) if (ee[0] != import_diff_match_patch.DIFF_INSERT) {
if (ee[1] != _[1]) {
Logger(`MERGING PANIC:${_[0]},${_[1]} == ${ee[0]},${ee[1]}`, LOG_LEVEL_VERBOSE);
he = false;
break e;
}
if (_[0] == import_diff_match_patch.DIFF_DELETE) if (ee[0] == import_diff_match_patch.DIFF_EQUAL) {
Oe.push(_);
continue;
} else {
he = false;
break e;
}
if (ee[0] == import_diff_match_patch.DIFF_DELETE) if (_[0] == import_diff_match_patch.DIFF_EQUAL) {
Oe.push(ee);
continue;
} else {
he = false;
break e;
}
Logger(`Weird condition:${_[0]},${_[1]} == ${ee[0]},${ee[1]}`, LOG_LEVEL_VERBOSE);
break e;
} else {
we--;
Oe.push(ee);
} else {
Ce--;
Oe.push(_);
}
} else Oe.push(_);
} while (we < Se.length || Ce < Ee.length);
if (he) {
Logger("Sensibly merge available", LOG_LEVEL_VERBOSE);
return Oe;
} else return false;
}
async mergeObject(_, ee, ne, ie) {
try {
const re = await this.getConflictedDoc(_, ee), se = await this.getConflictedDoc(_, ne), oe = await this.getConflictedDoc(_, ie);
if (false == re || false == se || false == oe) return false;
if (se.deleted && oe.deleted) return false;
const le = {
data: tryParseJSON(re.data, {})
}, ue = {
data: tryParseJSON(se.data, {})
}, de = {
data: tryParseJSON(oe.data, {})
}, fe = generatePatchObj(le, ue), he = generatePatchObj(le, de), pe = new Map(flattenObject(fe)), ge = new Map(flattenObject(he));
for (const [_, ee] of pe) if (ge.has(_)) if (ge.get(_) == ee) ge.delete(_);
for (const [_, ee] of ge) if (pe.has(_) && pe.get(_) != ee) return false;
const me = [ {
mtime: se.mtime,
patch: fe
}, {
mtime: oe.mtime,
patch: he
} ].sort(((_, ee) => _.mtime - ee.mtime));
let ye = {
...le
};
for (const _ of me) ye = applyPatch(ye, _.patch);
return JSON.stringify(ye.data);
} catch (_) {
Logger("Could not merge object");
Logger(_, LOG_LEVEL_VERBOSE);
return false;
}
}
async checkConflictAndPerformAutoMerge(_) {
var ee, ne;
const ie = await this.localDatabase.getDBEntry(_, {
conflicts: true,
revs_info: true
}, false, false, true);
if (false === ie) return MISSING_OR_ERROR;
if (null == ie) return MISSING_OR_ERROR;
if (!ie._conflicts) return NOT_CONFLICTED;
if (0 == ie._conflicts.length) return NOT_CONFLICTED;
const re = ie._conflicts.sort(((_, ee) => Number(_.split("-")[0]) - Number(ee.split("-")[0])));
if ((isSensibleMargeApplicable(_) || isObjectMargeApplicable(_)) && !this.settings.disableMarkdownAutoMerge) {
const se = re[0], oe = Number(se.split("-")[0]), le = null != (ne = null == (ee = ((await this.localDatabase.getRaw(await this.path2id(_), {
revs_info: true
}))._revs_info || []).filter((_ => "available" == _.status && Number(_.rev.split("-")[0]) < oe)).first()) ? void 0 : ee.rev) ? ne : "";
let ue;
if (le) {
if (isSensibleMargeApplicable(_)) {
const ee = await this.mergeSensibly(_, le, ie._rev, se);
if (ee) {
ue = ee.filter((_ => _[0] != import_diff_match_patch.DIFF_DELETE)).map((_ => _[1])).join("");
Logger(`Sensible merge:${_}`, LOG_LEVEL_INFO);
} else Logger("Sensible merge is not applicable.", LOG_LEVEL_VERBOSE);
} else if (isObjectMargeApplicable(_)) {
const ee = await this.mergeObject(_, le, ie._rev, se);
if (ee) {
Logger(`Object merge:${_}`, LOG_LEVEL_INFO);
ue = ee;
} else Logger("Object merge is not applicable.", LOG_LEVEL_VERBOSE);
}
if (null != ue) {
await this.localDatabase.deleteDBEntry(_, {
rev: se
});
const ee = this.vaultAccess.getAbstractFileByPath(stripAllPrefixes(_));
if (ee) {
if (await this.vaultAccess.vaultModify(ee, ue)) await this.updateIntoDB(ee);
} else {
const ee = await this.vaultAccess.vaultCreate(_, ue);
await this.updateIntoDB(ee);
}
await this.pullFile(_);
Logger(`Automatically merged (sensible) :${_}`, LOG_LEVEL_INFO);
return AUTO_MERGED;
}
}
}
const se = await this.getConflictedDoc(_, ie._rev), oe = await this.getConflictedDoc(_, re[0]);
if (false == se) {
Logger(`could not get current revisions:${_}`, LOG_LEVEL_NOTICE);
return MISSING_OR_ERROR;
}
if (false == oe) {
await this.localDatabase.deleteDBEntry(_, {
rev: re[0]
});
await this.pullFile(_, void 0, true);
Logger(`could not get old revisions, automatically used newer one:${_}`, LOG_LEVEL_NOTICE);
return AUTO_MERGED;
}
const le = se.data == oe.data && se.deleted == oe.deleted, ue = !isPlainText(_), de = this.settings.resolveConflictsByNewerFile;
if (le || ue || de) {
let ee = se;
if (compareMTime(se.mtime, oe.mtime) != TARGET_IS_NEW) ee = oe;
await this.localDatabase.deleteDBEntry(_, {
rev: ee.rev
});
await this.pullFile(_, void 0, true);
Logger(`Automatically merged (${le ? "same," : ""}${ue ? "binary," : ""}${de ? "alwaysNewer" : ""}) :${_}`, LOG_LEVEL_NOTICE);
return AUTO_MERGED;
}
const fe = new import_diff_match_patch.diff_match_patch, he = fe.diff_main(se.data, oe.data);
fe.diff_cleanupSemantic(he);
Logger(`conflict(s) found:${_}`);
return {
left: se,
right: oe,
diff: he
};
}
async resolveConflictByUI(_, ee) {
Logger("Merge:open conflict dialog", LOG_LEVEL_VERBOSE);
const ne = new ConflictResolveModal(this.app, _, ee);
ne.open();
const ie = await ne.waitForResult();
if (ie === CANCELLED) {
Logger(`Merge: Cancelled ${_}`, LOG_LEVEL_INFO);
return false;
}
const re = await this.localDatabase.getDBEntry(_, {
conflicts: true
}, false, false, true);
if (false === re) {
Logger(`Merge: Could not read ${_} from the local database`, LOG_LEVEL_VERBOSE);
return false;
}
if (!re._conflicts) {
Logger(`Merge: Nothing to do ${_}`, LOG_LEVEL_VERBOSE);
return false;
}
const se = ie, oe = ee.left.rev != se ? ee.left.rev : ee.right.rev;
if (se === LEAVE_TO_SUBSEQUENT) {
const ne = ee.diff.map((_ => _[1])).join("");
await this.localDatabase.deleteDBEntry(_, {
rev: re._conflicts[0]
});
const ie = this.vaultAccess.getAbstractFileByPath(stripAllPrefixes(_));
if (ie) {
if (await this.vaultAccess.vaultModify(ie, ne)) await this.updateIntoDB(ie);
} else {
const ee = await this.vaultAccess.vaultCreate(_, ne);
await this.updateIntoDB(ee);
}
await this.pullFile(_);
Logger(`Merge: Changes has been concatenated: ${_}`);
} else if ("string" == typeof se) {
await this.localDatabase.deleteDBEntry(_, {
rev: se
});
await this.pullFile(_, void 0, true, oe);
Logger(`Conflict resolved:${_}`);
} else {
Logger(`Merge: Something went wrong: ${_}, (${se})`, LOG_LEVEL_NOTICE);
return false;
}
if (this.settings.syncAfterMerge && !this.suspended) await shareRunningResult("replication", (() => this.replicate()));
this.conflictCheckQueue.enqueue(_);
return false;
}
async pullFile(_, ee, ne, ie, re = true) {
const se = this.vaultAccess.getAbstractFileByPath(stripAllPrefixes(_));
if (await this.isTargetFile(_)) if (null == se) {
const ee = await this.localDatabase.getDBEntry(_, ie ? {
rev: ie
} : void 0, false, re);
if (false === ee) {
Logger(`${_} Skipped`);
return;
}
await this.processEntryDoc(ee, void 0, ne);
} else if (se instanceof import_obsidian.TFile) {
const ee = se, oe = await this.localDatabase.getDBEntry(_, ie ? {
rev: ie
} : void 0, false, re);
if (false === oe) {
Logger(`${_} Skipped`);
return;
}
await this.processEntryDoc(oe, ee, ne);
} else Logger(`target files:${_} is exists as the folder`);
}
async syncFileBetweenDBandStorage(_, ee) {
if (!ee) throw new Error(`Missing doc:${_.path}`);
if (!(_ instanceof import_obsidian.TFile) && "path" in _) {
const ee = this.vaultAccess.getAbstractFileByPath(_.path);
if (ee instanceof import_obsidian.TFile) _ = ee; else throw new Error(`Missing file:${_.path}`);
}
switch (compareFileFreshness(_, ee)) {
case BASE_IS_NEW:
if (!this.isFileSizeExceeded(_.stat.size)) {
Logger("STORAGE -> DB :" + _.path);
await this.updateIntoDB(_);
fireAndForget((() => this.checkAndApplySettingFromMarkdown(_.path, true)));
} else Logger(`STORAGE -> DB : ${_.path} has been skipped due to file size exceeding the limit`, LOG_LEVEL_NOTICE);
break;
case TARGET_IS_NEW:
if (!this.isFileSizeExceeded(ee.size)) {
Logger("STORAGE <- DB :" + _.path);
const ee = await this.localDatabase.getDBEntry(getPathFromTFile(_), void 0, false, false, true);
if (false != ee) await this.processEntryDoc(ee, _); else Logger(`STORAGE <- DB : Cloud not read ${_.path}, possibly deleted`, LOG_LEVEL_NOTICE);
return caches;
} else Logger(`STORAGE <- DB : ${_.path} has been skipped due to file size exceeding the limit`, LOG_LEVEL_NOTICE);
break;
case EVEN:
Logger("STORAGE == DB :" + _.path, LOG_LEVEL_DEBUG);
break;
default:
Logger("STORAGE ?? DB :" + _.path + " Something got weird");
}
}
async updateIntoDB(_, ee, ne) {
if (!await this.isTargetFile(_)) return true;
if (shouldBeIgnored(_.path)) return true;
const ie = !isPlainText(_.name);
if (ie) Logger(`Reading : ${_.path}`, LOG_LEVEL_VERBOSE);
const re = createBlob(await this.vaultAccess.vaultReadAuto(_)), se = determineTypeFromBlob(re);
if (ie) Logger(`Processing: ${_.path}`, LOG_LEVEL_VERBOSE);
const oe = getPathFromTFile(_), le = {
_id: await this.path2id(oe),
path: getPathFromTFile(_),
data: re,
ctime: _.stat.ctime,
mtime: _.stat.mtime,
size: _.stat.size,
children: [],
datatype: se,
type: se,
eden: {}
}, ue = `STORAGE -> DB (${se}) `;
if (await serialized("file-" + oe, (async () => {
if (this.vaultAccess.recentlyTouched(_)) return true;
try {
const _ = await this.localDatabase.getDBEntry(oe, void 0, false, false);
if (false !== _) {
const ee = {
data: _.data,
deleted: _._deleted || _.deleted
}, ne = {
data: le.data,
deleted: le._deleted || le.deleted
};
if (ee.deleted != ne.deleted) return false;
if (!await isDocContentSame(_.data, ne.data)) return false;
Logger(ue + "Skipped (not changed) " + oe + (le._deleted || le.deleted ? " (deleted)" : ""), LOG_LEVEL_VERBOSE);
markChangesAreSame(_, le.mtime, _.mtime);
return true;
}
} catch (_) {
if (ne) Logger(ue + "Error, Could not check the diff for the old one." + (ne ? "force writing." : "") + oe + (le._deleted || le.deleted ? " (deleted)" : ""), LOG_LEVEL_VERBOSE); else Logger(ue + "Error, Could not check the diff for the old one." + oe + (le._deleted || le.deleted ? " (deleted)" : ""), LOG_LEVEL_VERBOSE);
return !ne;
}
return false;
}))) {
Logger(ue + " Skip " + oe, LOG_LEVEL_VERBOSE);
return true;
}
const de = await this.localDatabase.putDBEntry(le);
if (false !== de) {
Logger(ue + oe);
this.scheduleReplicateIfSyncOnSave();
}
return false != de;
}
scheduleReplicateIfSyncOnSave() {
if (this.settings.syncOnSave && !this.suspended) scheduleTask("perform-replicate-after-save", 250, (() => this.replicate()));
}
async deleteFromDB(_) {
if (!await this.isTargetFile(_)) return;
const ee = getPathFromTFile(_);
Logger(`deleteDB By path:${ee}`);
await this.deleteFromDBbyPath(ee);
this.scheduleReplicateIfSyncOnSave();
}
async deleteFromDBbyPath(_) {
await this.localDatabase.deleteDBEntry(_);
this.scheduleReplicateIfSyncOnSave();
}
async resetLocalDatabase() {
this.vaultAccess.clearTouched();
await this.localDatabase.resetDatabase();
}
async tryResetRemoteDatabase() {
await this.replicator.tryResetRemoteDatabase(this.settings);
}
async tryCreateRemoteDatabase() {
await this.replicator.tryCreateRemoteDatabase(this.settings);
}
filterTargetFiles(_, ee = false) {
const ne = this.settings.syncInternalFilesIgnorePatterns.replace(/\n| /g, "").split(",").filter((_ => _)).map((_ => new RegExp(_, "i")));
return _.filter((_ => !ne.some((ee => _.path.match(ee))))).filter((_ => !ee || ee && -1 !== ee.indexOf(_.path)));
}
async resolveConflictByNewerEntry(_) {
const ee = await this.path2id(_), ne = await this.localDatabase.getRaw(ee, {
conflicts: true
});
if (!("_conflicts" in ne) || void 0 === ne._conflicts) return false;
if (0 == ne._conflicts.length) return false;
Logger(`Hidden file conflicted:${this.getPath(ne)}`);
const ie = ne._conflicts.sort(((_, ee) => Number(_.split("-")[0]) - Number(ee.split("-")[0]))), re = ne._rev, se = ie[0], oe = await this.localDatabase.getRaw(ee, {
rev: se
}), le = ("mtime" in ne && ne.mtime || 0) < ("mtime" in oe && oe.mtime || 0) ? re : se;
await this.localDatabase.removeRevision(ee, le);
Logger(`Older one has been deleted:${this.getPath(ne)}`);
return true;
}
async readIgnoreFile(_) {
try {
const ee = (await this.vaultAccess.adapterRead(_)).split(/\r?\n/g);
this.ignoreFileCache.set(_, ee);
return ee;
} catch (ee) {
this.ignoreFileCache.set(_, false);
return false;
}
}
async getIgnoreFile(_) {
var ee;
if (this.ignoreFileCache.has(_)) return null != (ee = this.ignoreFileCache.get(_)) ? ee : false; else return await this.readIgnoreFile(_);
}
async isIgnoredByIgnoreFiles(_) {
if (!this.settings.useIgnoreFiles) return false;
const ee = _ instanceof import_obsidian.TFile ? _.path : _;
if (this.ignoreFileCache.has(ee)) await this.readIgnoreFile(ee);
if (!await isAcceptedAll(stripAllPrefixes(ee), this.ignoreFiles, (_ => this.getIgnoreFile(_)))) return true; else return false;
}
async isTargetFile(_) {
const ee = _ instanceof import_obsidian.TFile ? _.path : _;
if (this.settings.useIgnoreFiles && await this.isIgnoredByIgnoreFiles(_)) return false; else return this.localDatabase.isTargetFile(ee);
}
async dryRunGC() {
await skipIfDuplicated("cleanup", (async () => {
const _ = this.getReplicator();
if (!(_ instanceof LiveSyncCouchDBReplicator)) return;
const ee = await _.connectRemoteCouchDBWithSetting(this.settings, this.isMobile);
if ("string" != typeof ee) {
await purgeUnreferencedChunks(ee.db, true, this.settings, false);
await purgeUnreferencedChunks(this.localDatabase.localDatabase, true);
this.localDatabase.hashCaches.clear();
} else Logger(ee);
}));
}
async dbGC() {
await skipIfDuplicated("cleanup", (async () => {
const _ = this.getReplicator();
if (!(_ instanceof LiveSyncCouchDBReplicator)) return;
this.getReplicator().markRemoteLocked(this.settings, true, true);
const ee = await _.connectRemoteCouchDBWithSetting(this.settings, this.isMobile);
if ("string" != typeof ee) {
await purgeUnreferencedChunks(ee.db, false, this.settings, true);
await purgeUnreferencedChunks(this.localDatabase.localDatabase, false);
this.localDatabase.hashCaches.clear();
await balanceChunkPurgedDBs(this.localDatabase.localDatabase, ee.db);
this.localDatabase.refreshSettings();
Logger("The remote database has been cleaned up! Other devices will be cleaned up on the next synchronisation.");
} else Logger(ee);
}));
}
askYesNo(_) {
return askYesNo(this.app, _);
}
askSelectString(_, ee) {
return askSelectString(this.app, _, ee);
}
askInPopup(_, ee, ne) {
const ie = createFragment((_ => {
const [ie, re] = ee.split("{HERE}", 2);
_.createEl("span", void 0, (_ => {
_.appendText(ie);
_.appendChild(_.createEl("a", void 0, (_ => {
ne(_);
})));
_.appendText(re);
}));
})), re = "popup-" + _;
scheduleTask(re, 1e3, (async () => {
var _;
const ee = await memoIfNotExist(re, (() => new import_obsidian.Notice(ie, 0)));
if (!(null == (_ = null == ee ? void 0 : ee.noticeEl) ? void 0 : _.isShown())) memoObject(re, new import_obsidian.Notice(ie, 0));
scheduleTask(re + "-close", 2e4, (() => {
var _;
const ee = retrieveMemoObject(re);
if (ee) {
if (null == (_ = null == ee ? void 0 : ee.noticeEl) ? void 0 : _.isShown()) ee.hide();
disposeMemoObject(re);
}
}));
}));
}
openSetting() {
this.app.setting.open();
this.app.setting.openTabById("obsidian-livesync");
}
performAppReload() {
this.performCommand("app:reload");
}
performCommand(_) {
this.app.commands.executeCommandById(_);
}
get isReloadingScheduled() {
return void 0 !== this._totalProcessingCount;
}
askReload(_) {
if (!this.isReloadingScheduled) scheduleTask("configReload", 250, (async () => {
const ee = "Yes, restart immediately", ne = "Yes, schedule a restart after stabilisation", ie = await askSelectString(this.app, _ || "Do you want to restart and reload Obsidian now?", [ ne, ee, "No, Leave it to me" ]);
if (ie == ee) this.performAppReload(); else if (ie == ne) this.scheduleAppReload();
})); else Logger("Reloading is already scheduled", LOG_LEVEL_VERBOSE);
}
scheduleAppReload() {
if (!this._totalProcessingCount) {
const _ = reactiveSource(0);
this._totalProcessingCount = reactive((() => {
const ee = this.databaseQueueCount.value, ne = this.replicationResultCount.value, ie = this.storageApplyingCount.value, re = collectingChunks.value, se = pluginScanningCount.value, oe = hiddenFilesEventCount.value + hiddenFilesProcessingCount.value, le = this.conflictProcessQueueCount.value, ue = this.pendingFileEventCount.value, de = this.processingFileEventCount.value;
_.value;
return ee + ne + ie + re + se + oe + le + ue + de;
}));
this.registerInterval(setInterval((() => {
_.value++;
}), 1e3));
let ee = 3;
this._totalProcessingCount.onChanged((_ => {
if (0 == _.value) {
if (ee-- <= 0) this.performAppReload();
Logger(`Obsidian will be restarted soon! (Within ${ee} seconds)`, LOG_LEVEL_NOTICE, "restart-notice");
} else ee = 3;
}));
}
}
};
/*! Bundled license information:
tslib/tslib.es6.js:
(*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** *)
tslib/tslib.es6.js:
(*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** *)
tslib/tslib.es6.js:
(*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** *)
tslib/tslib.es6.js:
(*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** *)
tslib/tslib.es6.js:
(*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** *)
tslib/tslib.es6.js:
(*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** *)
tslib/tslib.es6.js:
(*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** *)
*/