/*
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 __create = Object.create, __defProp = Object.defineProperty, __getOwnPropDesc = Object.getOwnPropertyDescriptor, __getOwnPropNames = Object.getOwnPropertyNames, __getProtoOf = Object.getPrototypeOf, __hasOwnProp = Object.prototype.hasOwnProperty, __defNormalProp = (s, r, o) => r in s ? __defProp(s, r, {
enumerable: true,
configurable: true,
writable: true,
value: o
}) : s[r] = o, __commonJS = (s, r) => function __require() {
return r || (0, s[__getOwnPropNames(s)[0]])((r = {
exports: {}
}).exports, r), r.exports;
}, __export = (s, r) => {
for (var o in r) __defProp(s, o, {
get: r[o],
enumerable: true
});
}, __copyProps = (s, r, o, u) => {
if (r && "object" == typeof r || "function" == typeof r) for (let g of __getOwnPropNames(r)) if (!__hasOwnProp.call(s, g) && g !== o) __defProp(s, g, {
get: () => r[g],
enumerable: !(u = __getOwnPropDesc(r, g)) || u.enumerable
});
return s;
}, __toESM = (s, r, o) => (o = null != s ? __create(__getProtoOf(s)) : {}, __copyProps(r || !s || !s.__esModule ? __defProp(o, "default", {
value: s,
enumerable: true
}) : o, s)), __toCommonJS = s => __copyProps(__defProp({}, "__esModule", {
value: true
}), s), __publicField = (s, r, o) => {
__defNormalProp(s, "symbol" != typeof r ? r + "" : r, o);
return o;
}, __accessCheck = (s, r, o) => {
if (!r.has(s)) throw TypeError("Cannot " + o);
}, __privateGet = (s, r, o) => {
__accessCheck(s, r, "read from private field");
return o ? o.call(s) : r.get(s);
}, __privateAdd = (s, r, o) => {
if (r.has(s)) throw TypeError("Cannot add the same private member more than once");
r instanceof WeakSet ? r.add(s) : r.set(s, o);
}, __privateSet = (s, r, o, u) => {
__accessCheck(s, r, "write to private field");
u ? u.call(s, o) : r.set(s, o);
return o;
}, __privateMethod = (s, r, o) => {
__accessCheck(s, r, "access private method");
return o;
}, require_diff_match_patch = __commonJS({
"node_modules/diff-match-patch/index.js"(s, r) {
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;
}, o = -1;
diff_match_patch2.Diff = function(s, r) {
return [ s, r ];
};
diff_match_patch2.prototype.diff_main = function(s, r, o, u) {
if ("undefined" == typeof u) if (this.Diff_Timeout <= 0) u = Number.MAX_VALUE; else u = (new Date).getTime() + 1e3 * this.Diff_Timeout;
var g = u;
if (null == s || null == r) throw new Error("Null input. (diff_main)");
if (s == r) if (s) return [ new diff_match_patch2.Diff(0, s) ]; else return [];
if ("undefined" == typeof o) o = true;
var _ = o, m = this.diff_commonPrefix(s, r), b = s.substring(0, m);
s = s.substring(m);
r = r.substring(m);
m = this.diff_commonSuffix(s, r);
var E = s.substring(s.length - m);
s = s.substring(0, s.length - m);
r = r.substring(0, r.length - m);
var w = this.diff_compute_(s, r, _, g);
if (b) w.unshift(new diff_match_patch2.Diff(0, b));
if (E) w.push(new diff_match_patch2.Diff(0, E));
this.diff_cleanupMerge(w);
return w;
};
diff_match_patch2.prototype.diff_compute_ = function(s, r, u, g) {
var _;
if (!s) return [ new diff_match_patch2.Diff(1, r) ];
if (!r) return [ new diff_match_patch2.Diff(o, s) ];
var m = s.length > r.length ? s : r, b = s.length > r.length ? r : s, E = m.indexOf(b);
if (-1 != E) {
_ = [ new diff_match_patch2.Diff(1, m.substring(0, E)), new diff_match_patch2.Diff(0, b), new diff_match_patch2.Diff(1, m.substring(E + b.length)) ];
if (s.length > r.length) _[0][0] = _[2][0] = o;
return _;
}
if (1 == b.length) return [ new diff_match_patch2.Diff(o, s), new diff_match_patch2.Diff(1, r) ];
var w = this.diff_halfMatch_(s, r);
if (w) {
var S = w[0], L = w[1], O = w[2], D = w[3], k = w[4], C = this.diff_main(S, O, u, g), T = this.diff_main(L, D, u, g);
return C.concat([ new diff_match_patch2.Diff(0, k) ], T);
}
if (u && s.length > 100 && r.length > 100) return this.diff_lineMode_(s, r, g); else return this.diff_bisect_(s, r, g);
};
diff_match_patch2.prototype.diff_lineMode_ = function(s, r, u) {
var g = this.diff_linesToChars_(s, r);
s = g.chars1;
r = g.chars2;
var _ = g.lineArray, m = this.diff_main(s, r, false, u);
this.diff_charsToLines_(m, _);
this.diff_cleanupSemantic(m);
m.push(new diff_match_patch2.Diff(0, ""));
for (var b = 0, E = 0, w = 0, S = "", L = ""; b < m.length; ) {
switch (m[b][0]) {
case 1:
w++;
L += m[b][1];
break;
case o:
E++;
S += m[b][1];
break;
case 0:
if (E >= 1 && w >= 1) {
m.splice(b - E - w, E + w);
b = b - E - w;
for (var O = this.diff_main(S, L, false, u), D = O.length - 1; D >= 0; D--) m.splice(b, 0, O[D]);
b += O.length;
}
w = 0;
E = 0;
S = "";
L = "";
break;
}
b++;
}
m.pop();
return m;
};
diff_match_patch2.prototype.diff_bisect_ = function(s, r, u) {
for (var g = s.length, _ = r.length, m = Math.ceil((g + _) / 2), b = m, E = 2 * m, w = new Array(E), S = new Array(E), L = 0; L < E; L++) {
w[L] = -1;
S[L] = -1;
}
w[b + 1] = 0;
S[b + 1] = 0;
for (var O = g - _, D = O % 2 != 0, k = 0, C = 0, T = 0, I = 0, A = 0; A < m && !((new Date).getTime() > u); A++) {
for (var R = -A + k; R <= A - C; R += 2) {
var x = b + R;
if (R == -A || R != A && w[x - 1] < w[x + 1]) V = w[x + 1]; else V = w[x - 1] + 1;
for (var P = V - R; V < g && P < _ && s.charAt(V) == r.charAt(P); ) {
V++;
P++;
}
w[x] = V;
if (V > g) C += 2; else if (P > _) k += 2; else if (D) if ((F = b + O - R) >= 0 && F < E && -1 != S[F]) if (V >= (B = g - S[F])) return this.diff_bisectSplit_(s, r, V, P, u);
}
for (var N = -A + T; N <= A - I; N += 2) {
var B, F = b + N;
if (N == -A || N != A && S[F - 1] < S[F + 1]) B = S[F + 1]; else B = S[F - 1] + 1;
for (var M = B - N; B < g && M < _ && s.charAt(g - B - 1) == r.charAt(_ - M - 1); ) {
B++;
M++;
}
S[F] = B;
if (B > g) I += 2; else if (M > _) T += 2; else if (!D) if ((x = b + O - N) >= 0 && x < E && -1 != w[x]) {
var V;
P = b + (V = w[x]) - x;
if (V >= (B = g - B)) return this.diff_bisectSplit_(s, r, V, P, u);
}
}
}
return [ new diff_match_patch2.Diff(o, s), new diff_match_patch2.Diff(1, r) ];
};
diff_match_patch2.prototype.diff_bisectSplit_ = function(s, r, o, u, g) {
var _ = s.substring(0, o), m = r.substring(0, u), b = s.substring(o), E = r.substring(u), w = this.diff_main(_, m, false, g), S = this.diff_main(b, E, false, g);
return w.concat(S);
};
diff_match_patch2.prototype.diff_linesToChars_ = function(s, r) {
var o = [], u = {};
o[0] = "";
function diff_linesToCharsMunge_(s) {
for (var r = "", _ = 0, m = -1, b = o.length; m < s.length - 1; ) {
if (-1 == (m = s.indexOf("\n", _))) m = s.length - 1;
var E = s.substring(_, m + 1);
if (u.hasOwnProperty ? u.hasOwnProperty(E) : void 0 !== u[E]) r += String.fromCharCode(u[E]); else {
if (b == g) {
E = s.substring(_);
m = s.length;
}
r += String.fromCharCode(b);
u[E] = b;
o[b++] = E;
}
_ = m + 1;
}
return r;
}
var g = 4e4, _ = diff_linesToCharsMunge_(s);
g = 65535;
return {
chars1: _,
chars2: diff_linesToCharsMunge_(r),
lineArray: o
};
};
diff_match_patch2.prototype.diff_charsToLines_ = function(s, r) {
for (var o = 0; o < s.length; o++) {
for (var u = s[o][1], g = [], _ = 0; _ < u.length; _++) g[_] = r[u.charCodeAt(_)];
s[o][1] = g.join("");
}
};
diff_match_patch2.prototype.diff_commonPrefix = function(s, r) {
if (!s || !r || s.charAt(0) != r.charAt(0)) return 0;
for (var o = 0, u = Math.min(s.length, r.length), g = u, _ = 0; o < g; ) {
if (s.substring(_, g) == r.substring(_, g)) _ = o = g; else u = g;
g = Math.floor((u - o) / 2 + o);
}
return g;
};
diff_match_patch2.prototype.diff_commonSuffix = function(s, r) {
if (!s || !r || s.charAt(s.length - 1) != r.charAt(r.length - 1)) return 0;
for (var o = 0, u = Math.min(s.length, r.length), g = u, _ = 0; o < g; ) {
if (s.substring(s.length - g, s.length - _) == r.substring(r.length - g, r.length - _)) _ = o = g; else u = g;
g = Math.floor((u - o) / 2 + o);
}
return g;
};
diff_match_patch2.prototype.diff_commonOverlap_ = function(s, r) {
var o = s.length, u = r.length;
if (0 == o || 0 == u) return 0;
if (o > u) s = s.substring(o - u); else if (o < u) r = r.substring(0, o);
var g = Math.min(o, u);
if (s == r) return g;
for (var _ = 0, m = 1; ;) {
var b = s.substring(g - m), E = r.indexOf(b);
if (-1 == E) return _;
m += E;
if (0 == E || s.substring(g - m) == r.substring(0, m)) {
_ = m;
m++;
}
}
};
diff_match_patch2.prototype.diff_halfMatch_ = function(s, r) {
if (this.Diff_Timeout <= 0) return null;
var o = s.length > r.length ? s : r, u = s.length > r.length ? r : s;
if (o.length < 4 || 2 * u.length < o.length) return null;
var g = this;
function diff_halfMatchI_(s, r, o) {
for (var u, _, m, b, E = s.substring(o, o + Math.floor(s.length / 4)), w = -1, S = ""; -1 != (w = r.indexOf(E, w + 1)); ) {
var L = g.diff_commonPrefix(s.substring(o), r.substring(w)), O = g.diff_commonSuffix(s.substring(0, o), r.substring(0, w));
if (S.length < O + L) {
S = r.substring(w - O, w) + r.substring(w, w + L);
u = s.substring(0, o - O);
_ = s.substring(o + L);
m = r.substring(0, w - O);
b = r.substring(w + L);
}
}
if (2 * S.length >= s.length) return [ u, _, m, b, S ]; else return null;
}
var _, m, b, E, w, S = diff_halfMatchI_(o, u, Math.ceil(o.length / 4)), L = diff_halfMatchI_(o, u, Math.ceil(o.length / 2));
if (!S && !L) return null; else if (!L) _ = S; else if (!S) _ = L; else _ = S[4].length > L[4].length ? S : L;
if (s.length > r.length) {
m = _[0];
b = _[1];
E = _[2];
w = _[3];
} else {
E = _[0];
w = _[1];
m = _[2];
b = _[3];
}
return [ m, b, E, w, _[4] ];
};
diff_match_patch2.prototype.diff_cleanupSemantic = function(s) {
for (var r = false, u = [], g = 0, _ = null, m = 0, b = 0, E = 0, w = 0, S = 0; m < s.length; ) {
if (0 == s[m][0]) {
u[g++] = m;
b = w;
E = S;
w = 0;
S = 0;
_ = s[m][1];
} else {
if (1 == s[m][0]) w += s[m][1].length; else S += s[m][1].length;
if (_ && _.length <= Math.max(b, E) && _.length <= Math.max(w, S)) {
s.splice(u[g - 1], 0, new diff_match_patch2.Diff(o, _));
s[u[g - 1] + 1][0] = 1;
g--;
m = --g > 0 ? u[g - 1] : -1;
b = 0;
E = 0;
w = 0;
S = 0;
_ = null;
r = true;
}
}
m++;
}
if (r) this.diff_cleanupMerge(s);
this.diff_cleanupSemanticLossless(s);
m = 1;
for (;m < s.length; ) {
if (s[m - 1][0] == o && 1 == s[m][0]) {
var L = s[m - 1][1], O = s[m][1], D = this.diff_commonOverlap_(L, O), k = this.diff_commonOverlap_(O, L);
if (D >= k) {
if (D >= L.length / 2 || D >= O.length / 2) {
s.splice(m, 0, new diff_match_patch2.Diff(0, O.substring(0, D)));
s[m - 1][1] = L.substring(0, L.length - D);
s[m + 1][1] = O.substring(D);
m++;
}
} else if (k >= L.length / 2 || k >= O.length / 2) {
s.splice(m, 0, new diff_match_patch2.Diff(0, L.substring(0, k)));
s[m - 1][0] = 1;
s[m - 1][1] = O.substring(0, O.length - k);
s[m + 1][0] = o;
s[m + 1][1] = L.substring(k);
m++;
}
m++;
}
m++;
}
};
diff_match_patch2.prototype.diff_cleanupSemanticLossless = function(s) {
function diff_cleanupSemanticScore_(s, r) {
if (!s || !r) return 6;
var o = s.charAt(s.length - 1), u = r.charAt(0), g = o.match(diff_match_patch2.nonAlphaNumericRegex_), _ = u.match(diff_match_patch2.nonAlphaNumericRegex_), m = g && o.match(diff_match_patch2.whitespaceRegex_), b = _ && u.match(diff_match_patch2.whitespaceRegex_), E = m && o.match(diff_match_patch2.linebreakRegex_), w = b && u.match(diff_match_patch2.linebreakRegex_), S = E && s.match(diff_match_patch2.blanklineEndRegex_), L = w && r.match(diff_match_patch2.blanklineStartRegex_);
if (S || L) return 5; else if (E || w) return 4; else if (g && !m && b) return 3; else if (m || b) return 2; else if (g || _) return 1;
return 0;
}
for (var r = 1; r < s.length - 1; ) {
if (0 == s[r - 1][0] && 0 == s[r + 1][0]) {
var o = s[r - 1][1], u = s[r][1], g = s[r + 1][1], _ = this.diff_commonSuffix(o, u);
if (_) {
var m = u.substring(u.length - _);
o = o.substring(0, o.length - _);
u = m + u.substring(0, u.length - _);
g = m + g;
}
for (var b = o, E = u, w = g, S = diff_cleanupSemanticScore_(o, u) + diff_cleanupSemanticScore_(u, g); u.charAt(0) === g.charAt(0); ) {
o += u.charAt(0);
u = u.substring(1) + g.charAt(0);
g = g.substring(1);
var L = diff_cleanupSemanticScore_(o, u) + diff_cleanupSemanticScore_(u, g);
if (L >= S) {
S = L;
b = o;
E = u;
w = g;
}
}
if (s[r - 1][1] != b) {
if (b) s[r - 1][1] = b; else {
s.splice(r - 1, 1);
r--;
}
s[r][1] = E;
if (w) s[r + 1][1] = w; else {
s.splice(r + 1, 1);
r--;
}
}
}
r++;
}
};
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(s) {
for (var r = false, u = [], g = 0, _ = null, m = 0, b = false, E = false, w = false, S = false; m < s.length; ) {
if (0 == s[m][0]) {
if (s[m][1].length < this.Diff_EditCost && (w || S)) {
u[g++] = m;
b = w;
E = S;
_ = s[m][1];
} else {
g = 0;
_ = null;
}
w = S = false;
} else {
if (s[m][0] == o) S = true; else w = true;
if (_ && (b && E && w && S || _.length < this.Diff_EditCost / 2 && b + E + w + S == 3)) {
s.splice(u[g - 1], 0, new diff_match_patch2.Diff(o, _));
s[u[g - 1] + 1][0] = 1;
g--;
_ = null;
if (b && E) {
w = S = true;
g = 0;
} else {
m = --g > 0 ? u[g - 1] : -1;
w = S = false;
}
r = true;
}
}
m++;
}
if (r) this.diff_cleanupMerge(s);
};
diff_match_patch2.prototype.diff_cleanupMerge = function(s) {
s.push(new diff_match_patch2.Diff(0, ""));
for (var r, u = 0, g = 0, _ = 0, m = "", b = ""; u < s.length; ) switch (s[u][0]) {
case 1:
_++;
b += s[u][1];
u++;
break;
case o:
g++;
m += s[u][1];
u++;
break;
case 0:
if (g + _ > 1) {
if (0 !== g && 0 !== _) {
if (0 !== (r = this.diff_commonPrefix(b, m))) {
if (u - g - _ > 0 && 0 == s[u - g - _ - 1][0]) s[u - g - _ - 1][1] += b.substring(0, r); else {
s.splice(0, 0, new diff_match_patch2.Diff(0, b.substring(0, r)));
u++;
}
b = b.substring(r);
m = m.substring(r);
}
if (0 !== (r = this.diff_commonSuffix(b, m))) {
s[u][1] = b.substring(b.length - r) + s[u][1];
b = b.substring(0, b.length - r);
m = m.substring(0, m.length - r);
}
}
u -= g + _;
s.splice(u, g + _);
if (m.length) {
s.splice(u, 0, new diff_match_patch2.Diff(o, m));
u++;
}
if (b.length) {
s.splice(u, 0, new diff_match_patch2.Diff(1, b));
u++;
}
u++;
} else if (0 !== u && 0 == s[u - 1][0]) {
s[u - 1][1] += s[u][1];
s.splice(u, 1);
} else u++;
_ = 0;
g = 0;
m = "";
b = "";
break;
}
if ("" === s[s.length - 1][1]) s.pop();
var E = false;
u = 1;
for (;u < s.length - 1; ) {
if (0 == s[u - 1][0] && 0 == s[u + 1][0]) if (s[u][1].substring(s[u][1].length - s[u - 1][1].length) == s[u - 1][1]) {
s[u][1] = s[u - 1][1] + s[u][1].substring(0, s[u][1].length - s[u - 1][1].length);
s[u + 1][1] = s[u - 1][1] + s[u + 1][1];
s.splice(u - 1, 1);
E = true;
} else if (s[u][1].substring(0, s[u + 1][1].length) == s[u + 1][1]) {
s[u - 1][1] += s[u + 1][1];
s[u][1] = s[u][1].substring(s[u + 1][1].length) + s[u + 1][1];
s.splice(u + 1, 1);
E = true;
}
u++;
}
if (E) this.diff_cleanupMerge(s);
};
diff_match_patch2.prototype.diff_xIndex = function(s, r) {
var u, g = 0, _ = 0, m = 0, b = 0;
for (u = 0; u < s.length; u++) {
if (1 !== s[u][0]) g += s[u][1].length;
if (s[u][0] !== o) _ += s[u][1].length;
if (g > r) break;
m = g;
b = _;
}
if (s.length != u && s[u][0] === o) return b; else return b + (r - m);
};
diff_match_patch2.prototype.diff_prettyHtml = function(s) {
for (var r = [], u = /&/g, g = //g, m = /\n/g, b = 0; b < s.length; b++) {
var E = s[b][0], w = s[b][1].replace(u, "&").replace(g, "<").replace(_, ">").replace(m, "¶
");
switch (E) {
case 1:
r[b] = '' + w + "";
break;
case o:
r[b] = '' + w + "";
break;
case 0:
r[b] = "" + w + "";
break;
}
}
return r.join("");
};
diff_match_patch2.prototype.diff_text1 = function(s) {
for (var r = [], o = 0; o < s.length; o++) if (1 !== s[o][0]) r[o] = s[o][1];
return r.join("");
};
diff_match_patch2.prototype.diff_text2 = function(s) {
for (var r = [], u = 0; u < s.length; u++) if (s[u][0] !== o) r[u] = s[u][1];
return r.join("");
};
diff_match_patch2.prototype.diff_levenshtein = function(s) {
for (var r = 0, u = 0, g = 0, _ = 0; _ < s.length; _++) {
var m = s[_][0], b = s[_][1];
switch (m) {
case 1:
u += b.length;
break;
case o:
g += b.length;
break;
case 0:
r += Math.max(u, g);
u = 0;
g = 0;
break;
}
}
return r += Math.max(u, g);
};
diff_match_patch2.prototype.diff_toDelta = function(s) {
for (var r = [], u = 0; u < s.length; u++) switch (s[u][0]) {
case 1:
r[u] = "+" + encodeURI(s[u][1]);
break;
case o:
r[u] = "-" + s[u][1].length;
break;
case 0:
r[u] = "=" + s[u][1].length;
break;
}
return r.join("\t").replace(/%20/g, " ");
};
diff_match_patch2.prototype.diff_fromDelta = function(s, r) {
for (var u = [], g = 0, _ = 0, m = r.split(/\t/g), b = 0; b < m.length; b++) {
var E = m[b].substring(1);
switch (m[b].charAt(0)) {
case "+":
try {
u[g++] = new diff_match_patch2.Diff(1, decodeURI(E));
} catch (s) {
throw new Error("Illegal escape in diff_fromDelta: " + E);
}
break;
case "-":
case "=":
var w = parseInt(E, 10);
if (isNaN(w) || w < 0) throw new Error("Invalid number in diff_fromDelta: " + E);
var S = s.substring(_, _ += w);
if ("=" == m[b].charAt(0)) u[g++] = new diff_match_patch2.Diff(0, S); else u[g++] = new diff_match_patch2.Diff(o, S);
break;
default:
if (m[b]) throw new Error("Invalid diff operation in diff_fromDelta: " + m[b]);
}
}
if (_ != s.length) throw new Error("Delta length (" + _ + ") does not equal source text length (" + s.length + ").");
return u;
};
diff_match_patch2.prototype.match_main = function(s, r, o) {
if (null == s || null == r || null == o) throw new Error("Null input. (match_main)");
o = Math.max(0, Math.min(o, s.length));
if (s == r) return 0; else if (!s.length) return -1; else if (s.substring(o, o + r.length) == r) return o; else return this.match_bitap_(s, r, o);
};
diff_match_patch2.prototype.match_bitap_ = function(s, r, o) {
if (r.length > this.Match_MaxBits) throw new Error("Pattern too long for this browser.");
var u = this.match_alphabet_(r), g = this;
function match_bitapScore_(s, u) {
var _ = s / r.length, m = Math.abs(o - u);
if (!g.Match_Distance) return m ? 1 : _; else return _ + m / g.Match_Distance;
}
var _ = this.Match_Threshold, m = s.indexOf(r, o);
if (-1 != m) {
_ = Math.min(match_bitapScore_(0, m), _);
if (-1 != (m = s.lastIndexOf(r, o + r.length))) _ = Math.min(match_bitapScore_(0, m), _);
}
var b, E, w = 1 << r.length - 1;
m = -1;
for (var S, L = r.length + s.length, O = 0; O < r.length; O++) {
b = 0;
E = L;
for (;b < E; ) {
if (match_bitapScore_(O, o + E) <= _) b = E; else L = E;
E = Math.floor((L - b) / 2 + b);
}
L = E;
var D = Math.max(1, o - E + 1), k = Math.min(o + E, s.length) + r.length, C = Array(k + 2);
C[k + 1] = (1 << O) - 1;
for (var T = k; T >= D; T--) {
var I = u[s.charAt(T - 1)];
if (0 === O) C[T] = (C[T + 1] << 1 | 1) & I; else C[T] = (C[T + 1] << 1 | 1) & I | (S[T + 1] | S[T]) << 1 | 1 | S[T + 1];
if (C[T] & w) {
var A = match_bitapScore_(O, T - 1);
if (A <= _) {
_ = A;
if ((m = T - 1) > o) D = Math.max(1, 2 * o - m); else break;
}
}
}
if (match_bitapScore_(O + 1, o) > _) break;
S = C;
}
return m;
};
diff_match_patch2.prototype.match_alphabet_ = function(s) {
for (var r = {}, o = 0; o < s.length; o++) r[s.charAt(o)] = 0;
for (o = 0; o < s.length; o++) r[s.charAt(o)] |= 1 << s.length - o - 1;
return r;
};
diff_match_patch2.prototype.patch_addContext_ = function(s, r) {
if (0 != r.length) {
if (null === s.start2) throw Error("patch not initialized");
for (var o = r.substring(s.start2, s.start2 + s.length1), u = 0; r.indexOf(o) != r.lastIndexOf(o) && o.length < this.Match_MaxBits - this.Patch_Margin - this.Patch_Margin; ) {
u += this.Patch_Margin;
o = r.substring(s.start2 - u, s.start2 + s.length1 + u);
}
u += this.Patch_Margin;
var g = r.substring(s.start2 - u, s.start2);
if (g) s.diffs.unshift(new diff_match_patch2.Diff(0, g));
var _ = r.substring(s.start2 + s.length1, s.start2 + s.length1 + u);
if (_) s.diffs.push(new diff_match_patch2.Diff(0, _));
s.start1 -= g.length;
s.start2 -= g.length;
s.length1 += g.length + _.length;
s.length2 += g.length + _.length;
}
};
diff_match_patch2.prototype.patch_make = function(s, r, u) {
var g, _;
if ("string" == typeof s && "string" == typeof r && "undefined" == typeof u) {
g = s;
if ((_ = this.diff_main(g, r, true)).length > 2) {
this.diff_cleanupSemantic(_);
this.diff_cleanupEfficiency(_);
}
} else if (s && "object" == typeof s && "undefined" == typeof r && "undefined" == typeof u) {
_ = s;
g = this.diff_text1(_);
} else if ("string" == typeof s && r && "object" == typeof r && "undefined" == typeof u) {
g = s;
_ = r;
} else if ("string" == typeof s && "string" == typeof r && u && "object" == typeof u) {
g = s;
_ = u;
} else throw new Error("Unknown call format to patch_make.");
if (0 === _.length) return [];
for (var m = [], b = new diff_match_patch2.patch_obj, E = 0, w = 0, S = 0, L = g, O = g, D = 0; D < _.length; D++) {
var k = _[D][0], C = _[D][1];
if (!E && 0 !== k) {
b.start1 = w;
b.start2 = S;
}
switch (k) {
case 1:
b.diffs[E++] = _[D];
b.length2 += C.length;
O = O.substring(0, S) + C + O.substring(S);
break;
case o:
b.length1 += C.length;
b.diffs[E++] = _[D];
O = O.substring(0, S) + O.substring(S + C.length);
break;
case 0:
if (C.length <= 2 * this.Patch_Margin && E && _.length != D + 1) {
b.diffs[E++] = _[D];
b.length1 += C.length;
b.length2 += C.length;
} else if (C.length >= 2 * this.Patch_Margin) if (E) {
this.patch_addContext_(b, L);
m.push(b);
b = new diff_match_patch2.patch_obj;
E = 0;
L = O;
w = S;
}
break;
}
if (1 !== k) w += C.length;
if (k !== o) S += C.length;
}
if (E) {
this.patch_addContext_(b, L);
m.push(b);
}
return m;
};
diff_match_patch2.prototype.patch_deepCopy = function(s) {
for (var r = [], o = 0; o < s.length; o++) {
var u = s[o], g = new diff_match_patch2.patch_obj;
g.diffs = [];
for (var _ = 0; _ < u.diffs.length; _++) g.diffs[_] = new diff_match_patch2.Diff(u.diffs[_][0], u.diffs[_][1]);
g.start1 = u.start1;
g.start2 = u.start2;
g.length1 = u.length1;
g.length2 = u.length2;
r[o] = g;
}
return r;
};
diff_match_patch2.prototype.patch_apply = function(s, r) {
if (0 == s.length) return [ r, [] ];
s = this.patch_deepCopy(s);
var u = this.patch_addPadding(s);
r = u + r + u;
this.patch_splitMax(s);
for (var g = 0, _ = [], m = 0; m < s.length; m++) {
var b, E = s[m].start2 + g, w = this.diff_text1(s[m].diffs), S = -1;
if (w.length > this.Match_MaxBits) {
if (-1 != (b = this.match_main(r, w.substring(0, this.Match_MaxBits), E))) if (-1 == (S = this.match_main(r, w.substring(w.length - this.Match_MaxBits), E + w.length - this.Match_MaxBits)) || b >= S) b = -1;
} else b = this.match_main(r, w, E);
if (-1 == b) {
_[m] = false;
g -= s[m].length2 - s[m].length1;
} else {
_[m] = true;
g = b - E;
var L;
if (-1 == S) L = r.substring(b, b + w.length); else L = r.substring(b, S + this.Match_MaxBits);
if (w == L) r = r.substring(0, b) + this.diff_text2(s[m].diffs) + r.substring(b + w.length); else {
var O = this.diff_main(w, L, false);
if (w.length > this.Match_MaxBits && this.diff_levenshtein(O) / w.length > this.Patch_DeleteThreshold) _[m] = false; else {
this.diff_cleanupSemanticLossless(O);
for (var D, k = 0, C = 0; C < s[m].diffs.length; C++) {
var T = s[m].diffs[C];
if (0 !== T[0]) D = this.diff_xIndex(O, k);
if (1 === T[0]) r = r.substring(0, b + D) + T[1] + r.substring(b + D); else if (T[0] === o) r = r.substring(0, b + D) + r.substring(b + this.diff_xIndex(O, k + T[1].length));
if (T[0] !== o) k += T[1].length;
}
}
}
}
}
return [ r = r.substring(u.length, r.length - u.length), _ ];
};
diff_match_patch2.prototype.patch_addPadding = function(s) {
for (var r = this.Patch_Margin, o = "", u = 1; u <= r; u++) o += String.fromCharCode(u);
for (u = 0; u < s.length; u++) {
s[u].start1 += r;
s[u].start2 += r;
}
var g = s[0], _ = g.diffs;
if (0 == _.length || 0 != _[0][0]) {
_.unshift(new diff_match_patch2.Diff(0, o));
g.start1 -= r;
g.start2 -= r;
g.length1 += r;
g.length2 += r;
} else if (r > _[0][1].length) {
var m = r - _[0][1].length;
_[0][1] = o.substring(_[0][1].length) + _[0][1];
g.start1 -= m;
g.start2 -= m;
g.length1 += m;
g.length2 += m;
}
if (0 == (_ = (g = s[s.length - 1]).diffs).length || 0 != _[_.length - 1][0]) {
_.push(new diff_match_patch2.Diff(0, o));
g.length1 += r;
g.length2 += r;
} else if (r > _[_.length - 1][1].length) {
m = r - _[_.length - 1][1].length;
_[_.length - 1][1] += o.substring(0, m);
g.length1 += m;
g.length2 += m;
}
return o;
};
diff_match_patch2.prototype.patch_splitMax = function(s) {
for (var r = this.Match_MaxBits, u = 0; u < s.length; u++) if (!(s[u].length1 <= r)) {
var g = s[u];
s.splice(u--, 1);
for (var _ = g.start1, m = g.start2, b = ""; 0 !== g.diffs.length; ) {
var E = new diff_match_patch2.patch_obj, w = true;
E.start1 = _ - b.length;
E.start2 = m - b.length;
if ("" !== b) {
E.length1 = E.length2 = b.length;
E.diffs.push(new diff_match_patch2.Diff(0, b));
}
for (;0 !== g.diffs.length && E.length1 < r - this.Patch_Margin; ) {
var S = g.diffs[0][0], L = g.diffs[0][1];
if (1 === S) {
E.length2 += L.length;
m += L.length;
E.diffs.push(g.diffs.shift());
w = false;
} else if (S === o && 1 == E.diffs.length && 0 == E.diffs[0][0] && L.length > 2 * r) {
E.length1 += L.length;
_ += L.length;
w = false;
E.diffs.push(new diff_match_patch2.Diff(S, L));
g.diffs.shift();
} else {
L = L.substring(0, r - E.length1 - this.Patch_Margin);
E.length1 += L.length;
_ += L.length;
if (0 === S) {
E.length2 += L.length;
m += L.length;
} else w = false;
E.diffs.push(new diff_match_patch2.Diff(S, L));
if (L == g.diffs[0][1]) g.diffs.shift(); else g.diffs[0][1] = g.diffs[0][1].substring(L.length);
}
}
b = (b = this.diff_text2(E.diffs)).substring(b.length - this.Patch_Margin);
var O = this.diff_text1(g.diffs).substring(0, this.Patch_Margin);
if ("" !== O) {
E.length1 += O.length;
E.length2 += O.length;
if (0 !== E.diffs.length && 0 === E.diffs[E.diffs.length - 1][0]) E.diffs[E.diffs.length - 1][1] += O; else E.diffs.push(new diff_match_patch2.Diff(0, O));
}
if (!w) s.splice(++u, 0, E);
}
}
};
diff_match_patch2.prototype.patch_toText = function(s) {
for (var r = [], o = 0; o < s.length; o++) r[o] = s[o];
return r.join("");
};
diff_match_patch2.prototype.patch_fromText = function(s) {
var r = [];
if (!s) return r;
for (var u = s.split("\n"), g = 0, _ = /^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$/; g < u.length; ) {
var m = u[g].match(_);
if (!m) throw new Error("Invalid patch string: " + u[g]);
var b = new diff_match_patch2.patch_obj;
r.push(b);
b.start1 = parseInt(m[1], 10);
if ("" === m[2]) {
b.start1--;
b.length1 = 1;
} else if ("0" == m[2]) b.length1 = 0; else {
b.start1--;
b.length1 = parseInt(m[2], 10);
}
b.start2 = parseInt(m[3], 10);
if ("" === m[4]) {
b.start2--;
b.length2 = 1;
} else if ("0" == m[4]) b.length2 = 0; else {
b.start2--;
b.length2 = parseInt(m[4], 10);
}
g++;
for (;g < u.length; ) {
var E = u[g].charAt(0);
try {
var w = decodeURI(u[g].substring(1));
} catch (s) {
throw new Error("Illegal escape in patch_fromText: " + w);
}
if ("-" == E) b.diffs.push(new diff_match_patch2.Diff(o, w)); else if ("+" == E) b.diffs.push(new diff_match_patch2.Diff(1, w)); else if (" " == E) b.diffs.push(new diff_match_patch2.Diff(0, w)); else if ("@" == E) break; else if ("" === E) ; else throw new Error('Invalid patch mode "' + E + '" in: ' + w);
g++;
}
}
return r;
};
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 s, r;
if (0 === this.length1) s = this.start1 + ",0"; else if (1 == this.length1) s = this.start1 + 1; else s = this.start1 + 1 + "," + this.length1;
if (0 === this.length2) r = this.start2 + ",0"; else if (1 == this.length2) r = this.start2 + 1; else r = this.start2 + 1 + "," + this.length2;
for (var u, g = [ "@@ -" + s + " +" + r + " @@\n" ], _ = 0; _ < this.diffs.length; _++) {
switch (this.diffs[_][0]) {
case 1:
u = "+";
break;
case o:
u = "-";
break;
case 0:
u = " ";
break;
}
g[_ + 1] = u + encodeURI(this.diffs[_][1]) + "\n";
}
return g.join("").replace(/%20/g, " ");
};
r.exports = diff_match_patch2;
r.exports["diff_match_patch"] = diff_match_patch2;
r.exports["DIFF_DELETE"] = o;
r.exports["DIFF_INSERT"] = 1;
r.exports["DIFF_EQUAL"] = 0;
}
}), require_balanced_match = __commonJS({
"node_modules/balanced-match/index.js"(s, r) {
"use strict";
r.exports = balanced;
function balanced(s, r, o) {
if (s instanceof RegExp) s = maybeMatch(s, o);
if (r instanceof RegExp) r = maybeMatch(r, o);
var u = range2(s, r, o);
return u && {
start: u[0],
end: u[1],
pre: o.slice(0, u[0]),
body: o.slice(u[0] + s.length, u[1]),
post: o.slice(u[1] + r.length)
};
}
function maybeMatch(s, r) {
var o = r.match(s);
return o ? o[0] : null;
}
balanced.range = range2;
function range2(s, r, o) {
var u, g, _, m, b, E = o.indexOf(s), w = o.indexOf(r, E + 1), S = E;
if (E >= 0 && w > 0) {
if (s === r) return [ E, w ];
u = [];
_ = o.length;
for (;S >= 0 && !b; ) {
if (S == E) {
u.push(S);
E = o.indexOf(s, S + 1);
} else if (1 == u.length) b = [ u.pop(), w ]; else {
if ((g = u.pop()) < _) {
_ = g;
m = w;
}
w = o.indexOf(r, S + 1);
}
S = E < w && E >= 0 ? E : w;
}
if (u.length) b = [ _, m ];
}
return b;
}
}
}), require_brace_expansion = __commonJS({
"node_modules/brace-expansion/index.js"(s, r) {
var o = require_balanced_match();
r.exports = function expandTop(s) {
if (!s) return [];
if ("{}" === s.substr(0, 2)) s = "\\{\\}" + s.substr(2);
return expand2(function escapeBraces(s) {
return s.split("\\\\").join(u).split("\\{").join(g).split("\\}").join(_).split("\\,").join(m).split("\\.").join(b);
}(s), true).map(unescapeBraces);
};
var u = "\0SLASH" + Math.random() + "\0", g = "\0OPEN" + Math.random() + "\0", _ = "\0CLOSE" + Math.random() + "\0", m = "\0COMMA" + Math.random() + "\0", b = "\0PERIOD" + Math.random() + "\0";
function numeric(s) {
return parseInt(s, 10) == s ? parseInt(s, 10) : s.charCodeAt(0);
}
function unescapeBraces(s) {
return s.split(u).join("\\").split(g).join("{").split(_).join("}").split(m).join(",").split(b).join(".");
}
function parseCommaParts(s) {
if (!s) return [ "" ];
var r = [], u = o("{", "}", s);
if (!u) return s.split(",");
var g = u.pre, _ = u.body, m = u.post, b = g.split(",");
b[b.length - 1] += "{" + _ + "}";
var E = parseCommaParts(m);
if (m.length) {
b[b.length - 1] += E.shift();
b.push.apply(b, E);
}
r.push.apply(r, b);
return r;
}
function embrace(s) {
return "{" + s + "}";
}
function isPadded(s) {
return /^-?0\d/.test(s);
}
function lte(s, r) {
return s <= r;
}
function gte(s, r) {
return s >= r;
}
function expand2(s, r) {
var u = [], g = o("{", "}", s);
if (!g) return [ s ];
var m = g.pre, b = g.post.length ? expand2(g.post, false) : [ "" ];
if (/\$$/.test(g.pre)) for (var E = 0; E < b.length; E++) {
var w = m + "{" + g.body + "}" + b[E];
u.push(w);
} else {
var S, L, O = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(g.body), D = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(g.body), k = O || D, C = g.body.indexOf(",") >= 0;
if (!k && !C) if (g.post.match(/,.*\}/)) return expand2(s = g.pre + "{" + g.body + _ + g.post); else return [ s ];
if (k) S = g.body.split(/\.\./); else if (1 === (S = parseCommaParts(g.body)).length) if (1 === (S = expand2(S[0], false).map(embrace)).length) return b.map((function(s) {
return g.pre + S[0] + s;
}));
if (k) {
var T = numeric(S[0]), I = numeric(S[1]), A = Math.max(S[0].length, S[1].length), R = 3 == S.length ? Math.abs(numeric(S[2])) : 1, x = lte;
if (I < T) {
R *= -1;
x = gte;
}
var P = S.some(isPadded);
L = [];
for (var N = T; x(N, I); N += R) {
var B;
if (D) {
if ("\\" === (B = String.fromCharCode(N))) B = "";
} else {
B = String(N);
if (P) {
var F = A - B.length;
if (F > 0) {
var M = new Array(F + 1).join("0");
if (N < 0) B = "-" + M + B.slice(1); else B = M + B;
}
}
}
L.push(B);
}
} else {
L = [];
for (var V = 0; V < S.length; V++) L.push.apply(L, expand2(S[V], false));
}
for (V = 0; V < L.length; V++) for (E = 0; E < b.length; E++) {
w = m + L[V] + b[E];
if (!r || k || w) u.push(w);
}
}
return u;
}
}
}), require_nextTick = __commonJS({
"(disabled):node_modules/immediate/lib/nextTick"() {}
}), require_queueMicrotask = __commonJS({
"node_modules/immediate/lib/queueMicrotask.js"(s) {
"use strict";
s.test = function() {
return "function" == typeof window.queueMicrotask;
};
s.install = function(s) {
return function() {
window.queueMicrotask(s);
};
};
}
}), require_mutation = __commonJS({
"node_modules/immediate/lib/mutation.js"(s) {
"use strict";
var r = window.MutationObserver || window.WebKitMutationObserver;
s.test = function() {
return r;
};
s.install = function(s) {
var o = 0, u = new r(s), g = window.document.createTextNode("");
u.observe(g, {
characterData: true
});
return function() {
g.data = o = ++o % 2;
};
};
}
}), require_messageChannel = __commonJS({
"node_modules/immediate/lib/messageChannel.js"(s) {
"use strict";
s.test = function() {
if (window.setImmediate) return false; else return "undefined" != typeof window.MessageChannel;
};
s.install = function(s) {
var r = new window.MessageChannel;
r.port1.onmessage = s;
return function() {
r.port2.postMessage(0);
};
};
}
}), require_stateChange = __commonJS({
"node_modules/immediate/lib/stateChange.js"(s) {
"use strict";
s.test = function() {
return "document" in window && "onreadystatechange" in window.document.createElement("script");
};
s.install = function(s) {
return function() {
var r = window.document.createElement("script");
r.onreadystatechange = function() {
s();
r.onreadystatechange = null;
r.parentNode.removeChild(r);
r = null;
};
window.document.documentElement.appendChild(r);
return s;
};
};
}
}), require_timeout = __commonJS({
"node_modules/immediate/lib/timeout.js"(s) {
"use strict";
s.test = function() {
return true;
};
s.install = function(s) {
return function() {
setTimeout(s, 0);
};
};
}
}), require_lib = __commonJS({
"node_modules/immediate/lib/index.js"(s, r) {
"use strict";
var o, u, g, _ = [ require_nextTick(), require_queueMicrotask(), require_mutation(), require_messageChannel(), require_stateChange(), require_timeout() ], m = -1, b = [], E = false;
function cleanUpNextTick() {
if (o && u) {
o = false;
if (u.length) b = u.concat(b); else m = -1;
if (b.length) nextTick();
}
}
function nextTick() {
if (!o) {
E = false;
o = true;
for (var s = b.length, r = setTimeout(cleanUpNextTick); s; ) {
u = b;
b = [];
for (;u && ++m < s; ) u[m].run();
m = -1;
s = b.length;
}
u = null;
m = -1;
o = false;
clearTimeout(r);
}
}
for (var w = -1, S = _.length; ++w < S; ) if (_[w] && _[w].test && _[w].test()) {
g = _[w].install(nextTick);
break;
}
function Item(s, r) {
this.fun = s;
this.array = r;
}
Item.prototype.run = function() {
var s = this.fun, r = this.array;
switch (r.length) {
case 0:
return s();
case 1:
return s(r[0]);
case 2:
return s(r[0], r[1]);
case 3:
return s(r[0], r[1], r[2]);
default:
return s.apply(null, r);
}
};
r.exports = function immediate2(s) {
var r = new Array(arguments.length - 1);
if (arguments.length > 1) for (var u = 1; u < arguments.length; u++) r[u - 1] = arguments[u];
b.push(new Item(s, r));
if (!E && !o) {
E = true;
g();
}
};
}
}), require_events = __commonJS({
"node_modules/events/events.js"(s, r) {
"use strict";
var o, u = "object" == typeof Reflect ? Reflect : null, g = u && "function" == typeof u.apply ? u.apply : function ReflectApply2(s, r, o) {
return Function.prototype.apply.call(s, r, o);
};
if (u && "function" == typeof u.ownKeys) o = u.ownKeys; else if (Object.getOwnPropertySymbols) o = function ReflectOwnKeys2(s) {
return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s));
}; else o = function ReflectOwnKeys2(s) {
return Object.getOwnPropertyNames(s);
};
var _ = Number.isNaN || function NumberIsNaN2(s) {
return s != s;
};
function EventEmitter2() {
EventEmitter2.init.call(this);
}
r.exports = EventEmitter2;
r.exports.once = function once2(s, r) {
return new Promise((function(o, u) {
function errorListener(o) {
s.removeListener(r, resolver);
u(o);
}
function resolver() {
if ("function" == typeof s.removeListener) s.removeListener("error", errorListener);
o([].slice.call(arguments));
}
eventTargetAgnosticAddListener(s, r, resolver, {
once: true
});
if ("error" !== r) (function addErrorHandlerIfEventEmitter(s, r, o) {
if ("function" == typeof s.on) eventTargetAgnosticAddListener(s, "error", r, o);
})(s, errorListener, {
once: true
});
}));
};
EventEmitter2.EventEmitter = EventEmitter2;
EventEmitter2.prototype._events = void 0;
EventEmitter2.prototype._eventsCount = 0;
EventEmitter2.prototype._maxListeners = void 0;
var m = 10;
function checkListener(s) {
if ("function" != typeof s) throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof s);
}
Object.defineProperty(EventEmitter2, "defaultMaxListeners", {
enumerable: true,
get: function() {
return m;
},
set: function(s) {
if ("number" != typeof s || s < 0 || _(s)) throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + s + ".");
m = s;
}
});
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(s) {
if ("number" != typeof s || s < 0 || _(s)) throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + s + ".");
this._maxListeners = s;
return this;
};
function _getMaxListeners(s) {
if (void 0 === s._maxListeners) return EventEmitter2.defaultMaxListeners; else return s._maxListeners;
}
EventEmitter2.prototype.getMaxListeners = function getMaxListeners() {
return _getMaxListeners(this);
};
EventEmitter2.prototype.emit = function emit2(s) {
for (var r = [], o = 1; o < arguments.length; o++) r.push(arguments[o]);
var u = "error" === s, _ = this._events;
if (void 0 !== _) u = u && void 0 === _.error; else if (!u) return false;
if (u) {
var m;
if (r.length > 0) m = r[0];
if (m instanceof Error) throw m;
var b = new Error("Unhandled error." + (m ? " (" + m.message + ")" : ""));
b.context = m;
throw b;
}
var E = _[s];
if (void 0 === E) return false;
if ("function" == typeof E) g(E, this, r); else {
var w = E.length, S = arrayClone(E, w);
for (o = 0; o < w; ++o) g(S[o], this, r);
}
return true;
};
function _addListener(s, r, o, u) {
var g, _, m;
checkListener(o);
if (void 0 === (_ = s._events)) {
_ = s._events = Object.create(null);
s._eventsCount = 0;
} else {
if (void 0 !== _.newListener) {
s.emit("newListener", r, o.listener ? o.listener : o);
_ = s._events;
}
m = _[r];
}
if (void 0 === m) {
m = _[r] = o;
++s._eventsCount;
} else {
if ("function" == typeof m) m = _[r] = u ? [ o, m ] : [ m, o ]; else if (u) m.unshift(o); else m.push(o);
if ((g = _getMaxListeners(s)) > 0 && m.length > g && !m.warned) {
m.warned = true;
var b = new Error("Possible EventEmitter memory leak detected. " + m.length + " " + String(r) + " listeners added. Use emitter.setMaxListeners() to increase limit");
b.name = "MaxListenersExceededWarning";
b.emitter = s;
b.type = r;
b.count = m.length;
(function ProcessEmitWarning(s) {
if (console && console.warn) console.warn(s);
})(b);
}
}
return s;
}
EventEmitter2.prototype.addListener = function addListener(s, r) {
return _addListener(this, s, r, false);
};
EventEmitter2.prototype.on = EventEmitter2.prototype.addListener;
EventEmitter2.prototype.prependListener = function prependListener(s, r) {
return _addListener(this, s, r, 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(s, r, o) {
var u = {
fired: false,
wrapFn: void 0,
target: s,
type: r,
listener: o
}, g = onceWrapper.bind(u);
g.listener = o;
u.wrapFn = g;
return g;
}
EventEmitter2.prototype.once = function once3(s, r) {
checkListener(r);
this.on(s, _onceWrap(this, s, r));
return this;
};
EventEmitter2.prototype.prependOnceListener = function prependOnceListener(s, r) {
checkListener(r);
this.prependListener(s, _onceWrap(this, s, r));
return this;
};
EventEmitter2.prototype.removeListener = function removeListener(s, r) {
var o, u, g, _, m;
checkListener(r);
if (void 0 === (u = this._events)) return this;
if (void 0 === (o = u[s])) return this;
if (o === r || o.listener === r) if (0 == --this._eventsCount) this._events = Object.create(null); else {
delete u[s];
if (u.removeListener) this.emit("removeListener", s, o.listener || r);
} else if ("function" != typeof o) {
g = -1;
for (_ = o.length - 1; _ >= 0; _--) if (o[_] === r || o[_].listener === r) {
m = o[_].listener;
g = _;
break;
}
if (g < 0) return this;
if (0 === g) o.shift(); else (function spliceOne(s, r) {
for (;r + 1 < s.length; r++) s[r] = s[r + 1];
s.pop();
})(o, g);
if (1 === o.length) u[s] = o[0];
if (void 0 !== u.removeListener) this.emit("removeListener", s, m || r);
}
return this;
};
EventEmitter2.prototype.off = EventEmitter2.prototype.removeListener;
EventEmitter2.prototype.removeAllListeners = function removeAllListeners(s) {
var r, o, u;
if (void 0 === (o = this._events)) return this;
if (void 0 === o.removeListener) {
if (0 === arguments.length) {
this._events = Object.create(null);
this._eventsCount = 0;
} else if (void 0 !== o[s]) if (0 == --this._eventsCount) this._events = Object.create(null); else delete o[s];
return this;
}
if (0 === arguments.length) {
var g, _ = Object.keys(o);
for (u = 0; u < _.length; ++u) if ("removeListener" !== (g = _[u])) this.removeAllListeners(g);
this.removeAllListeners("removeListener");
this._events = Object.create(null);
this._eventsCount = 0;
return this;
}
if ("function" == typeof (r = o[s])) this.removeListener(s, r); else if (void 0 !== r) for (u = r.length - 1; u >= 0; u--) this.removeListener(s, r[u]);
return this;
};
function _listeners(s, r, o) {
var u = s._events;
if (void 0 === u) return [];
var g = u[r];
if (void 0 === g) return [];
if ("function" == typeof g) return o ? [ g.listener || g ] : [ g ]; else return o ? function unwrapListeners(s) {
for (var r = new Array(s.length), o = 0; o < r.length; ++o) r[o] = s[o].listener || s[o];
return r;
}(g) : arrayClone(g, g.length);
}
EventEmitter2.prototype.listeners = function listeners(s) {
return _listeners(this, s, true);
};
EventEmitter2.prototype.rawListeners = function rawListeners(s) {
return _listeners(this, s, false);
};
EventEmitter2.listenerCount = function(s, r) {
if ("function" == typeof s.listenerCount) return s.listenerCount(r); else return listenerCount2.call(s, r);
};
EventEmitter2.prototype.listenerCount = listenerCount2;
function listenerCount2(s) {
var r = this._events;
if (void 0 !== r) {
var o = r[s];
if ("function" == typeof o) return 1; else if (void 0 !== o) return o.length;
}
return 0;
}
EventEmitter2.prototype.eventNames = function eventNames() {
return this._eventsCount > 0 ? o(this._events) : [];
};
function arrayClone(s, r) {
for (var o = new Array(r), u = 0; u < r; ++u) o[u] = s[u];
return o;
}
function eventTargetAgnosticAddListener(s, r, o, u) {
if ("function" == typeof s.on) if (u.once) s.once(r, o); else s.on(r, o); else if ("function" == typeof s.addEventListener) s.addEventListener(r, (function wrapListener(g) {
if (u.once) s.removeEventListener(r, wrapListener);
o(g);
})); else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof s);
}
}
}), require_spark_md5 = __commonJS({
"node_modules/spark-md5/spark-md5.js"(s, r) {
(function(o) {
if ("object" == typeof s) r.exports = o(); else if ("function" == typeof define && define.amd) define(o); else {
var u;
try {
u = window;
} catch (s) {
u = self;
}
u.SparkMD5 = o();
}
})((function(s) {
"use strict";
var r = [ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" ];
function md5cycle(s, r) {
var o = s[0], u = s[1], g = s[2], _ = s[3];
u = ((u += ((g = ((g += ((_ = ((_ += ((o = ((o += (u & g | ~u & _) + r[0] - 680876936 | 0) << 7 | o >>> 25) + u | 0) & u | ~o & g) + r[1] - 389564586 | 0) << 12 | _ >>> 20) + o | 0) & o | ~_ & u) + r[2] + 606105819 | 0) << 17 | g >>> 15) + _ | 0) & _ | ~g & o) + r[3] - 1044525330 | 0) << 22 | u >>> 10) + g | 0;
u = ((u += ((g = ((g += ((_ = ((_ += ((o = ((o += (u & g | ~u & _) + r[4] - 176418897 | 0) << 7 | o >>> 25) + u | 0) & u | ~o & g) + r[5] + 1200080426 | 0) << 12 | _ >>> 20) + o | 0) & o | ~_ & u) + r[6] - 1473231341 | 0) << 17 | g >>> 15) + _ | 0) & _ | ~g & o) + r[7] - 45705983 | 0) << 22 | u >>> 10) + g | 0;
u = ((u += ((g = ((g += ((_ = ((_ += ((o = ((o += (u & g | ~u & _) + r[8] + 1770035416 | 0) << 7 | o >>> 25) + u | 0) & u | ~o & g) + r[9] - 1958414417 | 0) << 12 | _ >>> 20) + o | 0) & o | ~_ & u) + r[10] - 42063 | 0) << 17 | g >>> 15) + _ | 0) & _ | ~g & o) + r[11] - 1990404162 | 0) << 22 | u >>> 10) + g | 0;
u = ((u += ((g = ((g += ((_ = ((_ += ((o = ((o += (u & g | ~u & _) + r[12] + 1804603682 | 0) << 7 | o >>> 25) + u | 0) & u | ~o & g) + r[13] - 40341101 | 0) << 12 | _ >>> 20) + o | 0) & o | ~_ & u) + r[14] - 1502002290 | 0) << 17 | g >>> 15) + _ | 0) & _ | ~g & o) + r[15] + 1236535329 | 0) << 22 | u >>> 10) + g | 0;
u = ((u += ((g = ((g += ((_ = ((_ += ((o = ((o += (u & _ | g & ~_) + r[1] - 165796510 | 0) << 5 | o >>> 27) + u | 0) & g | u & ~g) + r[6] - 1069501632 | 0) << 9 | _ >>> 23) + o | 0) & u | o & ~u) + r[11] + 643717713 | 0) << 14 | g >>> 18) + _ | 0) & o | _ & ~o) + r[0] - 373897302 | 0) << 20 | u >>> 12) + g | 0;
u = ((u += ((g = ((g += ((_ = ((_ += ((o = ((o += (u & _ | g & ~_) + r[5] - 701558691 | 0) << 5 | o >>> 27) + u | 0) & g | u & ~g) + r[10] + 38016083 | 0) << 9 | _ >>> 23) + o | 0) & u | o & ~u) + r[15] - 660478335 | 0) << 14 | g >>> 18) + _ | 0) & o | _ & ~o) + r[4] - 405537848 | 0) << 20 | u >>> 12) + g | 0;
u = ((u += ((g = ((g += ((_ = ((_ += ((o = ((o += (u & _ | g & ~_) + r[9] + 568446438 | 0) << 5 | o >>> 27) + u | 0) & g | u & ~g) + r[14] - 1019803690 | 0) << 9 | _ >>> 23) + o | 0) & u | o & ~u) + r[3] - 187363961 | 0) << 14 | g >>> 18) + _ | 0) & o | _ & ~o) + r[8] + 1163531501 | 0) << 20 | u >>> 12) + g | 0;
u = ((u += ((g = ((g += ((_ = ((_ += ((o = ((o += (u & _ | g & ~_) + r[13] - 1444681467 | 0) << 5 | o >>> 27) + u | 0) & g | u & ~g) + r[2] - 51403784 | 0) << 9 | _ >>> 23) + o | 0) & u | o & ~u) + r[7] + 1735328473 | 0) << 14 | g >>> 18) + _ | 0) & o | _ & ~o) + r[12] - 1926607734 | 0) << 20 | u >>> 12) + g | 0;
u = ((u += ((g = ((g += ((_ = ((_ += ((o = ((o += (u ^ g ^ _) + r[5] - 378558 | 0) << 4 | o >>> 28) + u | 0) ^ u ^ g) + r[8] - 2022574463 | 0) << 11 | _ >>> 21) + o | 0) ^ o ^ u) + r[11] + 1839030562 | 0) << 16 | g >>> 16) + _ | 0) ^ _ ^ o) + r[14] - 35309556 | 0) << 23 | u >>> 9) + g | 0;
u = ((u += ((g = ((g += ((_ = ((_ += ((o = ((o += (u ^ g ^ _) + r[1] - 1530992060 | 0) << 4 | o >>> 28) + u | 0) ^ u ^ g) + r[4] + 1272893353 | 0) << 11 | _ >>> 21) + o | 0) ^ o ^ u) + r[7] - 155497632 | 0) << 16 | g >>> 16) + _ | 0) ^ _ ^ o) + r[10] - 1094730640 | 0) << 23 | u >>> 9) + g | 0;
u = ((u += ((g = ((g += ((_ = ((_ += ((o = ((o += (u ^ g ^ _) + r[13] + 681279174 | 0) << 4 | o >>> 28) + u | 0) ^ u ^ g) + r[0] - 358537222 | 0) << 11 | _ >>> 21) + o | 0) ^ o ^ u) + r[3] - 722521979 | 0) << 16 | g >>> 16) + _ | 0) ^ _ ^ o) + r[6] + 76029189 | 0) << 23 | u >>> 9) + g | 0;
u = ((u += ((g = ((g += ((_ = ((_ += ((o = ((o += (u ^ g ^ _) + r[9] - 640364487 | 0) << 4 | o >>> 28) + u | 0) ^ u ^ g) + r[12] - 421815835 | 0) << 11 | _ >>> 21) + o | 0) ^ o ^ u) + r[15] + 530742520 | 0) << 16 | g >>> 16) + _ | 0) ^ _ ^ o) + r[2] - 995338651 | 0) << 23 | u >>> 9) + g | 0;
u = ((u += ((_ = ((_ += (u ^ ((o = ((o += (g ^ (u | ~_)) + r[0] - 198630844 | 0) << 6 | o >>> 26) + u | 0) | ~g)) + r[7] + 1126891415 | 0) << 10 | _ >>> 22) + o | 0) ^ ((g = ((g += (o ^ (_ | ~u)) + r[14] - 1416354905 | 0) << 15 | g >>> 17) + _ | 0) | ~o)) + r[5] - 57434055 | 0) << 21 | u >>> 11) + g | 0;
u = ((u += ((_ = ((_ += (u ^ ((o = ((o += (g ^ (u | ~_)) + r[12] + 1700485571 | 0) << 6 | o >>> 26) + u | 0) | ~g)) + r[3] - 1894986606 | 0) << 10 | _ >>> 22) + o | 0) ^ ((g = ((g += (o ^ (_ | ~u)) + r[10] - 1051523 | 0) << 15 | g >>> 17) + _ | 0) | ~o)) + r[1] - 2054922799 | 0) << 21 | u >>> 11) + g | 0;
u = ((u += ((_ = ((_ += (u ^ ((o = ((o += (g ^ (u | ~_)) + r[8] + 1873313359 | 0) << 6 | o >>> 26) + u | 0) | ~g)) + r[15] - 30611744 | 0) << 10 | _ >>> 22) + o | 0) ^ ((g = ((g += (o ^ (_ | ~u)) + r[6] - 1560198380 | 0) << 15 | g >>> 17) + _ | 0) | ~o)) + r[13] + 1309151649 | 0) << 21 | u >>> 11) + g | 0;
u = ((u += ((_ = ((_ += (u ^ ((o = ((o += (g ^ (u | ~_)) + r[4] - 145523070 | 0) << 6 | o >>> 26) + u | 0) | ~g)) + r[11] - 1120210379 | 0) << 10 | _ >>> 22) + o | 0) ^ ((g = ((g += (o ^ (_ | ~u)) + r[2] + 718787259 | 0) << 15 | g >>> 17) + _ | 0) | ~o)) + r[9] - 343485551 | 0) << 21 | u >>> 11) + g | 0;
s[0] = o + s[0] | 0;
s[1] = u + s[1] | 0;
s[2] = g + s[2] | 0;
s[3] = _ + s[3] | 0;
}
function md5blk(s) {
var r, o = [];
for (r = 0; r < 64; r += 4) o[r >> 2] = s.charCodeAt(r) + (s.charCodeAt(r + 1) << 8) + (s.charCodeAt(r + 2) << 16) + (s.charCodeAt(r + 3) << 24);
return o;
}
function md5blk_array(s) {
var r, o = [];
for (r = 0; r < 64; r += 4) o[r >> 2] = s[r] + (s[r + 1] << 8) + (s[r + 2] << 16) + (s[r + 3] << 24);
return o;
}
function md51(s) {
var r, o, u, g, _, m, b = s.length, E = [ 1732584193, -271733879, -1732584194, 271733878 ];
for (r = 64; r <= b; r += 64) md5cycle(E, md5blk(s.substring(r - 64, r)));
o = (s = s.substring(r - 64)).length;
u = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ];
for (r = 0; r < o; r += 1) u[r >> 2] |= s.charCodeAt(r) << (r % 4 << 3);
u[r >> 2] |= 128 << (r % 4 << 3);
if (r > 55) {
md5cycle(E, u);
for (r = 0; r < 16; r += 1) u[r] = 0;
}
g = (g = 8 * b).toString(16).match(/(.*?)(.{0,8})$/);
_ = parseInt(g[2], 16);
m = parseInt(g[1], 16) || 0;
u[14] = _;
u[15] = m;
md5cycle(E, u);
return E;
}
function rhex(s) {
var o, u = "";
for (o = 0; o < 4; o += 1) u += r[s >> 8 * o + 4 & 15] + r[s >> 8 * o & 15];
return u;
}
function hex(s) {
var r;
for (r = 0; r < s.length; r += 1) s[r] = rhex(s[r]);
return s.join("");
}
if ("5d41402abc4b2a76b9719d911017c592" !== hex(md51("hello"))) ;
if ("undefined" != typeof ArrayBuffer && !ArrayBuffer.prototype.slice) (function() {
function clamp(s, r) {
if ((s = 0 | s || 0) < 0) return Math.max(s + r, 0); else return Math.min(s, r);
}
ArrayBuffer.prototype.slice = function(r, o) {
var u, g, _, m, b = this.byteLength, E = clamp(r, b), w = b;
if (o !== s) w = clamp(o, b);
if (E > w) return new ArrayBuffer(0);
u = w - E;
g = new ArrayBuffer(u);
_ = new Uint8Array(g);
m = new Uint8Array(this, E, u);
_.set(m);
return g;
};
})();
function toUtf8(s) {
if (/[\u0080-\uFFFF]/.test(s)) s = unescape(encodeURIComponent(s));
return s;
}
function hexToBinaryString(s) {
var r, o = [], u = s.length;
for (r = 0; r < u - 1; r += 2) o.push(parseInt(s.substr(r, 2), 16));
return String.fromCharCode.apply(String, o);
}
function SparkMD5() {
this.reset();
}
SparkMD5.prototype.append = function(s) {
this.appendBinary(toUtf8(s));
return this;
};
SparkMD5.prototype.appendBinary = function(s) {
this._buff += s;
this._length += s.length;
var r, o = this._buff.length;
for (r = 64; r <= o; r += 64) md5cycle(this._hash, md5blk(this._buff.substring(r - 64, r)));
this._buff = this._buff.substring(r - 64);
return this;
};
SparkMD5.prototype.end = function(s) {
var r, o, u = this._buff, g = u.length, _ = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ];
for (r = 0; r < g; r += 1) _[r >> 2] |= u.charCodeAt(r) << (r % 4 << 3);
this._finish(_, g);
o = hex(this._hash);
if (s) o = hexToBinaryString(o);
this.reset();
return o;
};
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(s) {
this._buff = s.buff;
this._length = s.length;
this._hash = s.hash;
return this;
};
SparkMD5.prototype.destroy = function() {
delete this._hash;
delete this._buff;
delete this._length;
};
SparkMD5.prototype._finish = function(s, r) {
var o, u, g, _ = r;
s[_ >> 2] |= 128 << (_ % 4 << 3);
if (_ > 55) {
md5cycle(this._hash, s);
for (_ = 0; _ < 16; _ += 1) s[_] = 0;
}
o = (o = 8 * this._length).toString(16).match(/(.*?)(.{0,8})$/);
u = parseInt(o[2], 16);
g = parseInt(o[1], 16) || 0;
s[14] = u;
s[15] = g;
md5cycle(this._hash, s);
};
SparkMD5.hash = function(s, r) {
return SparkMD5.hashBinary(toUtf8(s), r);
};
SparkMD5.hashBinary = function(s, r) {
var o = hex(md51(s));
return r ? hexToBinaryString(o) : o;
};
SparkMD5.ArrayBuffer = function() {
this.reset();
};
SparkMD5.ArrayBuffer.prototype.append = function(s) {
var r, o = function concatenateArrayBuffers(s, r, o) {
var u = new Uint8Array(s.byteLength + r.byteLength);
u.set(new Uint8Array(s));
u.set(new Uint8Array(r), s.byteLength);
return o ? u : u.buffer;
}(this._buff.buffer, s, true), u = o.length;
this._length += s.byteLength;
for (r = 64; r <= u; r += 64) md5cycle(this._hash, md5blk_array(o.subarray(r - 64, r)));
this._buff = r - 64 < u ? new Uint8Array(o.buffer.slice(r - 64)) : new Uint8Array(0);
return this;
};
SparkMD5.ArrayBuffer.prototype.end = function(s) {
var r, o, u = this._buff, g = u.length, _ = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ];
for (r = 0; r < g; r += 1) _[r >> 2] |= u[r] << (r % 4 << 3);
this._finish(_, g);
o = hex(this._hash);
if (s) o = hexToBinaryString(o);
this.reset();
return o;
};
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 s = SparkMD5.prototype.getState.call(this);
s.buff = function arrayBuffer2Utf8Str(s) {
return String.fromCharCode.apply(null, new Uint8Array(s));
}(s.buff);
return s;
};
SparkMD5.ArrayBuffer.prototype.setState = function(s) {
s.buff = function utf8Str2ArrayBuffer(s, r) {
var o, u = s.length, g = new ArrayBuffer(u), _ = new Uint8Array(g);
for (o = 0; o < u; o += 1) _[o] = s.charCodeAt(o);
return r ? _ : g;
}(s.buff, true);
return SparkMD5.prototype.setState.call(this, s);
};
SparkMD5.ArrayBuffer.prototype.destroy = SparkMD5.prototype.destroy;
SparkMD5.ArrayBuffer.prototype._finish = SparkMD5.prototype._finish;
SparkMD5.ArrayBuffer.hash = function(s, r) {
var o = function md51_array(s) {
var r, o, u, g, _, m, b = s.length, E = [ 1732584193, -271733879, -1732584194, 271733878 ];
for (r = 64; r <= b; r += 64) md5cycle(E, md5blk_array(s.subarray(r - 64, r)));
o = (s = r - 64 < b ? s.subarray(r - 64) : new Uint8Array(0)).length;
u = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ];
for (r = 0; r < o; r += 1) u[r >> 2] |= s[r] << (r % 4 << 3);
u[r >> 2] |= 128 << (r % 4 << 3);
if (r > 55) {
md5cycle(E, u);
for (r = 0; r < 16; r += 1) u[r] = 0;
}
g = (g = 8 * b).toString(16).match(/(.*?)(.{0,8})$/);
_ = parseInt(g[2], 16);
m = parseInt(g[1], 16) || 0;
u[14] = _;
u[15] = m;
md5cycle(E, u);
return E;
}(new Uint8Array(s)), u = hex(o);
return r ? hexToBinaryString(u) : u;
};
return SparkMD5;
}));
}
}), require_vuvuzela = __commonJS({
"node_modules/vuvuzela/index.js"(s) {
"use strict";
s.stringify = function stringify3(s) {
var r = [];
r.push({
obj: s
});
for (var o, u, g, _, m, b, E, w, S, L, O = ""; o = r.pop(); ) {
u = o.obj;
O += o.prefix || "";
if (g = o.val || "") O += g; else if ("object" != typeof u) O += "undefined" == typeof u ? null : JSON.stringify(u); else if (null === u) O += "null"; else if (Array.isArray(u)) {
r.push({
val: "]"
});
for (_ = u.length - 1; _ >= 0; _--) {
m = 0 === _ ? "" : ",";
r.push({
obj: u[_],
prefix: m
});
}
r.push({
val: "["
});
} else {
b = [];
for (E in u) if (u.hasOwnProperty(E)) b.push(E);
r.push({
val: "}"
});
for (_ = b.length - 1; _ >= 0; _--) {
S = u[w = b[_]];
L = _ > 0 ? "," : "";
L += JSON.stringify(w) + ":";
r.push({
obj: S,
prefix: L
});
}
r.push({
val: "{"
});
}
}
return O;
};
function pop2(s, r, o) {
var u = o[o.length - 1];
if (s === u.element) {
o.pop();
u = o[o.length - 1];
}
var g = u.element, _ = u.index;
if (Array.isArray(g)) g.push(s); else if (_ === r.length - 2) g[r.pop()] = s; else r.push(s);
}
s.parse = function(s) {
for (var r, o, u, g, _, m, b, E, w, S = [], L = [], O = 0; ;) {
if ("}" === (r = s[O++]) || "]" === r || "undefined" == typeof r) if (1 === S.length) return S.pop(); else {
pop2(S.pop(), S, L);
continue;
}
switch (r) {
case " ":
case "\t":
case "\n":
case ":":
case ",":
break;
case "n":
O += 3;
pop2(null, S, L);
break;
case "t":
O += 3;
pop2(true, S, L);
break;
case "f":
O += 4;
pop2(false, S, L);
break;
case "0":
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "8":
case "9":
case "-":
o = "";
O--;
for (;;) {
u = s[O++];
if (/[\d\.\-e\+]/.test(u)) o += u; else {
O--;
break;
}
}
pop2(parseFloat(o), S, L);
break;
case '"':
g = "";
_ = void 0;
m = 0;
for (;'"' !== (b = s[O++]) || "\\" === _ && m % 2 == 1; ) {
g += b;
if ("\\" === (_ = b)) m++; else m = 0;
}
pop2(JSON.parse('"' + g + '"'), S, L);
break;
case "[":
E = {
element: [],
index: S.length
};
S.push(E.element);
L.push(E);
break;
case "{":
w = {
element: {},
index: S.length
};
S.push(w.element);
L.push(w);
break;
default:
throw new Error("unexpectedly reached end of input: " + r);
}
}
};
}
}), require_pouchdb_wrappers = __commonJS({
"node_modules/pouchdb-wrappers/index.js"(s, r) {
"use strict";
function replacementMethod(s, r) {
return function(...o) {
function doMethod() {
let u = null;
const g = "query" === r ? 1 : 0;
if (o.length > g && "function" == typeof o[o.length - 1]) u = o.pop();
let _ = s._originals[r].bind(s);
for (const o of s._handlers[r]) _ = o.bind(s, _);
const m = _(...o);
if (m.then && u) (function nodify(s, r) {
s.then(((...s) => {
r(null, ...s);
})).catch((s => {
r(s);
}));
})(m, u);
return m;
}
if ("changes" !== r && s.taskqueue && !s.taskqueue.isReady) return new Promise(((r, o) => {
s.taskqueue.addTask((s => {
if (s) o(s); else r();
}));
})).then(doMethod); else return doMethod();
};
}
var o = {
install: function installWrappers(s, r = {}) {
if (!s._originals || !s._handlers) {
s._originals = {};
s._handlers = {};
}
for (const [o, u] of Object.entries(r)) {
if (!(o in s)) throw new Error(`Method '${o}' does not exist on given base, so it cannot be wrapped.`);
if (!(o in s._originals)) s._originals[o] = s[o];
if (o in s._handlers) s._handlers[o].unshift(u); else {
s._handlers[o] = [ u ];
s[o] = replacementMethod(s, o);
}
}
},
uninstall: function uninstallWrappers(s, r) {
if (!s._originals || !s._handlers) throw new Error("No wrapper methods installed, so no methods can be uninstalled.");
for (const [o, u] of Object.entries(r)) {
const r = `Wrapper method for '${o}' not installed: ${u.toString()}`;
if (!(o in s._handlers)) throw new Error(r);
const g = s._handlers[o].indexOf(u);
if (-1 === g) throw new Error(r); else s._handlers[o].splice(g, 1);
}
}
};
try {
r.exports = o;
} catch (s) {}
try {
window.PouchDBWrappers = o;
} catch (s) {}
}
}), require_transform_pouch = __commonJS({
"node_modules/transform-pouch/index.js"(s, r) {
"use strict";
var o = require_pouchdb_wrappers();
function isntInternalKey(s) {
return "_" !== s[0];
}
function isUntransformable(s) {
if ("string" == typeof s._id && /^_local/.test(s._id)) return true;
if (s._deleted) return 0 === Object.keys(s).filter(isntInternalKey).length; else return false;
}
r.exports = {
transform: transform2,
filter: transform2
};
function transform2(s) {
const incoming = function(r) {
if (!isUntransformable(r) && s.incoming) return s.incoming(r); else return r;
}, outgoing = function(r) {
if (!isUntransformable(r) && s.outgoing) return s.outgoing(r); else return r;
}, r = {
async get(s, ...r) {
const o = await s(...r);
if (Array.isArray(o)) {
await Promise.all(o.map((async s => {
if (s.ok) s.ok = await outgoing(s.ok);
})));
return o;
} else return outgoing(o);
},
async bulkDocs(s, r, ...o) {
if (r.docs) r.docs = await Promise.all(r.docs.map(incoming)); else r = await Promise.all(r.map(incoming));
return s(r, ...o);
},
async allDocs(s, ...r) {
const o = await s(...r);
await Promise.all(o.rows.map((async s => {
if (s.doc) s.doc = await outgoing(s.doc);
})));
return o;
},
async bulkGet(s, ...r) {
const mapDoc = async s => {
if (s.ok) return {
ok: await outgoing(s.ok)
}; else return s;
};
let {results: o, ...u} = await s(...r);
o = await Promise.all(o.map((async s => {
const {id: r, docs: o} = s;
if (r && o && Array.isArray(o)) return {
id: r,
docs: await Promise.all(o.map(mapDoc))
}; else return s;
})));
return {
results: o,
...u
};
},
changes(s, ...r) {
async function modifyChange(s) {
if (s.doc) {
s.doc = await outgoing(s.doc);
return s;
}
return s;
}
async function modifyChanges(s) {
if (s.results) {
s.results = await Promise.all(s.results.map(modifyChange));
return s;
}
return s;
}
const o = s(...r), {on: u, then: g} = o;
return Object.assign(o, {
on(s, r) {
const g = r;
if ("change" === s) r = async s => {
g(await modifyChange(s));
}; else if ("complete" === s) r = async s => {
g(await modifyChanges(s));
};
return u.call(o, s, r);
},
then: (s, r) => g.call(o, modifyChanges).then(s, r)
});
}
};
if ("http" === this.type()) {
r.put = async function(s, r, ...o) {
return s(r = await incoming(r), ...o);
};
r.query = async function(s, ...r) {
const o = await s(...r);
await Promise.all(o.rows.map((async s => {
if (s.doc) s.doc = await outgoing(s.doc);
})));
return o;
};
}
o.install(this, r);
}
if ("undefined" != typeof window && window.PouchDB) window.PouchDB.plugin(s);
}
}), main_exports = {};
__export(main_exports, {
default: () => ObsidianLiveSyncPlugin
});
module.exports = __toCommonJS(main_exports);
var symbolFilePath = Symbol(), symbolFilePathWithPrefix = Symbol(), symbolId = Symbol(), 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, DEFAULT_SETTINGS = {
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,
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
}, PREFERRED_SETTING_CLOUDANT = {
syncMaxSizeInMB: 50,
customChunkSize: 0,
concurrencyOfReadChunksOnline: 100,
minimumIntervalOfReadChunksOnline: 333
}, PREFERRED_SETTING_SELF_HOSTED = {
...PREFERRED_SETTING_CLOUDANT,
customChunkSize: 50,
concurrencyOfReadChunksOnline: 30,
minimumIntervalOfReadChunksOnline: 25
}, 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:", FileWatchEventQueueMax = 10, configURIBase = "obsidian://setuplivesync?settings=", LEVEL_INFO = LOG_LEVEL_INFO, defaultLoggerEnv = {
minLogLevel: LOG_LEVEL_INFO
}, defaultLogger = function defaultLogger2(s, r = LEVEL_INFO, o) {
if (r < defaultLoggerEnv.minLogLevel) return;
const u = (new Date).toLocaleString(), g = "string" == typeof s ? s : s instanceof Error ? `${s.name}:${s.message}` : JSON.stringify(s, null, 2);
if (s instanceof Error) console.dir(s.stack);
const _ = `${u}\t${r}\t${g}`;
console.log(_);
}, _logger = defaultLogger;
function setGlobalLogFunction(s) {
_logger = s;
}
function Logger(s, r, o) {
_logger(s, r, o);
}
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(s, r, o = false) {
this.cache = new Map([]);
this.revCache = new Map([]);
this.maxCache = 200;
this.maxCachedLength = 5e7;
this.cachedLength = 0;
this.enableReversed = true;
this.maxCache = s || 200;
this.maxCachedLength = 1e6 * (r || 1);
this.enableReversed = !o;
Logger(`Cache initialized ${this.maxCache} / ${this.maxCachedLength}`, LOG_LEVEL_VERBOSE);
}
clear() {
this.cache.clear();
this.revCache.clear();
}
has(s) {
return this.cache.has(s);
}
get(s) {
const r = this.cache.get(s);
if (r) {
this.cache.delete(s);
this.cache.set(s, r);
if (this.enableReversed) {
this.revCache.delete(r);
this.revCache.set(r, s);
}
}
return r;
}
revGet(s) {
const r = this.revCache.get(s);
if (s) {
this.cache.delete(r);
this.revCache.delete(s);
this.cache.set(r, s);
this.revCache.set(s, r);
}
return r;
}
set(s, r) {
this.cache.set(s, r);
if (this.enableReversed) this.revCache.set(r, s);
this.cachedLength += `${r}`.length;
if (this.cache.size > this.maxCache || this.cachedLength > this.maxCachedLength) for (const [s, r] of this.cache) {
this.cache.delete(s);
if (this.enableReversed) this.revCache.delete(r);
this.cachedLength -= `${r}`.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 = s => {
if ("string" != typeof s) throw new TypeError("invalid pattern");
if (s.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 = s => s.replace(/[[\]\\-]/g, "\\$&"), regexpEscape = s => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), rangesToString = s => s.join(""), parseClass = (s, r) => {
const o = r;
if ("[" !== s.charAt(o)) throw new Error("not in a brace expression");
const u = [], g = [];
let _ = o + 1, m = false, b = false, E = false, w = false, S = o, L = "";
e: for (;_ < s.length; ) {
const r = s.charAt(_);
if ("!" !== r && "^" !== r || _ !== o + 1) {
if ("]" === r && m && !E) {
S = _ + 1;
break;
}
m = true;
if ("\\" === r) if (!E) {
E = true;
_++;
continue;
}
if ("[" === r && !E) for (const [r, [m, E, w]] of Object.entries(posixClasses)) if (s.startsWith(r, _)) {
if (L) return [ "$.", false, s.length - o, true ];
_ += r.length;
if (w) g.push(m); else u.push(m);
b = b || E;
continue e;
}
E = false;
if (!L) if (!s.startsWith("-]", _ + 1)) if (!s.startsWith("-", _ + 1)) {
u.push(braceEscape(r));
_++;
} else {
L = r;
_ += 2;
} else {
u.push(braceEscape(r + "-"));
_ += 2;
} else {
if (r > L) u.push(braceEscape(L) + "-" + braceEscape(r)); else if (r === L) u.push(braceEscape(r));
L = "";
_++;
}
} else {
w = true;
_++;
}
}
if (S < _) return [ "", false, 0, false ];
if (!u.length && !g.length) return [ "$.", false, s.length - o, true ];
if (0 === g.length && 1 === u.length && /^\\?.$/.test(u[0]) && !w) {
const s = 2 === u[0].length ? u[0].slice(-1) : u[0];
return [ regexpEscape(s), false, S - o, false ];
}
const O = "[" + (w ? "^" : "") + rangesToString(u) + "]", D = "[" + (w ? "" : "^") + rangesToString(g) + "]";
return [ u.length && g.length ? "(" + O + "|" + D + ")" : u.length ? O : D, b, S - o, true ];
}, unescape2 = (s, {windowsPathsNoEscape: r = false} = {}) => r ? s.replace(/\[([^\/\\])\]/g, "$1") : s.replace(/((?!\\).|^)\[([^\/\\])\]/g, "$1$2").replace(/\\([^\/])/g, "$1"), types = new Set([ "!", "?", "+", "*", "@" ]), isExtglobType = s => types.has(s), startNoTraversal = "(?!(?:^|/)\\.\\.?(?:$|/))", startNoDot = "(?!\\.)", addPatternStart = new Set([ "[", "." ]), justDots = new Set([ "..", "." ]), reSpecials = new Set("().*{}+?[]^$\\!"), regExpEscape = s => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), qmark = "[^/]", star = qmark + "*?", starNoEmpty = qmark + "+?", _AST = class _AST {
constructor(s, r, o = {}) {
__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 = s;
if (s) __privateSet(this, _hasMagic, true);
__privateSet(this, _parent, r);
__privateSet(this, _root, __privateGet(this, _parent) ? __privateGet(__privateGet(this, _parent), _root) : this);
__privateSet(this, _options, __privateGet(this, _root) === this ? o : __privateGet(__privateGet(this, _root), _options));
__privateSet(this, _negs, __privateGet(this, _root) === this ? [] : __privateGet(__privateGet(this, _root), _negs));
if ("!" === s && !__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 s of __privateGet(this, _parts)) if ("string" != typeof s) if (s.type || s.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((s => String(s))).join("")); else return __privateSet(this, _toString, this.type + "(" + __privateGet(this, _parts).map((s => String(s))).join("|") + ")");
}
push(...s) {
for (const r of s) if ("" !== r) {
if ("string" != typeof r && !(r instanceof _AST && __privateGet(r, _parent) === this)) throw new Error("invalid part: " + r);
__privateGet(this, _parts).push(r);
}
}
toJSON() {
var s;
const r = null === this.type ? __privateGet(this, _parts).slice().map((s => "string" == typeof s ? s : s.toJSON())) : [ this.type, ...__privateGet(this, _parts).map((s => s.toJSON())) ];
if (this.isStart() && !this.type) r.unshift([]);
if (this.isEnd() && (this === __privateGet(this, _root) || __privateGet(__privateGet(this, _root), _filledNegs) && "!" === (null == (s = __privateGet(this, _parent)) ? void 0 : s.type))) r.push({});
return r;
}
isStart() {
var s;
if (__privateGet(this, _root) === this) return true;
if (!(null == (s = __privateGet(this, _parent)) ? void 0 : s.isStart())) return false;
if (0 === __privateGet(this, _parentIndex)) return true;
const r = __privateGet(this, _parent);
for (let s = 0; s < __privateGet(this, _parentIndex); s++) {
const o = __privateGet(r, _parts)[s];
if (!(o instanceof _AST && "!" === o.type)) return false;
}
return true;
}
isEnd() {
var s, r, o;
if (__privateGet(this, _root) === this) return true;
if ("!" === (null == (s = __privateGet(this, _parent)) ? void 0 : s.type)) return true;
if (!(null == (r = __privateGet(this, _parent)) ? void 0 : r.isEnd())) return false;
if (!this.type) return null == (o = __privateGet(this, _parent)) ? void 0 : o.isEnd();
const u = __privateGet(this, _parent) ? __privateGet(__privateGet(this, _parent), _parts).length : 0;
return __privateGet(this, _parentIndex) === u - 1;
}
copyIn(s) {
if ("string" == typeof s) this.push(s); else this.push(s.clone(this));
}
clone(s) {
const r = new _AST(this.type, s);
for (const s of __privateGet(this, _parts)) r.copyIn(s);
return r;
}
static fromGlob(s, r = {}) {
var o;
const u = new _AST(null, void 0, r);
__privateMethod(o = _AST, _parseAST, parseAST_fn).call(o, s, u, 0, r);
return u;
}
toMMPattern() {
if (this !== __privateGet(this, _root)) return __privateGet(this, _root).toMMPattern();
const s = this.toString(), [r, o, u, g] = this.toRegExpSource();
if (!(u || __privateGet(this, _hasMagic) || __privateGet(this, _options).nocase && !__privateGet(this, _options).nocaseMagicOnly && s.toUpperCase() !== s.toLowerCase())) return o;
const _ = (__privateGet(this, _options).nocase ? "i" : "") + (g ? "u" : "");
return Object.assign(new RegExp(`^${r}$`, _), {
_src: r,
_glob: s
});
}
toRegExpSource(s) {
var r;
const o = null != s ? s : !!__privateGet(this, _options).dot;
if (__privateGet(this, _root) === this) __privateMethod(this, _fillNegs, fillNegs_fn).call(this);
if (!this.type) {
const u = this.isStart() && this.isEnd(), g = __privateGet(this, _parts).map((r => {
var o;
const [g, _, m, b] = "string" == typeof r ? __privateMethod(o = _AST, _parseGlob, parseGlob_fn).call(o, r, __privateGet(this, _hasMagic), u) : r.toRegExpSource(s);
__privateSet(this, _hasMagic, __privateGet(this, _hasMagic) || m);
__privateSet(this, _uflag, __privateGet(this, _uflag) || b);
return g;
})).join("");
let _ = "";
if (this.isStart()) if ("string" == typeof __privateGet(this, _parts)[0]) if (!(1 === __privateGet(this, _parts).length && justDots.has(__privateGet(this, _parts)[0]))) {
const r = addPatternStart, u = o && r.has(g.charAt(0)) || g.startsWith("\\.") && r.has(g.charAt(2)) || g.startsWith("\\.\\.") && r.has(g.charAt(4)), m = !o && !s && r.has(g.charAt(0));
_ = u ? startNoTraversal : m ? startNoDot : "";
}
let m = "";
if (this.isEnd() && __privateGet(__privateGet(this, _root), _filledNegs) && "!" === (null == (r = __privateGet(this, _parent)) ? void 0 : r.type)) m = "(?:$|\\/)";
return [ _ + g + m, unescape2(g), __privateSet(this, _hasMagic, !!__privateGet(this, _hasMagic)), __privateGet(this, _uflag) ];
}
const u = "*" === this.type || "+" === this.type, g = "!" === this.type ? "(?:(?!(?:" : "(?:";
let _ = __privateMethod(this, _partsToRegExp, partsToRegExp_fn).call(this, o);
if (this.isStart() && this.isEnd() && !_ && "!" !== this.type) {
const s = this.toString();
__privateSet(this, _parts, [ s ]);
this.type = null;
__privateSet(this, _hasMagic, void 0);
return [ s, unescape2(this.toString()), false, false ];
}
let m = !u || s || o || !startNoDot ? "" : __privateMethod(this, _partsToRegExp, partsToRegExp_fn).call(this, true);
if (m === _) m = "";
if (m) _ = `(?:${_})(?:${m})*?`;
let b = "";
if ("!" === this.type && __privateGet(this, _emptyExt)) b = (this.isStart() && !o ? startNoDot : "") + starNoEmpty; else b = g + _ + ("!" === this.type ? "))" + (this.isStart() && !o && !s ? startNoDot : "") + star + ")" : "@" === this.type ? ")" : "?" === this.type ? ")?" : "+" === this.type && m ? ")" : "*" === this.type && m ? ")?" : `)${this.type}`);
return [ b, unescape2(_), __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 s;
for (;s = __privateGet(this, _negs).pop(); ) {
if ("!" !== s.type) continue;
let r = s, o = __privateGet(r, _parent);
for (;o; ) {
for (let u = __privateGet(r, _parentIndex) + 1; !o.type && u < __privateGet(o, _parts).length; u++) for (const r of __privateGet(s, _parts)) {
if ("string" == typeof r) throw new Error("string part in extglob AST??");
r.copyIn(__privateGet(o, _parts)[u]);
}
r = o;
o = __privateGet(r, _parent);
}
}
return this;
};
_parseAST = new WeakSet;
parseAST_fn = function(s, r, o, u) {
var g, _;
let m = false, b = false, E = -1, w = false;
if (null === r.type) {
let _ = o, S = "";
for (;_ < s.length; ) {
const o = s.charAt(_++);
if (!m && "\\" !== o) if (!b) {
if ("[" === o) {
b = true;
E = _;
w = false;
S += o;
continue;
}
if (u.noext || !isExtglobType(o) || "(" !== s.charAt(_)) S += o; else {
r.push(S);
S = "";
const m = new _AST(o, r);
_ = __privateMethod(g = _AST, _parseAST, parseAST_fn).call(g, s, m, _, u);
r.push(m);
}
} else {
if (_ === E + 1) {
if ("^" === o || "!" === o) w = true;
} else if ("]" === o && !(_ === E + 2 && w)) b = false;
S += o;
} else {
m = !m;
S += o;
}
}
r.push(S);
return _;
}
let S = o + 1, L = new _AST(null, r);
const O = [];
let D = "";
for (;S < s.length; ) {
const o = s.charAt(S++);
if (!m && "\\" !== o) if (!b) {
if ("[" === o) {
b = true;
E = S;
w = false;
D += o;
continue;
}
if (!isExtglobType(o) || "(" !== s.charAt(S)) if ("|" !== o) {
if (")" === o) {
if ("" === D && 0 === __privateGet(r, _parts).length) __privateSet(r, _emptyExt, true);
L.push(D);
D = "";
r.push(...O, L);
return S;
}
D += o;
} else {
L.push(D);
D = "";
O.push(L);
L = new _AST(null, r);
} else {
L.push(D);
D = "";
const r = new _AST(o, L);
L.push(r);
S = __privateMethod(_ = _AST, _parseAST, parseAST_fn).call(_, s, r, S, u);
}
} else {
if (S === E + 1) {
if ("^" === o || "!" === o) w = true;
} else if ("]" === o && !(S === E + 2 && w)) b = false;
D += o;
} else {
m = !m;
D += o;
}
}
r.type = null;
__privateSet(r, _hasMagic, void 0);
__privateSet(r, _parts, [ s.substring(o - 1) ]);
return S;
};
_partsToRegExp = new WeakSet;
partsToRegExp_fn = function(s) {
return __privateGet(this, _parts).map((r => {
if ("string" == typeof r) throw new Error("string type in extglob ast??");
const [o, u, g, _] = r.toRegExpSource(s);
__privateSet(this, _uflag, __privateGet(this, _uflag) || _);
return o;
})).filter((s => !(this.isStart() && this.isEnd() && !s))).join("|");
};
_parseGlob = new WeakSet;
parseGlob_fn = function(s, r, o = false) {
let u = false, g = "", _ = false;
for (let m = 0; m < s.length; m++) {
const b = s.charAt(m);
if (!u) if ("\\" !== b) {
if ("[" === b) {
const [o, u, b, E] = parseClass(s, m);
if (b) {
g += o;
_ = _ || u;
m += b - 1;
r = r || E;
continue;
}
}
if ("*" !== b) if ("?" !== b) g += regExpEscape(b); else {
g += qmark;
r = true;
} else {
if (o && "*" === s) g += starNoEmpty; else g += star;
r = true;
}
} else if (m === s.length - 1) g += "\\\\"; else u = true; else {
u = false;
g += (reSpecials.has(b) ? "\\" : "") + b;
}
}
return [ g, unescape2(s), !!r, _ ];
};
__privateAdd(_AST, _parseAST);
__privateAdd(_AST, _parseGlob);
var AST = _AST, escape = (s, {windowsPathsNoEscape: r = false} = {}) => r ? s.replace(/[?*()[\]]/g, "[$&]") : s.replace(/[?*()[\]\\]/g, "\\$&"), minimatch = (s, r, o = {}) => {
assertValidPattern(r);
if (!o.nocomment && "#" === r.charAt(0)) return false; else return new Minimatch(r, o).match(s);
}, starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/, starDotExtTest = s => r => !r.startsWith(".") && r.endsWith(s), starDotExtTestDot = s => r => r.endsWith(s), starDotExtTestNocase = s => {
s = s.toLowerCase();
return r => !r.startsWith(".") && r.toLowerCase().endsWith(s);
}, starDotExtTestNocaseDot = s => {
s = s.toLowerCase();
return r => r.toLowerCase().endsWith(s);
}, starDotStarRE = /^\*+\.\*+$/, starDotStarTest = s => !s.startsWith(".") && s.includes("."), starDotStarTestDot = s => "." !== s && ".." !== s && s.includes("."), dotStarRE = /^\.\*+$/, dotStarTest = s => "." !== s && ".." !== s && s.startsWith("."), starRE = /^\*+$/, starTest = s => 0 !== s.length && !s.startsWith("."), starTestDot = s => 0 !== s.length && "." !== s && ".." !== s, qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/, qmarksTestNocase = ([s, r = ""]) => {
const o = qmarksTestNoExt([ s ]);
if (!r) return o;
r = r.toLowerCase();
return s => o(s) && s.toLowerCase().endsWith(r);
}, qmarksTestNocaseDot = ([s, r = ""]) => {
const o = qmarksTestNoExtDot([ s ]);
if (!r) return o;
r = r.toLowerCase();
return s => o(s) && s.toLowerCase().endsWith(r);
}, qmarksTestDot = ([s, r = ""]) => {
const o = qmarksTestNoExtDot([ s ]);
return !r ? o : s => o(s) && s.endsWith(r);
}, qmarksTest = ([s, r = ""]) => {
const o = qmarksTestNoExt([ s ]);
return !r ? o : s => o(s) && s.endsWith(r);
}, qmarksTestNoExt = ([s]) => {
const r = s.length;
return s => s.length === r && !s.startsWith(".");
}, qmarksTestNoExtDot = ([s]) => {
const r = s.length;
return s => s.length === r && "." !== s && ".." !== s;
}, 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 = (s, r = {}) => o => minimatch(o, s, r);
minimatch.filter = filter;
var ext = (s, r = {}) => Object.assign({}, s, r), defaults = s => {
if (!s || "object" != typeof s || !Object.keys(s).length) return minimatch;
const r = minimatch;
return Object.assign(((o, u, g = {}) => r(o, u, ext(s, g))), {
Minimatch: class Minimatch extends r.Minimatch {
constructor(r, o = {}) {
super(r, ext(s, o));
}
static defaults(o) {
return r.defaults(ext(s, o)).Minimatch;
}
},
AST: class AST extends r.AST {
constructor(r, o, u = {}) {
super(r, o, ext(s, u));
}
static fromGlob(o, u = {}) {
return r.AST.fromGlob(o, ext(s, u));
}
},
unescape: (o, u = {}) => r.unescape(o, ext(s, u)),
escape: (o, u = {}) => r.escape(o, ext(s, u)),
filter: (o, u = {}) => r.filter(o, ext(s, u)),
defaults: o => r.defaults(ext(s, o)),
makeRe: (o, u = {}) => r.makeRe(o, ext(s, u)),
braceExpand: (o, u = {}) => r.braceExpand(o, ext(s, u)),
match: (o, u, g = {}) => r.match(o, u, ext(s, g)),
sep: r.sep,
GLOBSTAR
});
};
minimatch.defaults = defaults;
var braceExpand = (s, r = {}) => {
assertValidPattern(s);
if (r.nobrace || !/\{(?:(?!\{).)*\}/.test(s)) return [ s ]; else return (0, import_brace_expansion.default)(s);
};
minimatch.braceExpand = braceExpand;
var makeRe = (s, r = {}) => new Minimatch(s, r).makeRe();
minimatch.makeRe = makeRe;
var match = (s, r, o = {}) => {
const u = new Minimatch(r, o);
s = s.filter((s => u.match(s)));
if (u.options.nonull && !s.length) s.push(r);
return s;
};
minimatch.match = match;
var globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/, regExpEscape2 = s => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), Minimatch = class {
constructor(s, r = {}) {
__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(s);
r = r || {};
this.options = r;
this.pattern = s;
this.platform = r.platform || defaultPlatform;
this.isWindows = "win32" === this.platform;
this.windowsPathsNoEscape = !!r.windowsPathsNoEscape || false === r.allowWindowsEscape;
if (this.windowsPathsNoEscape) this.pattern = this.pattern.replace(/\\/g, "/");
this.preserveMultipleSlashes = !!r.preserveMultipleSlashes;
this.regexp = null;
this.negate = false;
this.nonegate = !!r.nonegate;
this.comment = false;
this.empty = false;
this.partial = !!r.partial;
this.nocase = !!this.options.nocase;
this.windowsNoMagicRoot = void 0 !== r.windowsNoMagicRoot ? r.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 s of this.set) for (const r of s) if ("string" != typeof r) return true;
return false;
}
debug(...s) {}
make() {
const s = this.pattern, r = this.options;
if (!r.nocomment && "#" === s.charAt(0)) {
this.comment = true;
return;
}
if (!s) {
this.empty = true;
return;
}
this.parseNegate();
this.globSet = [ ...new Set(this.braceExpand()) ];
if (r.debug) this.debug = (...s) => console.error(...s);
this.debug(this.pattern, this.globSet);
const o = this.globSet.map((s => this.slashSplit(s)));
this.globParts = this.preprocess(o);
this.debug(this.pattern, this.globParts);
let u = this.globParts.map(((s, r, o) => {
if (this.isWindows && this.windowsNoMagicRoot) {
const r = !("" !== s[0] || "" !== s[1] || "?" !== s[2] && globMagic.test(s[2]) || globMagic.test(s[3])), o = /^[a-z]:/i.test(s[0]);
if (r) return [ ...s.slice(0, 4), ...s.slice(4).map((s => this.parse(s))) ]; else if (o) return [ s[0], ...s.slice(1).map((s => this.parse(s))) ];
}
return s.map((s => this.parse(s)));
}));
this.debug(this.pattern, u);
this.set = u.filter((s => -1 === s.indexOf(false)));
if (this.isWindows) for (let s = 0; s < this.set.length; s++) {
const r = this.set[s];
if ("" === r[0] && "" === r[1] && "?" === this.globParts[s][2] && "string" == typeof r[3] && /^[a-z]:$/i.test(r[3])) r[2] = "?";
}
this.debug(this.pattern, this.set);
}
preprocess(s) {
if (this.options.noglobstar) for (let r = 0; r < s.length; r++) for (let o = 0; o < s[r].length; o++) if ("**" === s[r][o]) s[r][o] = "*";
const {optimizationLevel: r = 1} = this.options;
if (r >= 2) {
s = this.firstPhasePreProcess(s);
s = this.secondPhasePreProcess(s);
} else if (r >= 1) s = this.levelOneOptimize(s); else s = this.adjascentGlobstarOptimize(s);
return s;
}
adjascentGlobstarOptimize(s) {
return s.map((s => {
let r = -1;
for (;-1 !== (r = s.indexOf("**", r + 1)); ) {
let o = r;
for (;"**" === s[o + 1]; ) o++;
if (o !== r) s.splice(r, o - r);
}
return s;
}));
}
levelOneOptimize(s) {
return s.map((s => 0 === (s = s.reduce(((s, r) => {
const o = s[s.length - 1];
if ("**" === r && "**" === o) return s;
if (".." === r) if (o && ".." !== o && "." !== o && "**" !== o) {
s.pop();
return s;
}
s.push(r);
return s;
}), [])).length ? [ "" ] : s));
}
levelTwoFileOptimize(s) {
if (!Array.isArray(s)) s = this.slashSplit(s);
let r = false;
do {
r = false;
if (!this.preserveMultipleSlashes) {
for (let o = 1; o < s.length - 1; o++) {
const u = s[o];
if (1 !== o || "" !== u || "" !== s[0]) if ("." === u || "" === u) {
r = true;
s.splice(o, 1);
o--;
}
}
if ("." === s[0] && 2 === s.length && ("." === s[1] || "" === s[1])) {
r = true;
s.pop();
}
}
let o = 0;
for (;-1 !== (o = s.indexOf("..", o + 1)); ) {
const u = s[o - 1];
if (u && "." !== u && ".." !== u && "**" !== u) {
r = true;
s.splice(o - 1, 2);
o -= 2;
}
}
} while (r);
return 0 === s.length ? [ "" ] : s;
}
firstPhasePreProcess(s) {
let r = false;
do {
r = false;
for (let o of s) {
let u = -1;
for (;-1 !== (u = o.indexOf("**", u + 1)); ) {
let g = u;
for (;"**" === o[g + 1]; ) g++;
if (g > u) o.splice(u + 1, g - u);
let _ = o[u + 1];
const m = o[u + 2], b = o[u + 3];
if (".." !== _) continue;
if (!m || "." === m || ".." === m || !b || "." === b || ".." === b) continue;
r = true;
o.splice(u, 1);
const E = o.slice(0);
E[u] = "**";
s.push(E);
u--;
}
if (!this.preserveMultipleSlashes) {
for (let s = 1; s < o.length - 1; s++) {
const u = o[s];
if (1 !== s || "" !== u || "" !== o[0]) if ("." === u || "" === u) {
r = true;
o.splice(s, 1);
s--;
}
}
if ("." === o[0] && 2 === o.length && ("." === o[1] || "" === o[1])) {
r = true;
o.pop();
}
}
let g = 0;
for (;-1 !== (g = o.indexOf("..", g + 1)); ) {
const s = o[g - 1];
if (s && "." !== s && ".." !== s && "**" !== s) {
r = true;
const s = 1 === g && "**" === o[g + 1] ? [ "." ] : [];
o.splice(g - 1, 2, ...s);
if (0 === o.length) o.push("");
g -= 2;
}
}
}
} while (r);
return s;
}
secondPhasePreProcess(s) {
for (let r = 0; r < s.length - 1; r++) for (let o = r + 1; o < s.length; o++) {
const u = this.partsMatch(s[r], s[o], !this.preserveMultipleSlashes);
if (u) {
s[r] = u;
s[o] = [];
}
}
return s.filter((s => s.length));
}
partsMatch(s, r, o = false) {
let u = 0, g = 0, _ = [], m = "";
for (;u < s.length && g < r.length; ) if (s[u] === r[g]) {
_.push("b" === m ? r[g] : s[u]);
u++;
g++;
} else if (o && "**" === s[u] && r[g] === s[u + 1]) {
_.push(s[u]);
u++;
} else if (o && "**" === r[g] && s[u] === r[g + 1]) {
_.push(r[g]);
g++;
} else if ("*" === s[u] && r[g] && (this.options.dot || !r[g].startsWith(".")) && "**" !== r[g]) {
if ("b" === m) return false;
m = "a";
_.push(s[u]);
u++;
g++;
} else if ("*" === r[g] && s[u] && (this.options.dot || !s[u].startsWith(".")) && "**" !== s[u]) {
if ("a" === m) return false;
m = "b";
_.push(r[g]);
u++;
g++;
} else return false;
return s.length === r.length && _;
}
parseNegate() {
if (this.nonegate) return;
const s = this.pattern;
let r = false, o = 0;
for (let u = 0; u < s.length && "!" === s.charAt(u); u++) {
r = !r;
o++;
}
if (o) this.pattern = s.slice(o);
this.negate = r;
}
matchOne(s, r, o = false) {
const u = this.options;
if (this.isWindows) {
const o = "string" == typeof s[0] && /^[a-z]:$/i.test(s[0]), u = !o && "" === s[0] && "" === s[1] && "?" === s[2] && /^[a-z]:$/i.test(s[3]), g = "string" == typeof r[0] && /^[a-z]:$/i.test(r[0]), _ = u ? 3 : o ? 0 : void 0, m = !g && "" === r[0] && "" === r[1] && "?" === r[2] && "string" == typeof r[3] && /^[a-z]:$/i.test(r[3]) ? 3 : g ? 0 : void 0;
if ("number" == typeof _ && "number" == typeof m) {
const [o, u] = [ s[_], r[m] ];
if (o.toLowerCase() === u.toLowerCase()) {
r[m] = o;
if (m > _) r = r.slice(m); else if (_ > m) s = s.slice(_);
}
}
}
const {optimizationLevel: g = 1} = this.options;
if (g >= 2) s = this.levelTwoFileOptimize(s);
this.debug("matchOne", this, {
file: s,
pattern: r
});
this.debug("matchOne", s.length, r.length);
for (var _ = 0, m = 0, b = s.length, E = r.length; _ < b && m < E; _++, m++) {
this.debug("matchOne loop");
var w = r[m], S = s[_];
this.debug(r, w, S);
if (false === w) return false;
if (w === GLOBSTAR) {
this.debug("GLOBSTAR", [ r, w, S ]);
var L = _, O = m + 1;
if (O === E) {
this.debug("** at the end");
for (;_ < b; _++) if ("." === s[_] || ".." === s[_] || !u.dot && "." === s[_].charAt(0)) return false;
return true;
}
for (;L < b; ) {
var D = s[L];
this.debug("\nglobstar while", s, L, r, O, D);
if (this.matchOne(s.slice(L), r.slice(O), o)) {
this.debug("globstar found match!", L, b, D);
return true;
} else {
if ("." === D || ".." === D || !u.dot && "." === D.charAt(0)) {
this.debug("dot detected!", s, L, r, O);
break;
}
this.debug("globstar swallow a segment, and continue");
L++;
}
}
if (o) {
this.debug("\n>>> no match, partial?", s, L, r, O);
if (L === b) return true;
}
return false;
}
let g;
if ("string" == typeof w) {
g = S === w;
this.debug("string match", w, S, g);
} else {
g = w.test(S);
this.debug("pattern match", w, S, g);
}
if (!g) return false;
}
if (_ === b && m === E) return true; else if (_ === b) return o; else if (m === E) return _ === b - 1 && "" === s[_]; else throw new Error("wtf?");
}
braceExpand() {
return braceExpand(this.pattern, this.options);
}
parse(s) {
assertValidPattern(s);
const r = this.options;
if ("**" === s) return GLOBSTAR;
if ("" === s) return "";
let o, u = null;
if (o = s.match(starRE)) u = r.dot ? starTestDot : starTest; else if (o = s.match(starDotExtRE)) u = (r.nocase ? r.dot ? starDotExtTestNocaseDot : starDotExtTestNocase : r.dot ? starDotExtTestDot : starDotExtTest)(o[1]); else if (o = s.match(qmarksRE)) u = (r.nocase ? r.dot ? qmarksTestNocaseDot : qmarksTestNocase : r.dot ? qmarksTestDot : qmarksTest)(o); else if (o = s.match(starDotStarRE)) u = r.dot ? starDotStarTestDot : starDotStarTest; else if (o = s.match(dotStarRE)) u = dotStarTest;
const g = AST.fromGlob(s, this.options).toMMPattern();
return u ? Object.assign(g, {
test: u
}) : g;
}
makeRe() {
if (this.regexp || false === this.regexp) return this.regexp;
const s = this.set;
if (!s.length) {
this.regexp = false;
return this.regexp;
}
const r = this.options, o = r.noglobstar ? star2 : r.dot ? twoStarDot : twoStarNoDot, u = new Set(r.nocase ? [ "i" ] : []);
let g = s.map((s => {
const r = s.map((s => {
if (s instanceof RegExp) for (const r of s.flags.split("")) u.add(r);
return "string" == typeof s ? regExpEscape2(s) : s === GLOBSTAR ? GLOBSTAR : s._src;
}));
r.forEach(((s, u) => {
const g = r[u + 1], _ = r[u - 1];
if (s === GLOBSTAR && _ !== GLOBSTAR) if (void 0 === _) if (void 0 !== g && g !== GLOBSTAR) r[u + 1] = "(?:\\/|" + o + "\\/)?" + g; else r[u] = o; else if (void 0 === g) r[u - 1] = _ + "(?:\\/|" + o + ")?"; else if (g !== GLOBSTAR) {
r[u - 1] = _ + "(?:\\/|\\/" + o + "\\/)" + g;
r[u + 1] = GLOBSTAR;
}
}));
return r.filter((s => s !== GLOBSTAR)).join("/");
})).join("|");
const [_, m] = s.length > 1 ? [ "(?:", ")" ] : [ "", "" ];
g = "^" + _ + g + m + "$";
if (this.negate) g = "^(?!" + g + ").+$";
try {
this.regexp = new RegExp(g, [ ...u ].join(""));
} catch (s) {
this.regexp = false;
}
return this.regexp;
}
slashSplit(s) {
if (this.preserveMultipleSlashes) return s.split("/"); else if (this.isWindows && /^\/\/[^\/]+/.test(s)) return [ "", ...s.split(/\/+/) ]; else return s.split(/\/+/);
}
match(s, r = this.partial) {
this.debug("match", s, this.pattern);
if (this.comment) return false;
if (this.empty) return "" === s;
if ("/" === s && r) return true;
const o = this.options;
if (this.isWindows) s = s.split("\\").join("/");
const u = this.slashSplit(s);
this.debug(this.pattern, "split", u);
const g = this.set;
this.debug(this.pattern, "set", g);
let _ = u[u.length - 1];
if (!_) for (let s = u.length - 2; !_ && s >= 0; s--) _ = u[s];
for (let s = 0; s < g.length; s++) {
const m = g[s];
let b = u;
if (o.matchBase && 1 === m.length) b = [ _ ];
if (this.matchOne(b, m, r)) if (o.flipNegate) return true; else return !this.negate;
}
if (o.flipNegate) return false; else return this.negate;
}
static defaults(s) {
return minimatch.defaults(s).Minimatch;
}
};
minimatch.AST = AST;
minimatch.Minimatch = Minimatch;
minimatch.escape = escape;
minimatch.unescape = unescape2;
var webcrypto, import_crypto = require("crypto");
if ("undefined" != typeof window && window.crypto) webcrypto = window.crypto; else {
const s = import_crypto.webcrypto;
webcrypto = s;
}
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(s, r, o) {
if (r.buffer.byteLength < s.byteLength + o) {
const u = Math.ceil((s.byteLength + o - r.buffer.byteLength) / 65536);
r.grow(u);
}
new Uint8Array(r.buffer, o).set(s);
}
async function xxhash_wasm_default() {
const {instance: {exports: {mem: s, xxh32: r, xxh64: o}}} = await WebAssembly.instantiate(t);
function h2(o) {
let u = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0;
return n(o, s, 0), r(0, o.byteLength, u) >>> 0;
}
function c(r) {
let u = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0, g = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : 0;
n(r, s, 8);
const _ = new DataView(s.buffer);
return _.setUint32(0, u, true), _.setUint32(4, g, true), o(0, r.byteLength), _;
}
return {
h32: function(s) {
let r = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0;
e || (e = new TextEncoder);
return h2(e.encode(s), r).toString(16);
},
h32Raw: h2,
h64: function(s) {
let r = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0, o = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : 0;
e || (e = new TextEncoder);
const u = c(e.encode(s), r, o);
return u.getUint32(0, true).toString(16) + u.getUint32(4, true).toString(16);
},
h64Raw: function(s) {
let r = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0, o = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : 0;
return new Uint8Array(c(s, r, o).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: s, xxh32: r, xxh64: o, init32: u, update32: g, digest32: _, init64: m, update64: b, digest64: E}}} = await WebAssembly.instantiate(t2);
let w = new Uint8Array(s.buffer);
function c(r, o) {
if (s.buffer.byteLength < r + o) {
const u = Math.ceil((r + o - s.buffer.byteLength) / 65536);
s.grow(u), w = new Uint8Array(s.buffer);
}
}
function l(s, r, o, u, g, _) {
c(s);
const m = new Uint8Array(s);
return w.set(m), o(0, r), m.set(w.slice(0, s)), {
update(r) {
let o;
return w.set(m), "string" == typeof r ? (c(3 * r.length, s), o = L.encodeInto(r, w.subarray(s)).written) : (c(r.byteLength, s),
w.set(r, s), o = r.byteLength), u(0, s, o), m.set(w.slice(0, s)), this;
},
digest: () => (w.set(m), _(g(0)))
};
}
function d3(s) {
return s >>> 0;
}
const S = BigInt(2) ** BigInt(64) - BigInt(1);
function y(s) {
return s & S;
}
const L = new TextEncoder, O = BigInt(0);
function p(s) {
let o = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0;
return c(3 * s.length, 0), d3(r(0, L.encodeInto(s, w).written, o));
}
function v(s) {
let r = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : O;
return c(3 * s.length, 0), y(o(0, L.encodeInto(s, w).written, r));
}
return {
h32: p,
h32ToString(s) {
return p(s, arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0).toString(16).padStart(8, "0");
},
h32Raw(s) {
let o = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0;
return c(s.byteLength, 0), w.set(s), d3(r(0, s.byteLength, o));
},
create32() {
return l(48, arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : 0, u, g, _, d3);
},
h64: v,
h64ToString(s) {
return v(s, arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : O).toString(16).padStart(16, "0");
},
h64Raw(s) {
let r = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : O;
return c(s.byteLength, 0), w.set(s), y(o(0, s.byteLength, r));
},
create64() {
return l(88, arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : O, m, b, E, y);
}
};
}
var revMap = {}, numMap = {};
for (let s = 0; s < 256; s++) {
revMap[`00${s.toString(16)}`.slice(-2)] = s;
numMap[s] = `00${s.toString(16)}`.slice(-2);
}
function* range(s, r) {
for (let o = s; o <= r; o++) yield o;
}
var table = {}, revTable = {};
[ ...range(192, 447) ].forEach(((s, r) => {
table[r] = s;
revTable[s] = r;
}));
var BINARY_CHUNK_MAX = 31457280;
function hexStringToUint8Array(s) {
const r = s.length / 2, o = new Uint8Array(r);
for (let u = 0; u < r; u++) o[u] = revMap[s[2 * u] + s[2 * u + 1]];
return o;
}
function uint8ArrayToHexString(s) {
return [ ...s ].map((s => numMap[s])).join("");
}
function btoa_node(s) {
return Buffer.from(s, "binary").toString("base64");
}
function atob_node(s) {
return Buffer.from(s, "base64").toString("binary");
}
var btoa2 = window && window.btoa ? window.btoa : btoa_node, atob2 = window && window.atob ? window.atob : atob_node, QUANTUM = 32768, writeString = s => {
const r = new Uint8Array(4 * s.length), o = s.length;
let u = 0, g = 0, _ = 0;
for (;_ < o; ) {
g = s.charCodeAt(_++);
if (g < 128) r[u++] = g; else if (g < 2048) {
r[u++] = 192 | g >>> 6;
r[u++] = 128 | 63 & g;
} else if (g < 55296 || g > 57343) {
r[u++] = 224 | g >>> 12;
r[u++] = 128 | g >>> 6 & 63;
r[u++] = 128 | 63 & g;
} else {
g = 65536 + (g - 55296 << 10 | s.charCodeAt(_++) - 56320);
r[u++] = 240 | g >>> 18;
r[u++] = 128 | g >>> 12 & 63;
r[u++] = 128 | g >>> 6 & 63;
r[u++] = 128 | 63 & g;
}
}
return r.slice(0, u);
}, readString = s => {
let r = 0;
const o = s.length;
let u = "";
for (;r < o; ) {
const g = [], _ = Math.min(r + QUANTUM, o);
for (;r < _; ) {
const o = s[r++];
if (o < 128) g.push(o); else if (192 == (224 & o)) g.push((31 & o) << 6 | 63 & s[r++]); else if (224 == (240 & o)) g.push((15 & o) << 12 | (63 & s[r++]) << 6 | 63 & s[r++]); else if (240 == (248 & o)) {
let u = (7 & o) << 18 | (63 & s[r++]) << 12 | (63 & s[r++]) << 6 | 63 & s[r++];
if (u < 65536) g.push(u); else {
u -= 65536;
g.push(55296 + (u >>> 10), 56320 + (1023 & u));
}
}
}
u += String.fromCharCode(...g);
}
return u;
}, encodeChunkSize = 15e7;
function arrayBufferToBase64internalBrowser(s) {
return new Promise(((r, o) => {
const u = new Blob([ s ], {
type: "application/octet-binary"
}), g = new FileReader;
g.onload = function(u) {
var g, _;
const m = (null == (_ = null == (g = u.target) ? void 0 : g.result) ? void 0 : _.toString()) || "";
if (0 != s.byteLength && ("" == m || "data:" == m)) return o(new TypeError("Could not parse the encoded string"));
const b = m.substring(m.indexOf(",") + 1);
r(b);
};
g.readAsDataURL(u);
}));
}
function arrayBufferToBase64internalNode(s) {
return Buffer.from(s.buffer).toString("base64");
}
var arrayBufferToBase64internal = window && window.btoa ? arrayBufferToBase64internalBrowser : arrayBufferToBase64internalNode;
async function arrayBufferToBase64Single(s) {
const r = s instanceof Uint8Array ? s : new Uint8Array(s);
if (r.byteLength < QUANTUM) return btoa2(String.fromCharCode.apply(null, [ ...r ])); else return await arrayBufferToBase64internal(r);
}
async function arrayBufferToBase64(s) {
const r = s instanceof Uint8Array ? s : new Uint8Array(s);
if (r.byteLength < QUANTUM) return [ btoa2(String.fromCharCode.apply(null, [ ...r ])) ];
const o = r.byteLength, u = [];
let g = 0;
do {
const s = g * encodeChunkSize, o = new DataView(r.buffer, s, Math.min(encodeChunkSize, r.byteLength - s));
u.push(await arrayBufferToBase64internal(o));
g++;
} while (g * encodeChunkSize < o);
return u;
}
function base64ToArrayBuffer(s) {
if ("string" == typeof s) return base64ToArrayBufferInternal(s);
const r = s.map((s => base64ToArrayBufferInternal(s))), o = r.reduce(((s, r) => s + r.byteLength), 0), u = new Uint8Array(o);
let g = 0;
r.forEach((s => {
u.set(new Uint8Array(s), g);
g += s.byteLength;
}));
return u.buffer;
}
var base64ToArrayBufferInternal = window && window.atob ? base64ToArrayBufferInternalBrowser : base64ToArrayBufferInternalNode;
function base64ToArrayBufferInternalNode(s) {
try {
return Buffer.from(s, "base64").buffer;
} catch (s) {
Logger("Base64 decode error (Node)", LOG_LEVEL_VERBOSE);
Logger(s, LOG_LEVEL_VERBOSE);
return new ArrayBuffer(0);
}
}
function base64ToArrayBufferInternalBrowser(s) {
try {
const r = window.atob(s), o = r.length, u = new Uint8Array(o);
for (let s = 0; s < o; s++) u[s] = r.charCodeAt(s);
return u.buffer;
} catch (s) {
Logger("Base64 Decode error", LOG_LEVEL_VERBOSE);
Logger(s, LOG_LEVEL_VERBOSE);
return new ArrayBuffer(0);
}
}
function* pickPiece(s, r) {
let o = "";
e: do {
const u = s.shift();
if ("undefined" == typeof u) {
yield o;
break e;
}
if (u.startsWith("```") || u.startsWith(" ```") || u.startsWith(" ```") || u.startsWith(" ```")) {
yield o;
o = u + (0 != s.length ? "\n" : "");
t: do {
const r = s.shift();
if ("undefined" == typeof r) break t;
o += r + (0 != s.length ? "\n" : "");
} while (s.length > 0 && !(s[0].startsWith("```") || s[0].startsWith(" ```") || s[0].startsWith(" ```") || s[0].startsWith(" ```")));
const r = o.endsWith("="), g = o.length > 2048, _ = s.shift();
if ("undefined" != typeof _) {
o += _;
o += 0 != s.length ? "\n" : "";
}
if (!r && !g) {
const s = /(.*?[;,:<])/g, r = o.split(s).filter((s => "" != s));
for (const s of r) yield s;
} else yield o;
o = "";
} else {
o += u + (0 != s.length ? "\n" : "");
if (o.length >= r || 0 == s.length || "#" == s[0] || "#" == o[0]) {
yield o;
o = "";
}
}
} while (s.length > 0);
}
var charNewLine = "\n".charCodeAt(0);
function splitPiecesText(s, r, o, u) {
const g = "string" == typeof s ? [ s ] : s;
return function* pieces() {
for (const s of g) if (o) {
const o = pickPiece(s.split("\n"), u);
for (const s of o) {
let o = s;
do {
let s = r;
if (o.charCodeAt(s - 1) != o.codePointAt(s - 1)) s++;
yield o.substring(0, s);
o = o.substring(s);
} while ("" != o);
}
} else {
let o = s;
do {
const s = r, u = o.substring(0, s);
o = o.substring(s);
yield u;
} while ("" != o);
}
};
}
async function splitPieces2(s, r, o, u, g) {
if (isTextBlob(s)) return splitPiecesText(await s.text(), r, o, u);
let _ = 0;
if (g && g.endsWith(".pdf")) _ = "/".charCodeAt(0);
let m = 1, b = Math.max(1e5, Math.min(1e8, s.size));
for (;b > 10; ) {
b /= 12.5;
m++;
}
u = Math.floor(10 ** (m - 1));
return async function* piecesBlob() {
const o = s.size;
let g = 0;
do {
let o = r;
const m = new Uint8Array(await s.slice(g, g + r).arrayBuffer());
let b = m.indexOf(_, u);
o = -1 == b ? r : Math.min(r, b);
if (-1 == b) b = m.indexOf(charNewLine, u);
const E = m.slice(0, o);
g += E.length;
yield await arrayBufferToBase64Single(E);
} while (g < o);
};
}
function versionNumberString2Number(s) {
return s.split(".").reverse().map(((s, r) => s / 1 * 1e3 ** r)).reduce(((s, r) => s + r), 0);
}
var hashFunc, escapeStringToHTML = s => {
if (!s) return ""; else return s.replace(/[<>&"'`]/g, (s => ({
"<": "<",
">": ">",
"&": "&",
'"': """,
"'": "'",
"`": "`"
}[s])));
}, crc32kTable = new Uint32Array(256), crc32cTable = new Uint32Array(256);
function generateCRC32KTable() {
for (let s = 0; s < 256; s++) {
let r = s;
for (let s = 0; s < 8; s++) if (1 & r) r = r >>> 1 ^ 3988292384; else r >>>= 1;
crc32kTable[s] = r;
}
}
function generateCRC32CTable() {
for (let s = 0; s < 256; s++) {
let r = s;
for (let s = 0; s < 8; s++) if (1 & r) r = r >>> 1 ^ 517762881; else r >>>= 1;
crc32cTable[s] = r;
}
}
generateCRC32CTable();
generateCRC32KTable();
function decodeToArrayBuffer(s) {
if (1 == s.length) return _decodeToArrayBuffer(s[0]);
const r = s.map((s => _decodeToArrayBuffer(s))), o = r.reduce(((s, r) => s + r.byteLength), 0), u = new Uint8Array(o);
let g = 0;
r.forEach((s => {
u.set(new Uint8Array(s), g);
g += s.byteLength;
}));
return u.buffer;
}
function _decodeToArrayBuffer(s) {
const r = new Uint8Array(s.length), o = s.length;
for (let u = 0; u < o; u++) {
const o = s.charCodeAt(u);
if (o >= 38 && o <= 126 && 58 != o) r[u] = o; else r[u] = revTable[o];
}
return r.buffer;
}
function decodeBinary(s) {
if (0 == s.length) return (new Uint8Array).buffer;
if ("string" == typeof s) {
if ("%" === s[0]) return _decodeToArrayBuffer(s.substring(1));
} else if ("%" === s[0][0]) {
const [r, ...o] = s;
return decodeToArrayBuffer([ r.substring(1), ...o ]);
}
return base64ToArrayBuffer(s);
}
async function initHashFunc() {
try {
const {h32ToString: s} = await e2();
hashFunc = s;
Logger("xxhash for plugin initialised", LOG_LEVEL_VERBOSE);
} catch (s) {
Logger("Could not initialise xxhash. fallback...", LOG_LEVEL_VERBOSE);
Logger(s);
try {
const {h32: s} = await xxhash_wasm_default();
hashFunc = r => s(r);
} catch (s) {
Logger("Could not initialise old xxhash for plugin: use sha1", LOG_LEVEL_VERBOSE);
Logger(s);
hashFunc = s => s;
}
}
return hashFunc;
}
initHashFunc();
async function sha1(s) {
const r = writeString(s), o = await webcrypto.subtle.digest({
name: "SHA-1"
}, r);
return await arrayBufferToBase64Single(o);
}
function digestHash(s) {
return hashFunc(s);
}
function isValidFilenameInWidows(s) {
if (/[\u0000-\u001f]|[\\":?<>|*#]/g.test(s)) return false;
if (/(\\|\/)(COM\d|LPT\d|CON|PRN|AUX|NUL|CLOCK$)($|\.)/gi.test(s)) return false; else return true;
}
function isValidFilenameInDarwin(s) {
return !/[\u0000-\u001f]|[:]/g.test(s);
}
function isValidFilenameInLinux(s) {
return !/[\u0000-\u001f]|[:]/g.test(s);
}
function isValidFilenameInAndroid(s) {
return !/[\u0000-\u001f]|[\\":?<>|*#]/g.test(s);
}
function isFilePath(s) {
if (-1 === s.indexOf(":")) return true; else return false;
}
function stripAllPrefixes(s) {
if (isFilePath(s)) return s;
const [, r] = expandFilePathPrefix(s);
return stripAllPrefixes(r);
}
function addPrefix(s, r) {
if (r && s.startsWith(r)) return s; else return `${null != r ? r : ""}${s}`;
}
function expandFilePathPrefix(s) {
let [r, o] = s.split(":", 2);
if (!o) {
o = r;
r = "";
} else r += ":";
return [ r, o ];
}
function expandDocumentIDPrefix(s) {
let [r, o] = s.split(":", 2);
if (!o) {
o = r;
r = "";
} else r += ":";
return [ r, o ];
}
var hashString = memorizeFuncWithLRUCache((async s => {
const r = writeString(s);
let o = await webcrypto.subtle.digest("SHA-256", r);
const u = s.length;
for (let s = 0; s < u; s++) o = await webcrypto.subtle.digest("SHA-256", r);
return uint8ArrayToHexString(new Uint8Array(o));
}));
async function path2id_base(s, r) {
if (s.startsWith(PREFIX_OBFUSCATED)) return s;
let o = s;
if (o.startsWith("_")) o = "/" + o;
if (!r) return o;
const [u, g] = expandFilePathPrefix(o);
if (g.startsWith(PREFIX_OBFUSCATED)) return o;
const _ = await hashString(r), m = await hashString(`${_}:${s}`);
return u + PREFIX_OBFUSCATED + m;
}
function id2path_base(s, r) {
if (r && (null == r ? void 0 : r.path)) return id2path_base(r.path);
if (s.startsWith(PREFIX_OBFUSCATED)) throw new Error("Entry has been obfuscated!");
const [o, u] = expandDocumentIDPrefix(s);
if (u.startsWith(PREFIX_OBFUSCATED)) throw new Error("Entry has been obfuscated!");
if (u.startsWith("/")) return u.substring(1); else return o + u;
}
function getPath(s) {
return id2path_base(s._id, s);
}
function stripPrefix(s) {
const [r, o] = s.split(":", 2);
if (!o) return r; else return o;
}
function shouldBeIgnored(s) {
if (s == FLAGMD_REDFLAG) return true;
if (s == FLAGMD_REDFLAG2) return true;
if (s == FLAGMD_REDFLAG2_HR) return true;
if (s == FLAGMD_REDFLAG3) return true;
if (s == FLAGMD_REDFLAG3_HR) return true;
if (s.startsWith(PREFIXMD_LOGFILE)) return true; else return false;
}
function isPlainText(s) {
if (s.endsWith(".md")) return true;
if (s.endsWith(".txt")) return true;
if (s.endsWith(".svg")) return true;
if (s.endsWith(".html")) return true;
if (s.endsWith(".csv")) return true;
if (s.endsWith(".css")) return true;
if (s.endsWith(".js")) return true;
if (s.endsWith(".xml")) return true;
if (s.endsWith(".canvas")) return true; else return false;
}
function shouldSplitAsPlainText(s) {
if (s.endsWith(".md")) return true;
if (s.endsWith(".txt")) return true;
if (s.endsWith(".canvas")) return true; else return false;
}
var matchOpts = {
platform: "linux",
dot: true,
flipNegate: true,
nocase: true
};
function isAccepted(s, r) {
if (-1 !== s.indexOf("./") || -1 !== s.indexOf("../")) return false;
const o = r.map((s => s.trim())).filter((s => s.length > 0 && !s.startsWith("#")));
let u;
for (const r of o) {
if (r.endsWith("/")) if (minimatch(s, `${r}**`, matchOpts)) return false;
const o = r.startsWith("!");
if (minimatch(s, r, matchOpts) || !r.endsWith("/") && minimatch(s, r + "/**", matchOpts)) u = o;
}
return u;
}
async function isAcceptedAll(s, r, o) {
const u = unique(s.substring(0, s.lastIndexOf("/")).split("/").reduce(((s, r) => [ ...s, s[s.length - 1] + "/" + r ]), [ "" ]).map((s => s.substring(1)))).reverse();
for (const g of u) for (const u of r) {
const r = g + "/" + u, _ = await o(r);
if (false === _) continue;
const m = isAccepted(s.substring(g.length ? g.length + 1 : 0), _);
if (void 0 !== m) return m;
}
return true;
}
function makeUniqueString() {
const s = [ ...Array(30) ].map((() => Math.floor(52 * Math.random()))).map((s => "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"[s])).join("");
return `${Date.now()}-${s}`;
}
function Semaphore(s, r) {
let o = s, u = 0, g = [];
function execProcess() {
g = g.filter((s => "DONE" != s.state));
for (const s of g) if ("NONE" == s.state) {
if (s.quantity + u > o) break;
s.state = "RUNNING";
u += s.quantity;
if (null == s ? void 0 : s.timer) clearTimeout(s.timer);
s.notify(true);
}
}
function release(s) {
const o = g.find((r => r.key == s));
if (!o) throw new Error("Missing locked semaphore!");
if ("RUNNING" == o.state) u -= o.quantity;
o.state = "DONE";
if (r) r(g.filter((s => "DONE" != s.state)));
execProcess();
}
return {
setLimit(s) {
o = s;
},
_acquire(s, r, u) {
const _ = makeUniqueString();
if (o < s) throw Error("Too big quantity");
let notify = s => {};
const m = new Promise((s => {
notify = r => {
if (r) s((() => {
release(_);
})); else s(false);
};
})), b = {
key: _,
notify,
semaphoreStopper: m,
quantity: s,
memo: r,
state: "NONE"
};
if (u) b.timer = setTimeout((() => {
release(_);
notify(false);
}), u);
g.push(b);
execProcess();
return m;
},
acquire(s = 1, r) {
return this._acquire(s, null != r ? r : "", 0);
},
tryAcquire(s = 1, r, o) {
return this._acquire(s, null != o ? o : "", r);
},
peekQueues: () => g
};
}
var semiStaticFieldBuffer, KeyBuffs = new Map, decKeyBuffs = new Map, KEY_RECYCLE_COUNT = 100, nonceBuffer = new Uint32Array(1);
async function getKeyForEncrypt(s, r) {
const o = `${s}-${r}`, u = KeyBuffs.get(o);
if (u) {
u.count--;
if (u.count > 0) return [ u.key, u.salt ];
u.count--;
}
const g = 15 - s.length, _ = r ? 1e3 * (g > 0 ? g : 0) + 121 - g : 1e5, m = (new TextEncoder).encode(s), b = await webcrypto.subtle.digest({
name: "SHA-256"
}, m), E = await webcrypto.subtle.importKey("raw", b, {
name: "PBKDF2"
}, false, [ "deriveKey" ]), w = webcrypto.getRandomValues(new Uint8Array(16)), S = await webcrypto.subtle.deriveKey({
name: "PBKDF2",
salt: w,
iterations: _,
hash: "SHA-256"
}, E, {
name: "AES-GCM",
length: 256
}, false, [ "encrypt" ]);
KeyBuffs.set(o, {
key: S,
salt: w,
count: KEY_RECYCLE_COUNT
});
return [ S, w ];
}
var keyGCCount = 5 * KEY_RECYCLE_COUNT, decKeyIdx = 0, decKeyMin = 0;
async function getKeyForDecryption(s, r, o) {
if (--keyGCCount < 0) {
keyGCCount = KEY_RECYCLE_COUNT;
const s = (decKeyIdx - decKeyMin) / 2;
for (const [r, o] of decKeyBuffs) {
if (o.count < s) decKeyBuffs.delete(r);
decKeyMin = decKeyIdx;
}
}
decKeyIdx++;
const u = s + uint8ArrayToHexString(r) + o, g = decKeyBuffs.get(u);
if (g) {
g.count = decKeyIdx;
return [ g.key, g.salt ];
}
const _ = 15 - s.length, m = o ? 1e3 * (_ > 0 ? _ : 0) + 121 - _ : 1e5, b = (new TextEncoder).encode(s), E = await webcrypto.subtle.digest({
name: "SHA-256"
}, b), w = await webcrypto.subtle.importKey("raw", E, {
name: "PBKDF2"
}, false, [ "deriveKey" ]), S = await webcrypto.subtle.deriveKey({
name: "PBKDF2",
salt: r,
iterations: m,
hash: "SHA-256"
}, w, {
name: "AES-GCM",
length: 256
}, false, [ "decrypt" ]);
decKeyBuffs.set(u, {
key: S,
salt: r,
count: 0
});
return [ S, r ];
}
function getSemiStaticField(s) {
if (null != semiStaticFieldBuffer && !s) 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(s, r, o) {
const [u, g] = await getKeyForEncrypt(r, o), _ = getSemiStaticField(), m = getNonce(), b = new Uint8Array([ ..._, ...new Uint8Array(m.buffer) ]), E = writeString(s), w = await webcrypto.subtle.encrypt({
name: "AES-GCM",
iv: b
}, u, E), S = "" + await arrayBufferToBase64Single(new Uint8Array(w));
return `%${uint8ArrayToHexString(b)}${uint8ArrayToHexString(g)}${S}`;
}
async function getKeyForObfuscatePath(s, r, o) {
const u = 15 - s.length, g = o ? 1e3 * (u > 0 ? u : 0) + 121 - u : 1e5, _ = (new TextEncoder).encode(s), m = await webcrypto.subtle.digest({
name: "SHA-256"
}, _), b = new Uint8Array(await webcrypto.subtle.digest({
name: "SHA-256"
}, new Uint8Array([ ...r, ..._ ]))), E = b.slice(0, 16), w = b.slice(16, 32), S = await webcrypto.subtle.importKey("raw", m, {
name: "PBKDF2"
}, false, [ "deriveKey" ]);
return [ await webcrypto.subtle.deriveKey({
name: "PBKDF2",
salt: E,
iterations: g,
hash: "SHA-256"
}, S, {
name: "AES-GCM",
length: 256
}, false, [ "encrypt" ]), E, w ];
}
async function obfuscatePath(s, r, o) {
const u = writeString(s), [g, _, m] = await getKeyForObfuscatePath(r, u, o), b = await webcrypto.subtle.encrypt({
name: "AES-GCM",
iv: m
}, g, u), E = await arrayBufferToBase64Single(new Uint8Array(b));
return `%${uint8ArrayToHexString(m)}${uint8ArrayToHexString(_)}${E}`;
}
async function decryptV2(s, r, o) {
try {
const u = s.substring(1, 33), g = s.substring(33, 65), _ = s.substring(65), [m] = await getKeyForDecryption(r, hexStringToUint8Array(g), o), b = hexStringToUint8Array(u), E = decodeBinary(_), w = await webcrypto.subtle.decrypt({
name: "AES-GCM",
iv: b
}, m, E);
return readString(new Uint8Array(w));
} catch (s) {
Logger("Couldn't decode! You should wrong the passphrases (V2)", LOG_LEVEL_VERBOSE);
Logger(s, LOG_LEVEL_VERBOSE);
throw s;
}
}
async function decrypt(s, r, o) {
try {
if ("%" == s[0]) return decryptV2(s, r, o);
if (!s.startsWith("[") || !s.endsWith("]")) throw new Error("Encrypted data corrupted!");
const u = s.substring(1, s.length - 1).split(",").map((s => '"' == s[0] ? s.substring(1, s.length - 1) : s)), [g, _, m] = u, [b] = await getKeyForDecryption(r, hexStringToUint8Array(m), o), E = hexStringToUint8Array(_), w = atob2(g), S = w.length, L = new Uint8Array(S);
for (let s = S; s >= 0; --s) L[s] = w.charCodeAt(s);
const O = await webcrypto.subtle.decrypt({
name: "AES-GCM",
iv: E
}, b, L), D = readString(new Uint8Array(O));
return JSON.parse(D);
} catch (s) {
Logger("Couldn't decode! You should wrong the passphrases", LOG_LEVEL_VERBOSE);
Logger(s, LOG_LEVEL_VERBOSE);
throw s;
}
}
async function tryDecrypt(s, r, o) {
if (!r) return false;
try {
return await decrypt(s, r, o);
} catch (s) {
return false;
}
}
async function testCrypt() {
const s = "supercalifragilisticexpialidocious", r = await encrypt(s, "passwordTest", false);
if (s != await decrypt(r, "passwordTest", false)) {
Logger("WARNING! Your device would not support encryption.", LOG_LEVEL_VERBOSE);
return false;
} else {
Logger("CRYPT LOGIC OK", LOG_LEVEL_VERBOSE);
return true;
}
}
var queueTails = new Map;
async function performTask(s) {
const r = s.key;
try {
const r = await s.task();
s.resolver(r);
} catch (r) {
s.rejector(r);
} finally {
const o = s.next;
queueTails.set(r, o);
if (o) performTask(o);
}
}
function _enqueue(s, r, {swapIfExist: o, shareResult: u} = {}) {
let resolver = () => {}, rejector = () => {};
const g = new Promise(((s, r) => {
resolver = s, rejector = r;
})), _ = {
task: r,
resolver,
rejector,
key: s
}, m = queueTails.get(s);
if (void 0 === m) {
queueTails.set(s, _);
performTask(_);
} else {
const r = m;
queueTails.set(s, _);
r.next = _;
if (o) r.rejector(new Error("Cancelled"));
}
return g;
}
function serialized(s, r) {
return _enqueue(s, r);
}
function shareRunningResult(s, r) {
const o = queueTails.get(s);
if (!o) return _enqueue(s, r);
const u = o.resolver, g = o.rejector;
let resolver = () => {}, rejector = () => {};
const _ = new Promise(((s, r) => {
resolver = s, rejector = r;
}));
o.resolver = s => {
u(s);
resolver(s);
};
o.rejector = s => {
g(s);
rejector(s);
};
return _;
}
function skipIfDuplicated(s, r) {
if (void 0 !== queueTails.get(s)) return Promise.resolve(null); else return _enqueue(s, r);
}
function isLockAcquired(s) {
return void 0 !== queueTails.get(s);
}
function unwrapTaskResult(s) {
if ("ok" in s) return s.ok;
if ("err" in s) return s.err;
}
function isTaskWaiting(s) {
if (s instanceof Promise) return false;
if (s instanceof Function) return true;
throw new Error("Invalid state");
}
async function wrapEachProcess(s, r) {
try {
return {
key: s,
ok: await r
};
} catch (r) {
return {
key: s,
err: r
};
}
}
async function* processAllTasksWithConcurrencyLimit(s, r) {
const o = new Map;
let u = 0;
const g = r.reverse();
for (;g.length > 0 || o.size > 0; ) {
e: for (;o.size < s && g.length > 0; ) {
const s = g.pop();
if (void 0 === s) break e;
u++;
const r = wrapEachProcess(u, isTaskWaiting(s) ? s() : s);
o.set(u, r);
}
const r = await Promise.race(o.values());
o.delete(r.key);
yield r;
}
}
async function mapAllTasksWithConcurrencyLimit(s, r) {
const o = new Map;
for await (const u of processAllTasksWithConcurrencyLimit(s, r)) o.set(u.key, u);
return [ ...o.entries() ].sort(((s, r) => s[0] - r[0])).map((s => s[1]));
}
var tasks = {};
function scheduleTask(s, r, o, u) {
if (!u || !(s in tasks)) {
cancelTask(s);
tasks[s] = setTimeout((async () => {
delete tasks[s];
await o();
}), r);
}
}
function cancelTask(s) {
if (s in tasks) {
clearTimeout(tasks[s]);
delete tasks[s];
}
}
function cancelAllTasks() {
for (const s in tasks) {
clearTimeout(tasks[s]);
delete tasks[s];
}
}
var intervals = {};
function cancelAllPeriodicTask() {
for (const s in intervals) {
clearInterval(intervals[s]);
delete intervals[s];
}
}
var processNo = 0, QueueProcessor = class {
constructor(s, r, o, u) {
this._queue = [];
this._enqueueProcessor = (s, r) => (s.push(r), s);
this._isSuspended = true;
this._nextProcessNeedsImmediate = false;
this._processing = void 0;
this._waitId = "";
this._instance = processNo++;
this._keepResultUntilDownstreamConnected = false;
this._keptResult = [];
this._onIdle = () => {};
this._runOnUpdateBatch = () => {};
this.concurrentLimit = 1;
this.batchSize = 1;
this.yieldThreshold = 1;
this.delay = 0;
this.interval = 0;
this.processingEntities = 0;
var g, _, m, b, E, w, S;
this._root = this;
this._processor = s;
this.batchSize = null != (g = null == r ? void 0 : r.batchSize) ? g : 1;
this.yieldThreshold = null != (m = null != (_ = null == r ? void 0 : r.yieldThreshold) ? _ : null == r ? void 0 : r.batchSize) ? m : 0;
this.concurrentLimit = null != (b = null == r ? void 0 : r.concurrentLimit) ? b : 1;
this.delay = null != (E = null == r ? void 0 : r.delay) ? E : 0;
this.maintainDelay = null != (w = null == r ? void 0 : r.maintainDelay) ? w : false;
this.interval = null != (S = null == r ? void 0 : r.interval) ? S : 0;
if (null == r ? void 0 : r.keepResultUntilDownstreamConnected) this._keepResultUntilDownstreamConnected = r.keepResultUntilDownstreamConnected;
if (null == r ? void 0 : r.remainingReactiveSource) this._remainingReactiveSource = null == r ? void 0 : r.remainingReactiveSource;
if (null == r ? void 0 : r.totalRemainingReactiveSource) this._totalRemainingReactiveSource = null == r ? void 0 : r.totalRemainingReactiveSource;
if (null == r ? void 0 : r.processingEntitiesReactiveSource) this._processingEntitiesReactiveSource = null == r ? void 0 : r.processingEntitiesReactiveSource;
if (void 0 !== (null == r ? void 0 : r.suspended)) this._isSuspended = null == r ? void 0 : r.suspended;
if (u) this.replaceEnqueueProcessor(u);
if (void 0 !== (null == r ? void 0 : r.pipeTo)) this.pipeTo(r.pipeTo);
if (o) this.enqueueAll(o);
}
get remaining() {
return this._queue.length + this.processingEntities;
}
get totalRemaining() {
var s;
return this.remaining + ((null == (s = this._pipeTo) ? void 0 : s.totalRemaining) || 0);
}
suspend() {
this._isSuspended = true;
return this;
}
resume() {
this._isSuspended = false;
this.requestNextFlush();
this._run();
return this;
}
resumePipeLine() {
var s;
null == (s = this._pipeTo) || s.resumePipeLine();
this.resume();
return this;
}
startPipeline() {
this._root.resumePipeLine();
return this;
}
get root() {
return this._root;
}
replaceEnqueueProcessor(s) {
this._enqueueProcessor = s;
return this;
}
modifyQueue(s) {
this._queue = s(this._queue);
this._updateBatchProcessStatus();
}
clearQueue() {
this._queue = [];
this._updateBatchProcessStatus();
}
onUpdateProgress(s) {
this._runOnUpdateBatch = s;
return this;
}
pipeTo(s) {
this._pipeTo = s;
this._pipeTo._root = this._root;
if (this._keptResult.length > 0) {
const s = [ ...this._keptResult ];
this._keptResult = [];
this._pipeTo.enqueueAll(s);
}
return s;
}
isIdle() {
return 0 == this._queue.length && 0 === this._processing && (!this._pipeTo ? true : this._pipeTo.isIdle());
}
onIdle(s) {
this._onIdle = s;
return this;
}
_updateReactiveSource() {
if (this._remainingReactiveSource) this._remainingReactiveSource.value = this.remaining;
if (this._totalRemainingReactiveSource) this._totalRemainingReactiveSource.value = this.totalRemaining;
if (this._processingEntitiesReactiveSource) this._processingEntitiesReactiveSource.value = this.processingEntities;
}
_updateBatchProcessStatus() {
this._updateReactiveSource();
this._runOnUpdateBatch();
}
_collectBatch() {
return this._queue.splice(0, this.batchSize);
}
_finalizeBatch(s) {
this._updateBatchProcessStatus();
}
_spawnProcess() {
setTimeout((() => this._process()), 0);
}
isAnyEntityRemaining() {
return 0 != this._queue.length;
}
enqueue(s) {
this._queue = this._enqueueProcessor(this._queue, s);
this._updateBatchProcessStatus();
this._run();
return this;
}
enqueueAll(s) {
let r = this._queue;
for (const o of s) r = this._enqueueProcessor(r, o);
this._queue = r;
this._updateBatchProcessStatus();
this._run();
return this;
}
requestNextFlush() {
this._nextProcessNeedsImmediate = true;
}
flush() {
if (!this._isSuspended) {
cancelTask(`kickProcess-${this._instance}`);
this._process();
return this.waitForAllDownstream();
}
}
waitForAllDownstream(s) {
if (this.isIdle()) return Promise.resolve(true);
if ("" == this._waitId) {
const s = Date.now() + "-" + Math.random();
this._waitId = s;
}
return waitForSignal(this._waitId, s);
}
waitForPipeline(s) {
this._root.startPipeline();
return this._root.waitForAllDownstream(s);
}
async _runProcessor(s) {
const r = await this._processor(s);
if (r) if (this._pipeTo) this._pipeTo.enqueueAll(r); else if (this._keepResultUntilDownstreamConnected) this._keptResult.push(...r);
}
async _process() {
if (void 0 === this._processing) this._processing = 0;
if (!(this._processing >= this.concurrentLimit)) {
if (this._isSuspended) return this._root._notifyIfIdle();
try {
this._processing++;
let s;
do {
s = this._collectBatch();
if (!s || 0 == s.length) break;
const r = s.length;
this.processingEntities += r;
this._updateReactiveSource();
if (this.isAnyEntityRemaining() && this._processing < this.concurrentLimit) this._spawnProcess();
try {
await this._runProcessor(s);
} catch (s) {
Logger("Processor error!");
Logger(s, LOG_LEVEL_VERBOSE);
} finally {
this.processingEntities -= r;
this._updateReactiveSource();
this._finalizeBatch(s);
}
} while (!(this._isSuspended || s && 0 != s.length));
} finally {
this._processing--;
}
if (this.isAnyEntityRemaining()) this._spawnProcess();
this._root._notifyIfIdle();
}
}
_notifyIfIdle() {
if (!this.isIdle()) return;
this._onIdle();
this._updateReactiveSource();
if ("" == this._waitId) return;
const s = this._waitId;
this._waitId = "";
sendSignal(s);
}
_run() {
if (this._isSuspended) return;
const s = 0 == this.delay || this.yieldThreshold > 0 && this._queue.length > this.yieldThreshold || this._nextProcessNeedsImmediate ? 0 : this.delay;
this._nextProcessNeedsImmediate = false;
if (this.interval) runWithStartInterval(`kickProcess-interval-${this._instance}`, this.interval, (async () => await scheduleTask(`kickProcess-${this._instance}`, s, (() => this._process()), this.maintainDelay))); else scheduleTask(`kickProcess-${this._instance}`, s, (() => this._process()), this.maintainDelay);
}
}, KeyedQueueProcessor = class extends QueueProcessor {
constructor(s, r) {
super((r => s(r.map((s => s.entity)))), r);
this.processingKeys = new Set;
}
_collectBatch() {
const s = [];
let r = 0;
do {
if (r >= this._queue.length) break;
const o = this._queue[r].key;
if (!this.processingKeys.has(o)) {
this.processingKeys.add(o);
s.push(this._queue[r]);
this._queue.splice(r, 1);
if (s.length >= this.batchSize) break;
} else r++;
} while (r + 1 < this._queue.length);
return s;
}
_finalizeBatch(s) {
for (const r of s) this.processingKeys.delete(r.key);
super._finalizeBatch(s);
}
isAnyEntityRemaining() {
return 0 != this._queue.filter((s => !this.processingKeys.has(s.key))).length;
}
enqueueWithKey(s, r) {
this.enqueue({
entity: r,
key: s
});
return this;
}
}, isValidRemoteCouchDBURI = s => {
if (s.startsWith("https://")) return true;
if (s.startsWith("http://")) return true; else return false;
};
function isCloudantURI(s) {
if (-1 !== s.indexOf(".cloudantnosqldb.") || -1 !== s.indexOf(".cloudant.com")) return true; else return false;
}
var checkRemoteVersion = async (s, r, o = VER) => {
try {
const u = await s.get(VERSIONINFO_DOCID);
if ("versioninfo" != u.type) return false;
const g = u.version;
if (g < o) if (await r(g, o)) {
await bumpRemoteVersion(s);
return true;
}
if (g == o) return true; else return false;
} catch (r) {
if (isErrorOfMissingDoc(r)) if (await bumpRemoteVersion(s)) return true; else return false;
throw r;
}
}, bumpRemoteVersion = async (s, r = VER) => {
const o = {
_id: VERSIONINFO_DOCID,
version: r,
type: "versioninfo"
}, u = await resolveWithIgnoreKnownError(s.get(VERSIONINFO_DOCID), o);
if ("versioninfo" != u.type) return false;
o._rev = u._rev;
await s.put(o);
return true;
}, checkSyncInfo = async s => {
try {
const r = await s.get(SYNCINFO_ID);
console.log(r);
return true;
} catch (r) {
if (isErrorOfMissingDoc(r)) {
const r = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", o = [ ...Array(30) ].map((s => Math.floor(Math.random() * r.length))).map((s => r[s])).join(""), u = {
_id: SYNCINFO_ID,
type: "syncinfo",
data: o
};
if (await s.put(u)) return true; else return false;
} else {
console.dir(r);
return false;
}
}
}, enableEncryption = (s, r, o, u) => {
const g = new Map;
s.transform({
incoming: async s => {
const u = {
...s
};
if (isEncryptedChunkEntry(u) || isSyncInfoEntry(u)) try {
u.data = await encrypt(u.data, r, o);
} catch (s) {
Logger("Encryption failed.", LOG_LEVEL_NOTICE);
Logger(s);
throw s;
}
if (isObfuscatedEntry(u)) try {
u.path = await obfuscatePath(getPath(u), r, o);
} catch (s) {
Logger("Encryption failed.", LOG_LEVEL_NOTICE);
Logger(s);
throw s;
}
return u;
},
outgoing: async s => {
var _, m;
const b = {
...s
}, E = isEncryptedChunkEntry(b) || isSyncInfoEntry(b), w = isObfuscatedEntry(b);
if (E || w) {
if (u && g.has(b._id)) return b;
try {
if (E) b.data = await decrypt(b.data, r, o);
if (w) b.path = await decrypt(getPath(b), r, o);
if (u) g.set(b._id, true);
} catch (s) {
if (o) try {
if (E) b.data = await decrypt(b.data, r, false);
if (w) b.path = await decrypt(getPath(b), r, o);
if (u) g.set(b._id, true);
} catch (s) {
if (u && "SyntaxError" == s.name) return b;
Logger("Decryption failed.", LOG_LEVEL_NOTICE);
Logger(s, LOG_LEVEL_VERBOSE);
Logger(`id:${b._id}-${null == (_ = b._rev) ? void 0 : _.substring(0, 10)}`, LOG_LEVEL_VERBOSE);
throw s;
} else {
Logger("Decryption failed.", LOG_LEVEL_NOTICE);
Logger(s, LOG_LEVEL_VERBOSE);
Logger(`id:${b._id}-${null == (m = b._rev) ? void 0 : m.substring(0, 10)}`, LOG_LEVEL_VERBOSE);
throw s;
}
}
}
return b;
}
});
};
function isErrorOfMissingDoc(s) {
return 404 == (s && (null == s ? void 0 : s.status));
}
async function prepareChunkDesignDoc(s) {
var r;
const o = {
_id: "_design/chunks",
_rev: void 0,
ver: 2,
views: {
collectDangling: {
map: (function(s) {
if (s._id.startsWith("h:")) emit([ s._id ], 0); else if ("children" in s) s.children.forEach((s => emit([ s ], 1)));
}).toString(),
reduce: "_sum"
}
}
};
let u = false;
try {
const g = await s.get(o._id);
if (null != (r = null == g ? void 0 : g.ver) ? r : 0 < o.ver) {
o._rev = g._rev;
u = true;
}
} catch (s) {
if (404 == s.status) u = true; else {
Logger("Failed to make design document for operating chunks");
Logger(s, LOG_LEVEL_VERBOSE);
return false;
}
}
try {
if (u) await s.put(o);
} catch (s) {
Logger("Failed to make design document for operating chunks");
Logger(s, LOG_LEVEL_VERBOSE);
return false;
}
return true;
}
async function collectChunksUsage(s) {
if (!await prepareChunkDesignDoc(s)) {
Logger("Could not prepare design document for operating chunks");
return [];
}
return (await s.query("chunks/collectDangling", {
reduce: true,
group: true
})).rows;
}
function collectUnreferencedChunks(s) {
return collectChunks(s, "DANGLING");
}
async function collectChunks(s, r) {
const o = await collectChunksUsage(s), u = ("ALL" == r ? o : o.filter((s => "DANGLING" == r ? 0 == s.value : 0 != s.value))).flatMap((s => s.key));
return (await s.allDocs({
keys: u
})).rows.filter((s => !("error" in s))).map((s => ({
id: s.id,
rev: s.value.rev
})));
}
async function collectUnbalancedChunkIDs(s, r) {
const o = await collectChunks(s, "INUSE"), u = await collectChunks(r, "INUSE");
return {
onlyOnLocal: o.filter((s => !u.some((r => r.id == s.id)))),
onlyOnRemote: u.filter((s => !o.some((r => r.id == s.id))))
};
}
async function purgeChunksLocal(s, r) {
await serialized("purge-local", (async () => {
try {
Logger(`Purging unused ${r.length} chunks `, LOG_LEVEL_NOTICE, "purge-local-backup");
const o = arrayToChunkedArray(r, 100);
let u = {
ok: 0,
exist: 0,
error: 0
};
for (const r of o) {
const o = (await s.allDocs({
keys: r.map((s => s.id)),
include_docs: true
})).rows.filter((s => "doc" in s)).map((s => {
const r = {
...s.doc
};
delete r._rev;
r._id = `_local/${r._id}`;
return r;
})), g = await s.bulkDocs(o);
u = g.map((s => ({
ok: "ok" in s ? 1 : 0,
exist: "status" in s && 409 == s.status ? 1 : 0,
error: "status" in s && 409 != s.status ? 1 : 0
}))).reduce(((s, r) => ({
ok: s.ok + r.ok,
exist: s.exist + r.exist,
error: s.error + r.error
})), u);
Logger(`Local chunk backed up: new:${u.ok} ,exist:${u.exist}, error:${u.error}`, LOG_LEVEL_NOTICE, "purge-local-backup");
const _ = g.filter((s => "error" in s && 409 != s.status));
for (const s of _) Logger(`Failed to back up: ${s.id} / ${s.rev}`, LOG_LEVEL_VERBOSE);
}
} catch (s) {
Logger("Could not back up chunks");
Logger(s, LOG_LEVEL_VERBOSE);
}
Logger(`Purging unused ${r.length} chunks... `, LOG_LEVEL_NOTICE, "purge-local");
const o = arrayToChunkedArray(r, 100);
let u = 0;
for (const g of o) {
const o = await s.purgeMulti(g.map((s => [ s.id, s.rev ])));
u += Object.values(o).filter((s => "ok" in s)).length;
Logger(`Purging: ${u} / ${r.length}`, LOG_LEVEL_NOTICE, "purge-local");
}
Logger(`Purging unused chunks done!: ${u} chunks has been deleted.`, LOG_LEVEL_NOTICE, "purge-local");
}));
}
var _requestToCouchDBFetch = async (s, r, o, u, g, _) => {
const m = String.fromCharCode.apply(null, [ ...writeString(`${r}:${o}`) ]), b = window.btoa(m), E = `${s}/${u}`, w = {
url: E,
method: _ || (g ? "PUT" : "GET"),
headers: new Headers({
authorization: "Basic " + b,
"content-type": "application/json"
}),
contentType: "application/json",
body: JSON.stringify(g)
};
return await fetch(E, w);
};
async function purgeChunksRemote(s, r) {
await serialized("purge-remote", (async () => {
const o = function makeChunkedArrayFromArray(s) {
const r = [];
for (let o = 0; o < s.length; o += 100) r.push(s.slice(o, o + 100));
return r;
}(r);
for (const r of o) {
const o = await _requestToCouchDBFetch(`${s.couchDB_URI}/${s.couchDB_DBNAME}`, s.couchDB_USER, s.couchDB_PASSWORD, "_purge", Object.fromEntries(r.map((s => [ s.id, [ s.rev ] ]))), "POST");
Logger(JSON.stringify(await o.json()), LOG_LEVEL_VERBOSE);
}
}));
}
function sizeToHumanReadable(s) {
if (!s) return "-";
const r = Math.floor(Math.log(s) / Math.log(1024));
return Number.parseInt((s / Math.pow(1024, r)).toFixed(2)) + " " + [ "B", "kB", "MB", "GB", "TB" ][r];
}
async function purgeUnreferencedChunks(s, r, o, u = false) {
const g = await s.info();
let _ = 0;
const getSize = function(s, r) {
var o, u;
return Number.parseInt(null != (u = null == (o = null == s ? void 0 : s.sizes) ? void 0 : o[r]) ? u : 0);
}, m = o ? "-remote" : "-local";
Logger(`${r ? "Counting" : "Cleaning"} ${o ? "remote" : "local"} database`, LOG_LEVEL_NOTICE);
if (o) Logger(`Database active-size: ${sizeToHumanReadable(getSize(g, "active"))}, external-size:${sizeToHumanReadable(getSize(g, "external"))}, file-size: ${sizeToHumanReadable(getSize(g, "file"))}`, LOG_LEVEL_NOTICE);
Logger(`Collecting unreferenced chunks on ${g.db_name}`, LOG_LEVEL_NOTICE, "gc-countchunk" + m);
const b = await collectUnreferencedChunks(s);
_ = b.length;
if (0 == b.length) Logger(`No unreferenced chunks! ${g.db_name}`, LOG_LEVEL_NOTICE, "gc-countchunk" + m); else {
Logger(`Number of unreferenced chunks on ${g.db_name}: ${b.length}`, LOG_LEVEL_NOTICE, "gc-countchunk" + m);
if (r) {
Logger(`DryRun of cleaning ${o ? "remote" : "local"} database up: Done`, LOG_LEVEL_NOTICE);
return _;
}
if (o) {
Logger("Cleaning unreferenced chunks on remote", LOG_LEVEL_NOTICE, "gc-purge" + m);
await purgeChunksRemote(o, b);
} else {
Logger("Cleaning unreferenced chunks on local", LOG_LEVEL_NOTICE, "gc-purge" + m);
await purgeChunksLocal(s, b);
}
Logger("Cleaning unreferenced chunks done!", LOG_LEVEL_NOTICE, "gc-purge" + m);
}
if (u) {
Logger("Compacting database...", LOG_LEVEL_NOTICE, "gc-compact" + m);
await s.compact();
Logger("Compacting database done", LOG_LEVEL_NOTICE, "gc-compact" + m);
}
if (o) {
const r = await s.info();
Logger(`Processed database active-size: ${sizeToHumanReadable(getSize(r, "active"))}, external-size:${sizeToHumanReadable(getSize(r, "external"))}, file-size: ${sizeToHumanReadable(getSize(r, "file"))}`, LOG_LEVEL_NOTICE);
Logger(`Reduced sizes: active-size: ${sizeToHumanReadable(getSize(g, "active") - getSize(r, "active"))}, external-size:${sizeToHumanReadable(getSize(g, "external") - getSize(r, "external"))}, file-size: ${sizeToHumanReadable(getSize(g, "file") - getSize(r, "file"))}`, LOG_LEVEL_NOTICE);
}
Logger(`Cleaning ${o ? "remote" : "local"} database up: Done`, LOG_LEVEL_NOTICE);
return _;
}
function transferChunks(s, r, o, u, g) {
let _ = 0;
const m = g.length;
return new QueueProcessor((async s => {
const r = s.map((s => s.id));
return (await u.allDocs({
keys: r
})).rows.filter((s => "error" in s && "not_found" == s.error)).map((s => s.key));
}), {
batchSize: 50,
concurrentLimit: 5,
suspended: true,
delay: 100
}, g).pipeTo(new QueueProcessor((async s => (await o.allDocs({
keys: s,
include_docs: true
})).rows.filter((s => !("error" in s))).map((s => s.doc))), {
batchSize: 25,
concurrentLimit: 1,
suspended: true,
delay: 100
})).pipeTo(new QueueProcessor((async o => {
try {
await u.bulkDocs(o, {
new_edits: false
});
} catch (s) {
Logger(`${r}: Something went wrong on balancing`, LOG_LEVEL_NOTICE);
Logger(s, LOG_LEVEL_VERBOSE);
} finally {
_ += o.length;
Logger(`${r}: ${_} / ${m}`, LOG_LEVEL_NOTICE, "balance-" + s);
}
}), {
batchSize: 100,
delay: 100,
concurrentLimit: 2,
suspended: false
})).startPipeline().waitForPipeline();
}
async function balanceChunkPurgedDBs(s, r) {
Logger("Complement missing chunks between databases", LOG_LEVEL_NOTICE);
try {
const {onlyOnLocal: o, onlyOnRemote: u} = await collectUnbalancedChunkIDs(s, r), g = transferChunks("l2r", "local -> remote", s, r, o), _ = transferChunks("r2l", "remote -> local", r, s, u);
await Promise.all([ g, _ ]);
Logger("local -> remote: Done", LOG_LEVEL_NOTICE, "balance-l2r");
Logger("remote -> local: Done", LOG_LEVEL_NOTICE, "balance-r2l");
} catch (s) {
Logger("Something went wrong on balancing!", LOG_LEVEL_NOTICE);
Logger(s, LOG_LEVEL_VERBOSE);
}
Logger("Complement completed!", LOG_LEVEL_NOTICE);
}
async function fetchAllUsedChunks(s, r) {
try {
const o = await collectChunks(r, "INUSE");
await transferChunks("r2l", "remote -> local", r, s, o);
Logger("remote -> local: Done", LOG_LEVEL_NOTICE, "balance-r2l");
} catch (s) {
Logger("Something went wrong on balancing!", LOG_LEVEL_NOTICE);
Logger(s, LOG_LEVEL_VERBOSE);
}
}
function resolveWithIgnoreKnownError(s, r) {
return new Promise(((o, u) => {
s.then(o).catch((s => isErrorOfMissingDoc(s) ? o(r) : u(s)));
}));
}
var _a, delay = s => new Promise((r => {
setTimeout((() => {
r();
}), s);
}));
function getDocData(s) {
return "string" == typeof s ? s : s.join("");
}
function isTextBlob(s) {
return "text/plain" === s.type;
}
function createTextBlob(s) {
const r = Array.isArray(s) ? s : [ s ];
return new Blob(r, {
endings: "transparent",
type: "text/plain"
});
}
function createBinaryBlob(s) {
return new Blob([ s ], {
endings: "transparent",
type: "application/octet-stream"
});
}
function createBlob(s) {
if (s instanceof Blob) return s;
if (s instanceof Uint8Array || s instanceof ArrayBuffer) return createBinaryBlob(s); else return createTextBlob(s);
}
function isTextDocument(s) {
if ("plain" == s.type) return true;
if ("plain" == s.datatype) return true;
if (isPlainText(s.path)) return true; else return false;
}
function readAsBlob(s) {
if (isTextDocument(s)) return createTextBlob(s.data); else return createBinaryBlob(decodeBinary(s.data));
}
function readContent(s) {
if (isTextDocument(s)) return getDocData(s.data); else return decodeBinary(s.data);
}
var isIndexDBCmpExist = "undefined" != typeof (null == (_a = null == window ? void 0 : window.indexedDB) ? void 0 : _a.cmp);
async function isDocContentSame(s, r) {
const o = createBlob(s), u = createBlob(r);
if (o.size != u.size) return false;
if (isIndexDBCmpExist) return 0 === window.indexedDB.cmp(await o.arrayBuffer(), await u.arrayBuffer());
const g = 1e4, _ = o.size;
let m = 0;
for (;m < _; ) {
const s = await o.slice(m, m + g).arrayBuffer(), r = await u.slice(m, m + g).arrayBuffer();
m += g;
if (await arrayBufferToBase64Single(s) != await arrayBufferToBase64Single(r)) return false;
}
return true;
}
function isObfuscatedEntry(s) {
if (s._id.startsWith(PREFIX_OBFUSCATED)) return true; else return false;
}
function isEncryptedChunkEntry(s) {
if (s._id.startsWith(PREFIX_ENCRYPTED_CHUNK)) return true; else return false;
}
function isSyncInfoEntry(s) {
if (s._id == SYNCINFO_ID) return true; else return false;
}
function memorizeFuncWithLRUCache(s) {
const r = new LRUCache(100, 1e5, true);
return o => {
if (r.has(o)) return r.get(o);
const u = s(o);
r.set(o, u);
return u;
};
}
var traps = {};
async function waitForSignal(s, r) {
return await waitForValue(s, r) !== RESULT_TIMED_OUT;
}
function waitForValue(s, r) {
let o, u;
const g = r ? setTimeout((() => {
if (s in traps) traps[s] = traps[s].filter((s => s != u));
if (o) o(RESULT_TIMED_OUT);
o = void 0;
}), r) : false;
return new Promise((r => {
if (!(s in traps)) traps[s] = [];
o = r;
u = s => {
if (g) clearTimeout(g);
r(s);
};
traps[s].push(u);
}));
}
function sendSignal(s) {
sendValue(s, true);
}
function sendValue(s, r) {
if (!(s in traps)) return;
const o = traps[s];
delete traps[s];
for (const s of o) s(r);
}
function onlyNot(s) {
return function _onlyNot(r) {
if (r === s) return false; else return true;
};
}
var lastProcessed = {};
function markInterval(s, r) {
var o;
const u = null != r ? r : Date.now();
if (null != (o = null == lastProcessed ? void 0 : lastProcessed[s]) ? o : 0 < u) lastProcessed[s] = u;
}
async function runWithStartInterval(s, r, o) {
const u = Date.now();
if (!(s in lastProcessed)) {
markInterval(s, u);
return await o();
}
const g = u - lastProcessed[s];
if (g < r) {
markInterval(s, u);
await delay(g);
}
markInterval(s);
return await o();
}
var ExportedSet, ExportedMap, globalConcurrencyController = Semaphore(50);
function* arrayToChunkedArray(s, r) {
const o = [ ...s ];
for (;o.length; ) {
const s = o.splice(0, r);
yield s;
}
}
function unique(s) {
return [ ...new Set(s) ];
}
function fireAndForget(s) {
if ("function" == typeof s) return fireAndForget(s());
s.then((s => {})).catch((s => {}));
}
function isObjectDifferent(s, r) {
if (typeof s != typeof r) return true;
if ("object" == typeof s) if (null === s || null === r) return s !== r; else return [ ...new Set([ ...Object.keys(s), ...Object.keys(r) ]) ].map((o => isObjectDifferent(null == s ? void 0 : s[o], null == r ? void 0 : r[o]))).some((s => true == s)); else return s !== r;
}
function determineTypeFromBlob(s) {
return isTextBlob(s) ? "plain" : "newnote";
}
function determineType(s, r) {
if (r instanceof Blob) return determineTypeFromBlob(r);
if (isPlainText(s)) return "plain";
if (r instanceof Uint8Array) return "newnote";
if (r instanceof ArrayBuffer) return "newnote"; else return "plain";
}
function isAnyNote(s) {
return "type" in s && ("newnote" == s.type || "plain" == s.type);
}
function createSavingEntryFromLoadedEntry(s) {
const r = readAsBlob(s), o = determineType(s.path, r);
return {
...s,
data: r,
datatype: o,
type: o,
children: []
};
}
function mangle(s) {
return "$" + s;
}
function unmangle(s) {
return s.substring(1);
}
function Map$1() {
this._store = {};
}
Map$1.prototype.get = function(s) {
var r = mangle(s);
return this._store[r];
};
Map$1.prototype.set = function(s, r) {
var o = mangle(s);
this._store[o] = r;
return true;
};
Map$1.prototype.has = function(s) {
return mangle(s) in this._store;
};
Map$1.prototype.keys = function() {
return Object.keys(this._store).map((s => unmangle(s)));
};
Map$1.prototype.delete = function(s) {
var r = mangle(s), o = r in this._store;
delete this._store[r];
return o;
};
Map$1.prototype.forEach = function(s) {
for (var r = Object.keys(this._store), o = 0, u = r.length; o < u; o++) {
var g = r[o];
s(this._store[g], g = unmangle(g));
}
};
Object.defineProperty(Map$1.prototype, "size", {
get: function() {
return Object.keys(this._store).length;
}
});
function Set$1(s) {
this._store = new Map$1;
if (s && Array.isArray(s)) for (var r = 0, o = s.length; r < o; r++) this.add(s[r]);
}
Set$1.prototype.add = function(s) {
return this._store.set(s, true);
};
Set$1.prototype.has = function(s) {
return this._store.has(s);
};
Set$1.prototype.forEach = function(s) {
this._store.forEach((function(r, o) {
s(o);
}));
};
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 s = Object.getOwnPropertyDescriptor(Map, Symbol.species);
return s && "get" in s && 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(s, r, o) {
super();
this.status = s;
this.name = r;
this.message = o;
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(s, r) {
function CustomPouchError(r) {
for (var o = Object.getOwnPropertyNames(s), u = 0, g = o.length; u < g; u++) if ("function" != typeof s[o[u]]) this[o[u]] = s[o[u]];
if (void 0 === this.stack) this.stack = (new Error).stack;
if (void 0 !== r) this.reason = r;
}
CustomPouchError.prototype = PouchError.prototype;
return new CustomPouchError(r);
}
function generateErrorFromResponse(s) {
if ("object" != typeof s) {
var r = s;
(s = UNKNOWN_ERROR).data = r;
}
if ("error" in s && "conflict" === s.error) {
s.name = "conflict";
s.status = 409;
}
if (!("name" in s)) s.name = s.error || "unknown";
if (!("status" in s)) s.status = 500;
if (!("message" in s)) s.message = s.message || s.reason;
if (!("stack" in s)) s.stack = (new Error).stack;
return s;
}
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(s) {
return "string" == typeof s && regex_default.test(s);
}
var i, validate_default = validate, byteToHex = [];
for (i = 0; i < 256; ++i) byteToHex.push((i + 256).toString(16).substr(1));
function stringify(s) {
var r = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0, o = (byteToHex[s[r + 0]] + byteToHex[s[r + 1]] + byteToHex[s[r + 2]] + byteToHex[s[r + 3]] + "-" + byteToHex[s[r + 4]] + byteToHex[s[r + 5]] + "-" + byteToHex[s[r + 6]] + byteToHex[s[r + 7]] + "-" + byteToHex[s[r + 8]] + byteToHex[s[r + 9]] + "-" + byteToHex[s[r + 10]] + byteToHex[s[r + 11]] + byteToHex[s[r + 12]] + byteToHex[s[r + 13]] + byteToHex[s[r + 14]] + byteToHex[s[r + 15]]).toLowerCase();
if (!validate_default(o)) throw TypeError("Stringified UUID is invalid");
return o;
}
var stringify_default = stringify;
function v4(s, r, o) {
var u = (s = s || {}).random || (s.rng || rng)();
u[6] = 15 & u[6] | 64;
u[8] = 63 & u[8] | 128;
if (r) {
o = o || 0;
for (var g = 0; g < 16; ++g) r[o + g] = u[g];
return r;
}
return stringify_default(u);
}
var v4_default = v4, thisAtob = function(s) {
return atob(s);
}, thisBtoa = function(s) {
return btoa(s);
};
function createBlob2(s, r) {
s = s || [];
r = r || {};
try {
return new Blob(s, r);
} catch (g) {
if ("TypeError" !== g.name) throw g;
for (var o = new ("undefined" != typeof BlobBuilder ? BlobBuilder : "undefined" != typeof MSBlobBuilder ? MSBlobBuilder : "undefined" != typeof MozBlobBuilder ? MozBlobBuilder : WebKitBlobBuilder), u = 0; u < s.length; u += 1) o.append(s[u]);
return o.getBlob(r.type);
}
}
function binaryStringToArrayBuffer(s) {
for (var r = s.length, o = new ArrayBuffer(r), u = new Uint8Array(o), g = 0; g < r; g++) u[g] = s.charCodeAt(g);
return o;
}
function binStringToBluffer(s, r) {
return createBlob2([ binaryStringToArrayBuffer(s) ], {
type: r
});
}
function b64ToBluffer(s, r) {
return binStringToBluffer(thisAtob(s), r);
}
function arrayBufferToBinaryString(s) {
for (var r = "", o = new Uint8Array(s), u = o.byteLength, g = 0; g < u; g++) r += String.fromCharCode(o[g]);
return r;
}
function readAsBinaryString(s, r) {
var o = new FileReader, u = "function" == typeof o.readAsBinaryString;
o.onloadend = function(s) {
var o = s.target.result || "";
if (u) return r(o);
r(arrayBufferToBinaryString(o));
};
if (u) o.readAsBinaryString(s); else o.readAsArrayBuffer(s);
}
function blobToBinaryString(s, r) {
readAsBinaryString(s, (function(s) {
r(s);
}));
}
function blobToBase64(s, r) {
blobToBinaryString(s, (function(s) {
r(thisBtoa(s));
}));
}
function readAsArrayBuffer(s, r) {
var o = new FileReader;
o.onloadend = function(s) {
var o = s.target.result || new ArrayBuffer(0);
r(o);
};
o.readAsArrayBuffer(s);
}
var import_spark_md5 = __toESM(require_spark_md5()), setImmediateShim = self.setImmediate || self.setTimeout, MD5_CHUNK_SIZE = 32768;
function rawToBase64(s) {
return thisBtoa(s);
}
function sliceBlob(s, r, o) {
if (s.webkitSlice) return s.webkitSlice(r, o); else return s.slice(r, o);
}
function appendBlob(s, r, o, u, g) {
if (o > 0 || u < r.size) r = sliceBlob(r, o, u);
readAsArrayBuffer(r, (function(r) {
s.append(r);
g();
}));
}
function appendString(s, r, o, u, g) {
if (o > 0 || u < r.length) r = r.substring(o, u);
s.appendBinary(r);
g();
}
function binaryMd5(s, r) {
var o = "string" == typeof s, u = o ? s.length : s.size, g = Math.min(MD5_CHUNK_SIZE, u), _ = Math.ceil(u / g), m = 0, b = o ? new import_spark_md5.default : new import_spark_md5.default.ArrayBuffer, E = o ? appendString : appendBlob;
function next() {
setImmediateShim(loadNextChunk);
}
function done() {
var s = rawToBase64(b.end(true));
r(s);
b.destroy();
}
function loadNextChunk() {
var r = m * g, o = r + g;
if (++m < _) E(b, s, r, o, next); else E(b, s, r, o, done);
}
loadNextChunk();
}
function stringMd5(s) {
return import_spark_md5.default.hash(s);
}
function isBinaryObject(s) {
return "undefined" != typeof ArrayBuffer && s instanceof ArrayBuffer || "undefined" != typeof Blob && s instanceof Blob;
}
function cloneArrayBuffer(s) {
if ("function" == typeof s.slice) return s.slice(0);
var r = new ArrayBuffer(s.byteLength), o = new Uint8Array(r), u = new Uint8Array(s);
o.set(u);
return r;
}
function cloneBinaryObject(s) {
if (s instanceof ArrayBuffer) return cloneArrayBuffer(s);
var r = s.size, o = s.type;
if ("function" == typeof s.slice) return s.slice(0, r, o); else return s.webkitSlice(0, r, o);
}
var funcToString = Function.prototype.toString, objectCtorString = funcToString.call(Object);
function isPlainObject(s) {
var r = Object.getPrototypeOf(s);
if (null === r) return true;
var o = r.constructor;
return "function" == typeof o && o instanceof o && funcToString.call(o) == objectCtorString;
}
function clone(s) {
var r, o, u;
if (!s || "object" != typeof s) return s;
if (Array.isArray(s)) {
r = [];
for (o = 0, u = s.length; o < u; o++) r[o] = clone(s[o]);
return r;
}
if (s instanceof Date && isFinite(s)) return s.toISOString();
if (isBinaryObject(s)) return cloneBinaryObject(s);
if (!isPlainObject(s)) return s;
r = {};
for (o in s) if (Object.prototype.hasOwnProperty.call(s, o)) {
var g = clone(s[o]);
if ("undefined" != typeof g) r[o] = g;
}
return r;
}
function once(s) {
var r = false;
return function(...o) {
if (r) throw new Error("once called more than once"); else {
r = true;
s.apply(this, o);
}
};
}
function toPromise(s) {
return function(...r) {
r = clone(r);
var o = this, u = "function" == typeof r[r.length - 1] ? r.pop() : false, g = new Promise((function(u, g) {
var _;
try {
var m = once((function(s, r) {
if (s) g(s); else u(r);
}));
r.push(m);
if ((_ = s.apply(o, r)) && "function" == typeof _.then) u(_);
} catch (s) {
g(s);
}
}));
if (u) g.then((function(s) {
u(null, s);
}), u);
return g;
};
}
function logApiCall(s, r, o) {
if (s.constructor.listeners("debug").length) {
for (var u = [ "api", s.name, r ], g = 0; g < o.length - 1; g++) u.push(o[g]);
s.constructor.emit("debug", u);
var _ = o[o.length - 1];
o[o.length - 1] = function(o, u) {
var g = [ "api", s.name, r ];
g = g.concat(o ? [ "error", o ] : [ "success", u ]);
s.constructor.emit("debug", g);
_(o, u);
};
}
}
function adapterFun(s, r) {
return toPromise((function(...o) {
if (this._closed) return Promise.reject(new Error("database is closed"));
if (this._destroyed) return Promise.reject(new Error("database is destroyed"));
var u = this;
logApiCall(u, s, o);
if (!this.taskqueue.isReady) return new Promise((function(r, g) {
u.taskqueue.addTask((function(_) {
if (_) g(_); else r(u[s].apply(u, o));
}));
})); else return r.apply(this, o);
}));
}
function pick(s, r) {
for (var o = {}, u = 0, g = r.length; u < g; u++) {
var _ = r[u];
if (_ in s) o[_] = s[_];
}
return o;
}
var hasLocal, MAX_NUM_CONCURRENT_REQUESTS = 6;
function identityFunction(s) {
return s;
}
function formatResultForOpenRevsGet(s) {
return [ {
ok: s
} ];
}
function bulkGet(s, r, o) {
var u = r.docs, g = new ExportedMap;
u.forEach((function(s) {
if (g.has(s.id)) g.get(s.id).push(s); else g.set(s.id, [ s ]);
}));
var _ = g.size, m = 0, b = new Array(_), E = [];
g.forEach((function(s, r) {
E.push(r);
}));
var w = 0;
(function nextBatch() {
if (!(w >= E.length)) {
var u = Math.min(w + MAX_NUM_CONCURRENT_REQUESTS, E.length), S = E.slice(w, u);
(function processBatch(u, E) {
u.forEach((function(u, w) {
var S = E + w, L = g.get(u), O = pick(L[0], [ "atts_since", "attachments" ]);
O.open_revs = L.map((function(s) {
return s.rev;
}));
O.open_revs = O.open_revs.filter(identityFunction);
var D = identityFunction;
if (0 === O.open_revs.length) {
delete O.open_revs;
D = formatResultForOpenRevsGet;
}
[ "revs", "attachments", "binary", "ajax", "latest" ].forEach((function(s) {
if (s in r) O[s] = r[s];
}));
s.get(u, O, (function(s, r) {
var g;
if (s) g = [ {
error: s
} ]; else g = D(r);
(function gotResult(s, r, u) {
b[s] = {
id: r,
docs: u
};
(function checkDone() {
if (++m === _) (function collapseResultsAndFinish() {
var s = [];
b.forEach((function(r) {
r.docs.forEach((function(o) {
s.push({
id: r.id,
docs: [ o ]
});
}));
}));
o(null, {
results: s
});
})();
})();
})(S, u, g);
nextBatch();
}));
}));
})(S, w);
w += S.length;
}
})();
}
try {
localStorage.setItem("_pouch_check_localstorage", 1);
hasLocal = !!localStorage.getItem("_pouch_check_localstorage");
} catch (s) {
hasLocal = false;
}
function hasLocalStorage() {
return hasLocal;
}
var assign$1, Changes = class extends import_events.default {
constructor() {
super();
this._listeners = {};
if (hasLocalStorage()) addEventListener("storage", (s => {
this.emit(s.key);
}));
}
addListener(s, r, o, u) {
if (!this._listeners[r]) {
var g = false, _ = this;
this._listeners[r] = eventFunction;
this.on(s, eventFunction);
}
function eventFunction() {
if (_._listeners[r]) if (!g) {
g = true;
var s = pick(u, [ "style", "include_docs", "attachments", "conflicts", "filter", "doc_ids", "view", "since", "query_params", "binary", "return_docs" ]);
o.changes(s).on("change", (function(s) {
if (s.seq > u.since && !u.cancelled) {
u.since = s.seq;
u.onChange(s);
}
})).on("complete", (function() {
if ("waiting" === g) (0, import_immediate.default)(eventFunction);
g = false;
})).on("error", (function onError() {
g = false;
}));
} else g = "waiting";
}
}
removeListener(s, r) {
if (r in this._listeners) {
super.removeListener(s, this._listeners[r]);
delete this._listeners[r];
}
}
notifyLocalWindows(s) {
if (hasLocalStorage()) localStorage[s] = "a" === localStorage[s] ? "b" : "a";
}
notify(s) {
this.emit(s);
this.notifyLocalWindows(s);
}
};
function guardedConsole(s) {
if ("undefined" != typeof console && "function" == typeof console[s]) {
var r = Array.prototype.slice.call(arguments, 1);
console[s].apply(console, r);
}
}
function randomNumber(s, r) {
var o = 6e5;
s = parseInt(s, 10) || 0;
if ((r = parseInt(r, 10)) != r || r <= s) r = (s || 1) << 1; else r += 1;
if (r > o) {
s = 3e5;
r = o;
}
return ~~((r - s) * Math.random() + s);
}
function defaultBackOff(s) {
var r = 0;
if (!s) r = 2e3;
return randomNumber(s, r);
}
function explainError(s, r) {
guardedConsole("info", "The above " + s + " is totally normal. " + r);
}
if ("function" == typeof Object.assign) assign$1 = Object.assign; else assign$1 = function(s) {
for (var r = Object(s), o = 1; o < arguments.length; o++) {
var u = arguments[o];
if (null != u) for (var g in u) if (Object.prototype.hasOwnProperty.call(u, g)) r[g] = u[g];
}
return r;
};
var assign$2 = assign$1;
function tryFilter(s, r, o) {
try {
return !s(r, o);
} catch (s) {
var u = "Filter function threw: " + s.toString();
return createError(BAD_REQUEST, u);
}
}
function filterChange(s) {
var r = {}, o = s.filter && "function" == typeof s.filter;
r.query = s.query_params;
return function filter3(u) {
if (!u.doc) u.doc = {};
var g = o && tryFilter(s.filter, u.doc, r);
if ("object" == typeof g) return g;
if (g) return false;
if (!s.include_docs) delete u.doc; else if (!s.attachments) for (var _ in u.doc._attachments) if (Object.prototype.hasOwnProperty.call(u.doc._attachments, _)) u.doc._attachments[_].stub = true;
return true;
};
}
function flatten(s) {
for (var r = [], o = 0, u = s.length; o < u; o++) r = r.concat(s[o]);
return r;
}
function f() {}
var res, hasName = f.name;
if (hasName) res = function(s) {
return s.name;
}; else res = function(s) {
var r = s.toString().match(/^\s*function\s*(?:(\S+)\s*)?\(/);
if (r && r[1]) return r[1]; else return "";
};
function invalidIdError(s) {
var r;
if (!s) r = createError(MISSING_ID); else if ("string" != typeof s) r = createError(INVALID_ID); else if (/^_/.test(s) && !/^_(design|local)/.test(s)) r = createError(RESERVED_ID);
if (r) throw r;
}
function isRemote(s) {
if ("boolean" == typeof s._remote) return s._remote;
if ("function" == typeof s.type) {
guardedConsole("warn", "db.type() is deprecated and will be removed in a future version of PouchDB");
return "http" === s.type();
}
return false;
}
function listenerCount(s, r) {
return "listenerCount" in s ? s.listenerCount(r) : import_events.default.listenerCount(s, r);
}
function parseDesignDocFunctionName(s) {
if (!s) return null;
var r = s.split("/");
if (2 === r.length) return r;
if (1 === r.length) return [ s, s ]; else return null;
}
function normalizeDesignDocFunctionName(s) {
var r = parseDesignDocFunctionName(s);
return r ? r.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(s) {
for (var r = parser.exec(s), o = {}, u = 14; u--; ) {
var g = keys[u], _ = r[u] || "", m = -1 !== [ "user", "password" ].indexOf(g);
o[g] = m ? decodeURIComponent(_) : _;
}
o[qName] = {};
o[keys[12]].replace(qParser, (function(s, r, u) {
if (r) o[qName][r] = u;
}));
return o;
}
function scopeEval(s, r) {
var o = [], u = [];
for (var g in r) if (Object.prototype.hasOwnProperty.call(r, g)) {
o.push(g);
u.push(r[g]);
}
o.push(s);
return Function.apply(null, o).apply(null, u);
}
function upsert(s, r, o) {
return s.get(r).catch((function(s) {
if (404 !== s.status) throw s;
return {};
})).then((function(u) {
var g = u._rev, _ = o(u);
if (!_) return {
updated: false,
rev: g
};
_._id = r;
_._rev = g;
return tryAndPut(s, _, o);
}));
}
function tryAndPut(s, r, o) {
return s.put(r).then((function(s) {
return {
updated: true,
rev: s.rev
};
}), (function(u) {
if (409 !== u.status) throw u;
return upsert(s, r._id, o);
}));
}
function rev(s, r) {
if (!r) return v4_default().replace(/-/g, "").toLowerCase();
var o = assign$2({}, s);
delete o._rev_tree;
return stringMd5(JSON.stringify(o));
}
var uuid = v4_default;
function winningRev(s) {
for (var r, o, u, g, _ = s.rev_tree.slice(); g = _.pop(); ) {
var m = g.ids, b = m[2], E = g.pos;
if (!b.length) {
var w = !!m[1].deleted, S = m[0];
if (!r || (u !== w ? u : o !== E ? o < E : r < S)) {
r = S;
o = E;
u = w;
}
} else for (var L = 0, O = b.length; L < O; L++) _.push({
pos: E + 1,
ids: b[L]
});
}
return o + "-" + r;
}
function traverseRevTree(s, r) {
for (var o, u = s.slice(); o = u.pop(); ) for (var g = o.pos, _ = o.ids, m = _[2], b = r(0 === m.length, g, _[0], o.ctx, _[1]), E = 0, w = m.length; E < w; E++) u.push({
pos: g + 1,
ids: m[E],
ctx: b
});
}
function sortByPos(s, r) {
return s.pos - r.pos;
}
function collectLeaves(s) {
var r = [];
traverseRevTree(s, (function(s, o, u, g, _) {
if (s) r.push({
rev: o + "-" + u,
pos: o,
opts: _
});
}));
r.sort(sortByPos).reverse();
for (var o = 0, u = r.length; o < u; o++) delete r[o].pos;
return r;
}
function collectConflicts(s) {
for (var r = winningRev(s), o = collectLeaves(s.rev_tree), u = [], g = 0, _ = o.length; g < _; g++) {
var m = o[g];
if (m.rev !== r && !m.opts.deleted) u.push(m.rev);
}
return u;
}
function compactTree(s) {
var r = [];
traverseRevTree(s.rev_tree, (function(s, o, u, g, _) {
if ("available" === _.status && !s) {
r.push(o + "-" + u);
_.status = "missing";
}
}));
return r;
}
function findPathToLeaf(s, r) {
let o = [];
const u = s.slice();
let g;
for (;g = u.pop(); ) {
const {pos: s, ids: _} = g, m = `${s}-${_[0]}`, b = _[2];
o.push(m);
if (m === r) {
if (0 !== b.length) throw new Error("The requested revision is not a leaf");
return o.reverse();
}
if (0 === b.length || b.length > 1) o = [];
for (let r = 0, o = b.length; r < o; r++) u.push({
pos: s + 1,
ids: b[r]
});
}
if (0 === o.length) throw new Error("The requested revision does not exist");
return o.reverse();
}
function rootToLeaf(s) {
for (var r, o = [], u = s.slice(); r = u.pop(); ) {
var g = r.pos, _ = r.ids, m = _[0], b = _[1], E = _[2], w = 0 === E.length, S = r.history ? r.history.slice() : [];
S.push({
id: m,
opts: b
});
if (w) o.push({
pos: g + 1 - S.length,
ids: S
});
for (var L = 0, O = E.length; L < O; L++) u.push({
pos: g + 1,
ids: E[L],
history: S
});
}
return o.reverse();
}
function sortByPos$1(s, r) {
return s.pos - r.pos;
}
function binarySearch(s, r, o) {
for (var u, g = 0, _ = s.length; g < _; ) if (o(s[u = g + _ >>> 1], r) < 0) g = u + 1; else _ = u;
return g;
}
function insertSorted(s, r, o) {
var u = binarySearch(s, r, o);
s.splice(u, 0, r);
}
function pathToTree(s, r) {
for (var o, u, g = r, _ = s.length; g < _; g++) {
var m = s[g], b = [ m.id, m.opts, [] ];
if (u) {
u[2].push(b);
u = b;
} else o = u = b;
}
return o;
}
function compareTree(s, r) {
return s[0] < r[0] ? -1 : 1;
}
function mergeTree(s, r) {
for (var o = [ {
tree1: s,
tree2: r
} ], u = false; o.length > 0; ) {
var g = o.pop(), _ = g.tree1, m = g.tree2;
if (_[1].status || m[1].status) _[1].status = "available" === _[1].status || "available" === m[1].status ? "available" : "missing";
for (var b = 0; b < m[2].length; b++) if (_[2][0]) {
for (var E = false, w = 0; w < _[2].length; w++) if (_[2][w][0] === m[2][b][0]) {
o.push({
tree1: _[2][w],
tree2: m[2][b]
});
E = true;
}
if (!E) {
u = "new_branch";
insertSorted(_[2], m[2][b], compareTree);
}
} else {
u = "new_leaf";
_[2][0] = m[2][b];
}
}
return {
conflicts: u,
tree: s
};
}
function doMerge(s, r, o) {
var u, g = [], _ = false, m = false;
if (!s.length) return {
tree: [ r ],
conflicts: "new_leaf"
};
for (var b = 0, E = s.length; b < E; b++) {
var w = s[b];
if (w.pos === r.pos && w.ids[0] === r.ids[0]) {
u = mergeTree(w.ids, r.ids);
g.push({
pos: w.pos,
ids: u.tree
});
_ = _ || u.conflicts;
m = true;
} else if (true !== o) {
var S = w.pos < r.pos ? w : r, L = w.pos < r.pos ? r : w, O = L.pos - S.pos, D = [], k = [];
k.push({
ids: S.ids,
diff: O,
parent: null,
parentIdx: null
});
for (;k.length > 0; ) {
var C = k.pop();
if (0 !== C.diff) for (var T = C.ids[2], I = 0, A = T.length; I < A; I++) k.push({
ids: T[I],
diff: C.diff - 1,
parent: C.ids,
parentIdx: I
}); else if (C.ids[0] === L.ids[0]) D.push(C);
}
var R = D[0];
if (!R) g.push(w); else {
u = mergeTree(R.ids, L.ids);
R.parent[2][R.parentIdx] = u.tree;
g.push({
pos: S.pos,
ids: S.ids
});
_ = _ || u.conflicts;
m = true;
}
} else g.push(w);
}
if (!m) g.push(r);
g.sort(sortByPos$1);
return {
tree: g,
conflicts: _ || "internal_node"
};
}
function stem(s, r) {
for (var o, u, g = rootToLeaf(s), _ = 0, m = g.length; _ < m; _++) {
var b, E = g[_], w = E.ids;
if (w.length > r) {
if (!o) o = {};
var S = w.length - r;
b = {
pos: E.pos + S,
ids: pathToTree(w, S)
};
for (var L = 0; L < S; L++) {
var O = E.pos + L + "-" + w[L].id;
o[O] = true;
}
} else b = {
pos: E.pos,
ids: pathToTree(w, 0)
};
if (u) u = doMerge(u, b, true).tree; else u = [ b ];
}
if (o) traverseRevTree(u, (function(s, r, u) {
delete o[r + "-" + u];
}));
return {
tree: u,
revs: o ? Object.keys(o) : []
};
}
function merge(s, r, o) {
var u = doMerge(s, r), g = stem(u.tree, o);
return {
tree: g.tree,
stemmedRevs: g.revs,
conflicts: u.conflicts
};
}
function removeLeafFromRevTree(s, r) {
return s.flatMap((s => (s = removeLeafFromPath(s, r)) ? [ s ] : []));
}
function removeLeafFromPath(s, r) {
const o = clone(s), u = [ o ];
let g;
for (;g = u.pop(); ) {
const {pos: s, ids: [_, , m], parent: b} = g;
if (0 === m.length && `${s}-${_}` === r) {
if (!b) return null;
b.ids[2] = b.ids[2].filter((function(s) {
return s[0] !== _;
}));
return o;
}
for (let r = 0, o = m.length; r < o; r++) u.push({
pos: s + 1,
ids: m[r],
parent: g
});
}
return o;
}
function revExists(s, r) {
for (var o, u = s.slice(), g = r.split("-"), _ = parseInt(g[0], 10), m = g[1]; o = u.pop(); ) {
if (o.pos === _ && o.ids[0] === m) return true;
for (var b = o.ids[2], E = 0, w = b.length; E < w; E++) u.push({
pos: o.pos + 1,
ids: b[E]
});
}
return false;
}
function getTrees(s) {
return s.ids;
}
function isDeleted(s, r) {
if (!r) r = winningRev(s);
for (var o, u = r.substring(r.indexOf("-") + 1), g = s.rev_tree.map(getTrees); o = g.pop(); ) {
if (o[0] === u) return !!o[1].deleted;
g = g.concat(o[2]);
}
}
function isLocalId(s) {
return /^_local/.test(s);
}
function latest(s, r) {
for (var o, u = r.rev_tree.slice(); o = u.pop(); ) {
var g = o.pos, _ = o.ids, m = _[0], b = _[1], E = _[2], w = 0 === E.length, S = o.history ? o.history.slice() : [];
S.push({
id: m,
pos: g,
opts: b
});
if (w) for (var L = 0, O = S.length; L < O; L++) {
var D = S[L];
if (D.pos + "-" + D.id === s) return g + "-" + m;
}
for (var k = 0, C = E.length; k < C; k++) u.push({
pos: g + 1,
ids: E[k],
history: S
});
}
throw new Error("Unable to resolve latest revision for id " + r.id + ", rev " + s);
}
var import_events2 = __toESM(require_events()), a = "undefined" != typeof AbortController ? AbortController : function() {
return {
abort: function() {}
};
}, f2 = fetch, h = Headers;
function pad(s, r, o) {
for (var u = "", g = o - s.length; u.length < g; ) u += r;
return u;
}
function padLeft(s, r, o) {
return pad(s, r, o) + s;
}
var MIN_MAGNITUDE = -324, MAGNITUDE_DIGITS = 3, SEP = "";
function collate(s, r) {
if (s === r) return 0;
s = normalizeKey(s);
r = normalizeKey(r);
var o = collationIndex(s), u = collationIndex(r);
if (o - u != 0) return o - u;
switch (typeof s) {
case "number":
return s - r;
case "boolean":
return s < r ? -1 : 1;
case "string":
return stringCollate(s, r);
}
return Array.isArray(s) ? arrayCollate(s, r) : objectCollate(s, r);
}
function normalizeKey(s) {
switch (typeof s) {
case "undefined":
return null;
case "number":
if (s === 1 / 0 || s === -1 / 0 || isNaN(s)) return null; else return s;
case "object":
var r = s;
if (Array.isArray(s)) {
var o = s.length;
s = new Array(o);
for (var u = 0; u < o; u++) s[u] = normalizeKey(r[u]);
} else if (s instanceof Date) return s.toJSON(); else if (null !== s) {
s = {};
for (var g in r) if (Object.prototype.hasOwnProperty.call(r, g)) {
var _ = r[g];
if ("undefined" != typeof _) s[g] = normalizeKey(_);
}
}
}
return s;
}
function indexify(s) {
if (null !== s) switch (typeof s) {
case "boolean":
return s ? 1 : 0;
case "number":
return numToIndexableString(s);
case "string":
return s.replace(/\u0002/g, "").replace(/\u0001/g, "").replace(/\u0000/g, "");
case "object":
var r = Array.isArray(s), o = r ? s : Object.keys(s), u = -1, g = o.length, _ = "";
if (r) for (;++u < g; ) _ += toIndexableString(o[u]); else for (;++u < g; ) {
var m = o[u];
_ += toIndexableString(m) + toIndexableString(s[m]);
}
return _;
}
return "";
}
function toIndexableString(s) {
return collationIndex(s = normalizeKey(s)) + SEP + indexify(s) + "\0";
}
function parseNumber(s, r) {
var o, u = r;
if ("1" === s[r]) {
o = 0;
r++;
} else {
var g = "0" === s[r];
r++;
var _ = "", m = s.substring(r, r + MAGNITUDE_DIGITS), b = parseInt(m, 10) + MIN_MAGNITUDE;
if (g) b = -b;
r += MAGNITUDE_DIGITS;
for (;;) {
var E = s[r];
if ("\0" === E) break; else _ += E;
r++;
}
if (1 === (_ = _.split(".")).length) o = parseInt(_, 10); else o = parseFloat(_[0] + "." + _[1]);
if (g) o -= 10;
if (0 !== b) o = parseFloat(o + "e" + b);
}
return {
num: o,
length: r - u
};
}
function pop(s, r) {
var o = s.pop();
if (r.length) {
var u = r[r.length - 1];
if (o === u.element) {
r.pop();
u = r[r.length - 1];
}
var g = u.element, _ = u.index;
if (Array.isArray(g)) g.push(o); else if (_ === s.length - 2) g[s.pop()] = o; else s.push(o);
}
}
function parseIndexableString(s) {
for (var r = [], o = [], u = 0; ;) {
var g = s[u++];
if ("\0" === g) if (1 === r.length) return r.pop(); else {
pop(r, o);
continue;
}
switch (g) {
case "1":
r.push(null);
break;
case "2":
r.push("1" === s[u]);
u++;
break;
case "3":
var _ = parseNumber(s, u);
r.push(_.num);
u += _.length;
break;
case "4":
for (var m = ""; ;) {
var b = s[u];
if ("\0" === b) break;
m += b;
u++;
}
m = m.replace(/\u0001\u0001/g, "\0").replace(/\u0001\u0002/g, "").replace(/\u0002\u0002/g, "");
r.push(m);
break;
case "5":
var E = {
element: [],
index: r.length
};
r.push(E.element);
o.push(E);
break;
case "6":
var w = {
element: {},
index: r.length
};
r.push(w.element);
o.push(w);
break;
default:
throw new Error("bad collationIndex or unexpectedly reached end of input: " + g);
}
}
}
function arrayCollate(s, r) {
for (var o = Math.min(s.length, r.length), u = 0; u < o; u++) {
var g = collate(s[u], r[u]);
if (0 !== g) return g;
}
return s.length === r.length ? 0 : s.length > r.length ? 1 : -1;
}
function stringCollate(s, r) {
return s === r ? 0 : s > r ? 1 : -1;
}
function objectCollate(s, r) {
for (var o = Object.keys(s), u = Object.keys(r), g = Math.min(o.length, u.length), _ = 0; _ < g; _++) {
var m = collate(o[_], u[_]);
if (0 !== m) return m;
if (0 !== (m = collate(s[o[_]], r[u[_]]))) return m;
}
return o.length === u.length ? 0 : o.length > u.length ? 1 : -1;
}
function collationIndex(s) {
var r = [ "boolean", "number", "string", "object" ].indexOf(typeof s);
if (~r) {
if (null === s) return 1;
if (Array.isArray(s)) return 5; else return r < 3 ? r + 2 : r + 3;
}
if (Array.isArray(s)) return 5;
}
function numToIndexableString(s) {
if (0 === s) return "1";
var r = s.toExponential().split(/e\+?/), o = parseInt(r[1], 10), u = s < 0, g = u ? "0" : "2", _ = padLeft(((u ? -o : o) - MIN_MAGNITUDE).toString(), "0", MAGNITUDE_DIGITS);
g += SEP + _;
var m = Math.abs(parseFloat(r[0]));
if (u) m = 10 - m;
var b = m.toFixed(20);
b = b.replace(/\.?0+$/, "");
return g += SEP + b;
}
function getFieldFromDoc(s, r) {
for (var o = s, u = 0, g = r.length; u < g && (o = o[r[u]]); u++) ;
return o;
}
function setFieldInDoc(s, r, o) {
for (var u = 0, g = r.length; u < g - 1; u++) {
var _ = r[u];
s = s[_] = s[_] || {};
}
s[r[g - 1]] = o;
}
function compare(s, r) {
return s < r ? -1 : s > r ? 1 : 0;
}
function parseField(s) {
for (var r = [], o = "", u = 0, g = s.length; u < g; u++) {
var _ = s[u];
if (u > 0 && "\\" === s[u - 1] && ("$" === _ || "." === _)) o = o.substring(0, o.length - 1) + _; else if ("." === _) {
r.push(o);
o = "";
} else o += _;
}
r.push(o);
return r;
}
var combinationFields = [ "$or", "$nor", "$not" ];
function isCombinationalField(s) {
return combinationFields.indexOf(s) > -1;
}
function getKey(s) {
return Object.keys(s)[0];
}
function getValue(s) {
return s[getKey(s)];
}
function mergeAndedSelectors(s) {
var r = {}, o = {
$or: true,
$nor: true
};
s.forEach((function(s) {
Object.keys(s).forEach((function(u) {
var g = s[u];
if ("object" != typeof g) g = {
$eq: g
};
if (isCombinationalField(u)) if (g instanceof Array) {
if (o[u]) {
o[u] = false;
r[u] = g;
return;
}
var _ = [];
r[u].forEach((function(s) {
Object.keys(g).forEach((function(r) {
var o = g[r], u = Math.max(Object.keys(s).length, Object.keys(o).length), m = mergeAndedSelectors([ s, o ]);
if (!(Object.keys(m).length <= u)) _.push(m);
}));
}));
r[u] = _;
} else r[u] = mergeAndedSelectors([ g ]); else {
var m = r[u] = r[u] || {};
Object.keys(g).forEach((function(s) {
var r = g[s];
if ("$gt" === s || "$gte" === s) return mergeGtGte(s, r, m); else if ("$lt" === s || "$lte" === s) return mergeLtLte(s, r, m); else if ("$ne" === s) return mergeNe(r, m); else if ("$eq" === s) return mergeEq(r, m); else if ("$regex" === s) return mergeRegex(r, m);
m[s] = r;
}));
}
}));
}));
return r;
}
function mergeGtGte(s, r, o) {
if ("undefined" == typeof o.$eq) if ("undefined" != typeof o.$gte) {
if ("$gte" === s) {
if (r > o.$gte) o.$gte = r;
} else if (r >= o.$gte) {
delete o.$gte;
o.$gt = r;
}
} else if ("undefined" != typeof o.$gt) {
if ("$gte" === s) {
if (r > o.$gt) {
delete o.$gt;
o.$gte = r;
}
} else if (r > o.$gt) o.$gt = r;
} else o[s] = r;
}
function mergeLtLte(s, r, o) {
if ("undefined" == typeof o.$eq) if ("undefined" != typeof o.$lte) {
if ("$lte" === s) {
if (r < o.$lte) o.$lte = r;
} else if (r <= o.$lte) {
delete o.$lte;
o.$lt = r;
}
} else if ("undefined" != typeof o.$lt) {
if ("$lte" === s) {
if (r < o.$lt) {
delete o.$lt;
o.$lte = r;
}
} else if (r < o.$lt) o.$lt = r;
} else o[s] = r;
}
function mergeNe(s, r) {
if ("$ne" in r) r.$ne.push(s); else r.$ne = [ s ];
}
function mergeEq(s, r) {
delete r.$gt;
delete r.$gte;
delete r.$lt;
delete r.$lte;
delete r.$ne;
r.$eq = s;
}
function mergeRegex(s, r) {
if ("$regex" in r) r.$regex.push(s); else r.$regex = [ s ];
}
function mergeAndedSelectorsNested(s) {
for (var r in s) {
if (Array.isArray(s)) for (var o in s) if (s[o]["$and"]) s[o] = mergeAndedSelectors(s[o]["$and"]);
var u = s[r];
if ("object" == typeof u) mergeAndedSelectorsNested(u);
}
return s;
}
function isAndInSelector(s, r) {
for (var o in s) {
if ("$and" === o) r = true;
var u = s[o];
if ("object" == typeof u) r = isAndInSelector(u, r);
}
return r;
}
function massageSelector(s) {
var r = clone(s);
if (isAndInSelector(r, false)) if ("$and" in (r = mergeAndedSelectorsNested(r))) r = mergeAndedSelectors(r["$and"]);
[ "$or", "$nor" ].forEach((function(s) {
if (s in r) r[s].forEach((function(s) {
for (var r = Object.keys(s), o = 0; o < r.length; o++) {
var u = r[o], g = s[u];
if ("object" != typeof g || null === g) s[u] = {
$eq: g
};
}
}));
}));
if ("$not" in r) r["$not"] = mergeAndedSelectors([ r["$not"] ]);
for (var o = Object.keys(r), u = 0; u < o.length; u++) {
var g = o[u], _ = r[g];
if ("object" != typeof _ || null === _) _ = {
$eq: _
};
r[g] = _;
}
normalizeArrayOperators(r);
return r;
}
function normalizeArrayOperators(s) {
Object.keys(s).forEach((function(r) {
var o = s[r];
if (Array.isArray(o)) o.forEach((function(s) {
if (s && "object" == typeof s) normalizeArrayOperators(s);
})); else if ("$ne" === r) s.$ne = [ o ]; else if ("$regex" === r) s.$regex = [ o ]; else if (o && "object" == typeof o) normalizeArrayOperators(o);
}));
}
function createFieldSorter(s) {
function getFieldValuesAsArray(r) {
return s.map((function(s) {
var o = parseField(getKey(s));
return getFieldFromDoc(r, o);
}));
}
return function(s, r) {
var o = collate(getFieldValuesAsArray(s.doc), getFieldValuesAsArray(r.doc));
if (0 !== o) return o; else return compare(s.doc._id, r.doc._id);
};
}
function filterInMemoryFields(s, r, o) {
s = s.filter((function(s) {
return rowFilter(s.doc, r.selector, o);
}));
if (r.sort) {
var u = createFieldSorter(r.sort);
s = s.sort(u);
if ("string" != typeof r.sort[0] && "desc" === getValue(r.sort[0])) s = s.reverse();
}
if ("limit" in r || "skip" in r) {
var g = r.skip || 0, _ = ("limit" in r ? r.limit : s.length) + g;
s = s.slice(g, _);
}
return s;
}
function rowFilter(s, r, o) {
return o.every((function(o) {
var u = r[o], g = parseField(o), _ = getFieldFromDoc(s, g);
if (isCombinationalField(o)) return matchCominationalSelector(o, u, s); else return matchSelector(u, s, g, _);
}));
}
function matchSelector(s, r, o, u) {
if (!s) return true;
if ("object" == typeof s) return Object.keys(s).every((function(g) {
var _ = s[g];
if (0 === g.indexOf("$")) return match2(g, r, _, o, u); else {
var m = parseField(g);
if (void 0 === u && "object" != typeof _ && m.length > 0) return false;
var b = getFieldFromDoc(u, m);
if ("object" == typeof _) return matchSelector(_, r, o, b); else return match2("$eq", r, _, m, b);
}
})); else return s === u;
}
function matchCominationalSelector(s, r, o) {
if ("$or" === s) return r.some((function(s) {
return rowFilter(o, s, Object.keys(s));
}));
if ("$not" === s) return !rowFilter(o, r, Object.keys(r)); else return !r.find((function(s) {
return rowFilter(o, s, Object.keys(s));
}));
}
function match2(s, r, o, u, g) {
if (!matchers[s]) throw new Error('unknown operator "' + s + '" - should be one of $eq, $lte, $lt, $gt, $gte, $exists, $ne, $in, $nin, $size, $mod, $regex, $elemMatch, $type, $allMatch or $all');
return matchers[s](r, o, u, g);
}
function fieldExists(s) {
return "undefined" != typeof s && null !== s;
}
function fieldIsNotUndefined(s) {
return "undefined" != typeof s;
}
function modField(s, r) {
if ("number" != typeof s || parseInt(s, 10) !== s) return false; else return s % r[0] === r[1];
}
function arrayContainsValue(s, r) {
return r.some((function(r) {
if (s instanceof Array) return s.some((function(s) {
return 0 === collate(r, s);
})); else return 0 === collate(r, s);
}));
}
function arrayContainsAllValues(s, r) {
return r.every((function(r) {
return s.some((function(s) {
return 0 === collate(r, s);
}));
}));
}
function arraySize(s, r) {
return s.length === r;
}
function regexMatch(s, r) {
return new RegExp(r).test(s);
}
function typeMatch(s, r) {
switch (r) {
case "null":
return null === s;
case "boolean":
return "boolean" == typeof s;
case "number":
return "number" == typeof s;
case "string":
return "string" == typeof s;
case "array":
return s instanceof Array;
case "object":
return "[object Object]" === {}.toString.call(s);
}
}
var matchers = {
$elemMatch: function(s, r, o, u) {
if (!Array.isArray(u)) return false;
if (0 === u.length) return false;
if ("object" == typeof u[0] && null !== u[0]) return u.some((function(s) {
return rowFilter(s, r, Object.keys(r));
})); else return u.some((function(u) {
return matchSelector(r, s, o, u);
}));
},
$allMatch: function(s, r, o, u) {
if (!Array.isArray(u)) return false;
if (0 === u.length) return false;
if ("object" == typeof u[0] && null !== u[0]) return u.every((function(s) {
return rowFilter(s, r, Object.keys(r));
})); else return u.every((function(u) {
return matchSelector(r, s, o, u);
}));
},
$eq: function(s, r, o, u) {
return fieldIsNotUndefined(u) && 0 === collate(u, r);
},
$gte: function(s, r, o, u) {
return fieldIsNotUndefined(u) && collate(u, r) >= 0;
},
$gt: function(s, r, o, u) {
return fieldIsNotUndefined(u) && collate(u, r) > 0;
},
$lte: function(s, r, o, u) {
return fieldIsNotUndefined(u) && collate(u, r) <= 0;
},
$lt: function(s, r, o, u) {
return fieldIsNotUndefined(u) && collate(u, r) < 0;
},
$exists: function(s, r, o, u) {
if (r) return fieldIsNotUndefined(u); else return !fieldIsNotUndefined(u);
},
$mod: function(s, r, o, u) {
return fieldExists(u) && modField(u, r);
},
$ne: function(s, r, o, u) {
return r.every((function(s) {
return 0 !== collate(u, s);
}));
},
$in: function(s, r, o, u) {
return fieldExists(u) && arrayContainsValue(u, r);
},
$nin: function(s, r, o, u) {
return fieldExists(u) && !arrayContainsValue(u, r);
},
$size: function(s, r, o, u) {
return fieldExists(u) && Array.isArray(u) && arraySize(u, r);
},
$all: function(s, r, o, u) {
return Array.isArray(u) && arrayContainsAllValues(u, r);
},
$regex: function(s, r, o, u) {
return fieldExists(u) && "string" == typeof u && r.every((function(s) {
return regexMatch(u, s);
}));
},
$type: function(s, r, o, u) {
return typeMatch(u, r);
}
};
function matchesSelector(s, r) {
if ("object" != typeof r) throw new Error("Selector error: expected a JSON object");
var o = filterInMemoryFields([ {
doc: s
} ], {
selector: r = massageSelector(r)
}, Object.keys(r));
return o && 1 === o.length;
}
function evalFilter(s) {
return scopeEval('"use strict";\nreturn ' + s + ";", {});
}
function evalView(s) {
return scopeEval([ "return function(doc) {", ' "use strict";', " var emitted = false;", " var emit = function (a, b) {", " emitted = true;", " };", " var view = " + s + ";", " view(doc);", " if (emitted) {", " return true;", " }", "};" ].join("\n"), {});
}
function validate2(s, r) {
if (s.selector) if (s.filter && "_selector" !== s.filter) {
var o = "string" == typeof s.filter ? s.filter : "function";
return r(new Error('selector invalid for filter "' + o + '"'));
}
r();
}
function normalize(s) {
if (s.view && !s.filter) s.filter = "_view";
if (s.selector && !s.filter) s.filter = "_selector";
if (s.filter && "string" == typeof s.filter) if ("_view" === s.filter) s.view = normalizeDesignDocFunctionName(s.view); else s.filter = normalizeDesignDocFunctionName(s.filter);
}
function shouldFilter(s, r) {
return r.filter && "string" == typeof r.filter && !r.doc_ids && !isRemote(s.db);
}
function filter2(s, r) {
var o = r.complete;
if ("_view" === r.filter) {
if (!r.view || "string" != typeof r.view) {
var u = createError(BAD_REQUEST, "`view` filter parameter not found or invalid.");
return o(u);
}
var g = parseDesignDocFunctionName(r.view);
s.db.get("_design/" + g[0], (function(u, _) {
if (s.isCancelled) return o(null, {
status: "cancelled"
});
if (u) return o(generateErrorFromResponse(u));
var m = _ && _.views && _.views[g[1]] && _.views[g[1]].map;
if (!m) return o(createError(MISSING_DOC, _.views ? "missing json key: " + g[1] : "missing json key: views"));
r.filter = evalView(m);
s.doChanges(r);
}));
} else if (r.selector) {
r.filter = function(s) {
return matchesSelector(s, r.selector);
};
s.doChanges(r);
} else {
var _ = parseDesignDocFunctionName(r.filter);
s.db.get("_design/" + _[0], (function(u, g) {
if (s.isCancelled) return o(null, {
status: "cancelled"
});
if (u) return o(generateErrorFromResponse(u));
var m = g && g.filters && g.filters[_[1]];
if (!m) return o(createError(MISSING_DOC, g && g.filters ? "missing json key: " + _[1] : "missing json key: filters"));
r.filter = evalFilter(m);
s.doChanges(r);
}));
}
}
function applyChangesFilterPlugin(s) {
s._changesFilterPlugin = {
validate: validate2,
normalize,
shouldFilter,
filter: filter2
};
}
var index_browser_es_default = applyChangesFilterPlugin;
function tryCatchInChangeListener(s, r, o, u) {
try {
s.emit("change", r, o, u);
} catch (s) {
guardedConsole("error", 'Error in .on("change", function):', s);
}
}
function processChange(s, r, o) {
var u = [ {
rev: s._rev
} ];
if ("all_docs" === o.style) u = collectLeaves(r.rev_tree).map((function(s) {
return {
rev: s.rev
};
}));
var g = {
id: r.id,
changes: u,
doc: s
};
if (isDeleted(r, s._rev)) g.deleted = true;
if (o.conflicts) {
g.doc._conflicts = collectConflicts(r);
if (!g.doc._conflicts.length) delete g.doc._conflicts;
}
return g;
}
var Changes2 = class extends import_events2.default {
constructor(s, r, o) {
super();
this.db = s;
var u = (r = r ? clone(r) : {}).complete = once(((r, o) => {
if (r) {
if (listenerCount(this, "error") > 0) this.emit("error", r);
} else this.emit("complete", o);
this.removeAllListeners();
s.removeListener("destroyed", onDestroy2);
}));
if (o) {
this.on("complete", (function(s) {
o(null, s);
}));
this.on("error", o);
}
const onDestroy2 = () => {
this.cancel();
};
s.once("destroyed", onDestroy2);
r.onChange = (s, r, o) => {
if (!this.isCancelled) tryCatchInChangeListener(this, s, r, o);
};
var g = new Promise((function(s, o) {
r.complete = function(r, u) {
if (r) o(r); else s(u);
};
}));
this.once("cancel", (function() {
s.removeListener("destroyed", onDestroy2);
r.complete(null, {
status: "cancelled"
});
}));
this.then = g.then.bind(g);
this["catch"] = g["catch"].bind(g);
this.then((function(s) {
u(null, s);
}), u);
if (!s.taskqueue.isReady) s.taskqueue.addTask((s => {
if (s) r.complete(s); else if (this.isCancelled) this.emit("cancel"); else this.validateChanges(r);
})); else this.validateChanges(r);
}
cancel() {
this.isCancelled = true;
if (this.db.taskqueue.isReady) this.emit("cancel");
}
validateChanges(s) {
var r = s.complete;
if (PouchDB._changesFilterPlugin) PouchDB._changesFilterPlugin.validate(s, (o => {
if (o) return r(o);
this.doChanges(s);
})); else this.doChanges(s);
}
doChanges(s) {
var r = s.complete;
if ("live" in (s = clone(s)) && !("continuous" in s)) s.continuous = s.live;
s.processChange = processChange;
if ("latest" === s.since) s.since = "now";
if (!s.since) s.since = 0;
if ("now" !== s.since) {
if (PouchDB._changesFilterPlugin) {
PouchDB._changesFilterPlugin.normalize(s);
if (PouchDB._changesFilterPlugin.shouldFilter(this, s)) return PouchDB._changesFilterPlugin.filter(this, s);
} else [ "doc_ids", "filter", "selector", "view" ].forEach((function(r) {
if (r in s) guardedConsole("warn", 'The "' + r + '" 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 s)) s.descending = false;
s.limit = 0 === s.limit ? 1 : s.limit;
s.complete = r;
var o = this.db._changes(s);
if (o && "function" == typeof o.cancel) {
const s = this.cancel;
this.cancel = (...r) => {
o.cancel();
s.apply(this, r);
};
}
} else this.db.info().then((o => {
if (!this.isCancelled) {
s.since = o.update_seq;
this.doChanges(s);
} else r(null, {
status: "cancelled"
});
}), r);
}
};
function compare2(s, r) {
return s < r ? -1 : s > r ? 1 : 0;
}
function yankError(s, r) {
return function(o, u) {
if (o || u[0] && u[0].error) {
(o = o || u[0]).docId = r;
s(o);
} else s(null, u.length ? u[0] : u);
};
}
function cleanDocs(s) {
for (var r = 0; r < s.length; r++) {
var o = s[r];
if (o._deleted) delete o._attachments; else if (o._attachments) for (var u = Object.keys(o._attachments), g = 0; g < u.length; g++) {
var _ = u[g];
o._attachments[_] = pick(o._attachments[_], [ "data", "digest", "content_type", "length", "revpos", "stub" ]);
}
}
}
function compareByIdThenRev(s, r) {
var o = compare2(s._id, r._id);
if (0 !== o) return o; else return compare2(s._revisions ? s._revisions.start : 0, r._revisions ? r._revisions.start : 0);
}
function computeHeight(s) {
var r = {}, o = [];
traverseRevTree(s, (function(s, u, g, _) {
var m = u + "-" + g;
if (s) r[m] = 0;
if (void 0 !== _) o.push({
from: _,
to: m
});
return m;
}));
o.reverse();
o.forEach((function(s) {
if (void 0 === r[s.from]) r[s.from] = 1 + r[s.to]; else r[s.from] = Math.min(r[s.from], 1 + r[s.to]);
}));
return r;
}
function allDocsKeysParse(s) {
var r = "limit" in s ? s.keys.slice(s.skip, s.limit + s.skip) : s.skip > 0 ? s.keys.slice(s.skip) : s.keys;
s.keys = r;
s.skip = 0;
delete s.limit;
if (s.descending) {
r.reverse();
s.descending = false;
}
}
function doNextCompaction(s) {
var r = s._compactionQueue[0], o = r.opts, u = r.callback;
s.get("_local/compaction").catch((function() {
return false;
})).then((function(r) {
if (r && r.last_seq) o.last_seq = r.last_seq;
s._compact(o, (function(r, o) {
if (r) u(r); else u(null, o);
(0, import_immediate.default)((function() {
s._compactionQueue.shift();
if (s._compactionQueue.length) doNextCompaction(s);
}));
}));
}));
}
function appendPurgeSeq(s, r, o) {
return s.get("_local/purges").then((function(s) {
const u = s.purgeSeq + 1;
s.purges.push({
docId: r,
rev: o,
purgeSeq: u
});
if (s.purges.length > self.purged_infos_limit) s.purges.splice(0, s.purges.length - self.purged_infos_limit);
s.purgeSeq = u;
return s;
})).catch((function(s) {
if (404 !== s.status) throw s;
return {
_id: "_local/purges",
purges: [ {
docId: r,
rev: o,
purgeSeq: 0
} ],
purgeSeq: 0
};
})).then((function(r) {
return s.put(r);
}));
}
function attachmentNameError(s) {
if ("_" === s.charAt(0)) return s + " 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(s, r, o) {
if ("function" == typeof r) {
o = r;
r = {};
}
if ("object" != typeof s || Array.isArray(s)) return o(createError(NOT_AN_OBJECT));
this.bulkDocs({
docs: [ s ]
}, r, yankError(o, s._id));
})).bind(this);
this.put = adapterFun("put", (function(s, r, o) {
if ("function" == typeof r) {
o = r;
r = {};
}
if ("object" != typeof s || Array.isArray(s)) return o(createError(NOT_AN_OBJECT));
invalidIdError(s._id);
if (isLocalId(s._id) && "function" == typeof this._putLocal) if (s._deleted) return this._removeLocal(s, o); else return this._putLocal(s, o);
const putDoc = o => {
if ("function" == typeof this._put && false !== r.new_edits) this._put(s, r, o); else this.bulkDocs({
docs: [ s ]
}, r, yankError(o, s._id));
};
if (r.force && s._rev) {
(function transformForceOptionToNewEditsOption() {
var o = s._rev.split("-"), u = o[1], g = parseInt(o[0], 10) + 1, _ = rev();
s._revisions = {
start: g,
ids: [ _, u ]
};
s._rev = g + "-" + _;
r.new_edits = false;
})();
putDoc((function(r) {
var u = r ? null : {
ok: true,
id: s._id,
rev: s._rev
};
o(r, u);
}));
} else putDoc(o);
})).bind(this);
this.putAttachment = adapterFun("putAttachment", (function(s, r, o, u, g) {
var _ = this;
if ("function" == typeof g) {
g = u;
u = o;
o = null;
}
if ("undefined" == typeof g) {
g = u;
u = o;
o = null;
}
if (!g) guardedConsole("warn", "Attachment", r, "on document", s, "is missing content_type");
function createAttachment(s) {
var o = "_rev" in s ? parseInt(s._rev, 10) : 0;
s._attachments = s._attachments || {};
s._attachments[r] = {
content_type: g,
data: u,
revpos: ++o
};
return _.put(s);
}
return _.get(s).then((function(s) {
if (s._rev !== o) throw createError(REV_CONFLICT);
return createAttachment(s);
}), (function(r) {
if (r.reason === MISSING_DOC.message) return createAttachment({
_id: s
}); else throw r;
}));
})).bind(this);
this.removeAttachment = adapterFun("removeAttachment", (function(s, r, o, u) {
this.get(s, ((s, g) => {
if (!s) if (g._rev === o) {
if (!g._attachments) return u();
delete g._attachments[r];
if (0 === Object.keys(g._attachments).length) delete g._attachments;
this.put(g, u);
} else u(createError(REV_CONFLICT)); else u(s);
}));
})).bind(this);
this.remove = adapterFun("remove", (function(s, r, o, u) {
var g;
if ("string" == typeof r) {
g = {
_id: s,
_rev: r
};
if ("function" == typeof o) {
u = o;
o = {};
}
} else {
g = s;
if ("function" == typeof r) {
u = r;
o = {};
} else {
u = o;
o = r;
}
}
(o = o || {}).was_delete = true;
var _ = {
_id: g._id,
_rev: g._rev || o.rev,
_deleted: true
};
if (isLocalId(_._id) && "function" == typeof this._removeLocal) return this._removeLocal(g, u);
this.bulkDocs({
docs: [ _ ]
}, o, yankError(u, _._id));
})).bind(this);
this.revsDiff = adapterFun("revsDiff", (function(s, r, o) {
if ("function" == typeof r) {
o = r;
r = {};
}
var u = Object.keys(s);
if (!u.length) return o(null, {});
var g = 0, _ = new ExportedMap;
function addToMissing(s, r) {
if (!_.has(s)) _.set(s, {
missing: []
});
_.get(s).missing.push(r);
}
u.map((function(r) {
this._getRevisionTree(r, (function(m, b) {
if (m && 404 === m.status && "missing" === m.message) _.set(r, {
missing: s[r]
}); else if (m) return o(m); else (function processDoc(r, o) {
var u = s[r].slice(0);
traverseRevTree(o, (function(s, o, g, _, m) {
var b = o + "-" + g, E = u.indexOf(b);
if (-1 !== E) {
u.splice(E, 1);
if ("available" !== m.status) addToMissing(r, b);
}
}));
u.forEach((function(s) {
addToMissing(r, s);
}));
})(r, b);
if (++g === u.length) {
var E = {};
_.forEach((function(s, r) {
E[r] = s;
}));
return o(null, E);
}
}));
}), this);
})).bind(this);
this.bulkGet = adapterFun("bulkGet", (function(s, r) {
bulkGet(this, s, r);
})).bind(this);
this.compactDocument = adapterFun("compactDocument", (function(s, r, o) {
this._getRevisionTree(s, ((u, g) => {
if (u) return o(u);
var _ = computeHeight(g), m = [], b = [];
Object.keys(_).forEach((function(s) {
if (_[s] > r) m.push(s);
}));
traverseRevTree(g, (function(s, r, o, u, g) {
var _ = r + "-" + o;
if ("available" === g.status && -1 !== m.indexOf(_)) b.push(_);
}));
this._doCompaction(s, b, o);
}));
})).bind(this);
this.compact = adapterFun("compact", (function(s, r) {
if ("function" == typeof s) {
r = s;
s = {};
}
s = s || {};
this._compactionQueue = this._compactionQueue || [];
this._compactionQueue.push({
opts: s,
callback: r
});
if (1 === this._compactionQueue.length) doNextCompaction(this);
})).bind(this);
this.get = adapterFun("get", (function(s, r, o) {
if ("function" == typeof r) {
o = r;
r = {};
}
if ("string" != typeof s) return o(createError(INVALID_ID));
if (isLocalId(s) && "function" == typeof this._getLocal) return this._getLocal(s, o);
var u = [];
const finishOpenRevs = () => {
var g = [], _ = u.length;
if (!_) return o(null, g);
u.forEach((u => {
this.get(s, {
rev: u,
revs: r.revs,
latest: r.latest,
attachments: r.attachments,
binary: r.binary
}, (function(s, r) {
if (!s) {
for (var m, b = 0, E = g.length; b < E; b++) if (g[b].ok && g[b].ok._rev === r._rev) {
m = true;
break;
}
if (!m) g.push({
ok: r
});
} else g.push({
missing: u
});
if (! --_) o(null, g);
}));
}));
};
if (!r.open_revs) return this._get(s, r, ((u, g) => {
if (u) {
u.docId = s;
return o(u);
}
var _ = g.doc, m = g.metadata, b = g.ctx;
if (r.conflicts) {
var E = collectConflicts(m);
if (E.length) _._conflicts = E;
}
if (isDeleted(m, _._rev)) _._deleted = true;
if (r.revs || r.revs_info) {
for (var w = _._rev.split("-"), S = parseInt(w[0], 10), L = w[1], O = rootToLeaf(m.rev_tree), D = null, k = 0; k < O.length; k++) {
var C = O[k], T = C.ids.map((function(s) {
return s.id;
})).indexOf(L);
if (T === S - 1 || !D && -1 !== T) D = C;
}
if (!D) {
(u = new Error("invalid rev tree")).docId = s;
return o(u);
}
var I = D.ids.map((function(s) {
return s.id;
})).indexOf(_._rev.split("-")[1]) + 1, A = D.ids.length - I;
D.ids.splice(I, A);
D.ids.reverse();
if (r.revs) _._revisions = {
start: D.pos + D.ids.length - 1,
ids: D.ids.map((function(s) {
return s.id;
}))
};
if (r.revs_info) {
var R = D.pos + D.ids.length;
_._revs_info = D.ids.map((function(s) {
return {
rev: --R + "-" + s.id,
status: s.opts.status
};
}));
}
}
if (r.attachments && _._attachments) {
var x = _._attachments, P = Object.keys(x).length;
if (0 === P) return o(null, _);
Object.keys(x).forEach((s => {
this._getAttachment(_._id, s, x[s], {
rev: _._rev,
binary: r.binary,
ctx: b
}, (function(r, u) {
var g = _._attachments[s];
g.data = u;
delete g.stub;
delete g.length;
if (! --P) o(null, _);
}));
}));
} else {
if (_._attachments) for (var N in _._attachments) if (Object.prototype.hasOwnProperty.call(_._attachments, N)) _._attachments[N].stub = true;
o(null, _);
}
})); else if ("all" === r.open_revs) this._getRevisionTree(s, (function(s, r) {
if (s) return o(s);
u = collectLeaves(r).map((function(s) {
return s.rev;
}));
finishOpenRevs();
})); else if (Array.isArray(r.open_revs)) {
u = r.open_revs;
for (var g = 0; g < u.length; g++) {
var _ = u[g];
if (!("string" == typeof _ && /^\d+-/.test(_))) return o(createError(INVALID_REV));
}
finishOpenRevs();
} else return o(createError(UNKNOWN_ERROR, "function_clause"));
})).bind(this);
this.getAttachment = adapterFun("getAttachment", (function(s, r, o, u) {
if (o instanceof Function) {
u = o;
o = {};
}
this._get(s, o, ((g, _) => {
if (g) return u(g);
if (_.doc._attachments && _.doc._attachments[r]) {
o.ctx = _.ctx;
o.binary = true;
this._getAttachment(s, r, _.doc._attachments[r], o, u);
} else return u(createError(MISSING_DOC));
}));
})).bind(this);
this.allDocs = adapterFun("allDocs", (function(s, r) {
if ("function" == typeof s) {
r = s;
s = {};
}
s.skip = "undefined" != typeof s.skip ? s.skip : 0;
if (s.start_key) s.startkey = s.start_key;
if (s.end_key) s.endkey = s.end_key;
if ("keys" in s) {
if (!Array.isArray(s.keys)) return r(new TypeError("options.keys must be an array"));
var o = [ "startkey", "endkey", "key" ].filter((function(r) {
return r in s;
}))[0];
if (o) {
r(createError(QUERY_PARSE_ERROR, "Query parameter `" + o + "` is not compatible with multi-get"));
return;
}
if (!isRemote(this)) {
allDocsKeysParse(s);
if (0 === s.keys.length) return this._allDocs({
limit: 0
}, r);
}
}
return this._allDocs(s, r);
})).bind(this);
this.close = adapterFun("close", (function(s) {
this._closed = true;
this.emit("closed");
return this._close(s);
})).bind(this);
this.info = adapterFun("info", (function(s) {
this._info(((r, o) => {
if (r) return s(r);
o.db_name = o.db_name || this.name;
o.auto_compaction = !!(this.auto_compaction && !isRemote(this));
o.adapter = this.adapter;
s(null, o);
}));
})).bind(this);
this.id = adapterFun("id", (function(s) {
return this._id(s);
})).bind(this);
this.bulkDocs = adapterFun("bulkDocs", (function(s, r, o) {
if ("function" == typeof r) {
o = r;
r = {};
}
r = r || {};
if (Array.isArray(s)) s = {
docs: s
};
if (!s || !s.docs || !Array.isArray(s.docs)) return o(createError(MISSING_BULK_DOCS));
for (var u = 0; u < s.docs.length; ++u) if ("object" != typeof s.docs[u] || Array.isArray(s.docs[u])) return o(createError(NOT_AN_OBJECT));
var g;
s.docs.forEach((function(s) {
if (s._attachments) Object.keys(s._attachments).forEach((function(r) {
g = g || attachmentNameError(r);
if (!s._attachments[r].content_type) guardedConsole("warn", "Attachment", r, "on document", s._id, "is missing content_type");
}));
}));
if (g) return o(createError(BAD_REQUEST, g));
if (!("new_edits" in r)) if ("new_edits" in s) r.new_edits = s.new_edits; else r.new_edits = true;
var _ = this;
if (!r.new_edits && !isRemote(_)) s.docs.sort(compareByIdThenRev);
cleanDocs(s.docs);
var m = s.docs.map((function(s) {
return s._id;
}));
this._bulkDocs(s, r, (function(s, u) {
if (s) return o(s);
if (!r.new_edits) u = u.filter((function(s) {
return s.error;
}));
if (!isRemote(_)) for (var g = 0, b = u.length; g < b; g++) u[g].id = u[g].id || m[g];
o(null, u);
}));
})).bind(this);
this.registerDependentDatabase = adapterFun("registerDependentDatabase", (function(s, r) {
var o = clone(this.__opts);
if (this.__opts.view_adapter) o.adapter = this.__opts.view_adapter;
var u = new this.constructor(s, o);
upsert(this, "_local/_pouch_dependentDbs", (function diffFun(r) {
r.dependentDbs = r.dependentDbs || {};
if (r.dependentDbs[s]) return false;
r.dependentDbs[s] = true;
return r;
})).then((function() {
r(null, {
db: u
});
})).catch(r);
})).bind(this);
this.destroy = adapterFun("destroy", (function(s, r) {
if ("function" == typeof s) {
r = s;
s = {};
}
var o = "use_prefix" in this ? this.use_prefix : true;
const destroyDb = () => {
this._destroy(s, ((s, o) => {
if (s) return r(s);
this._destroyed = true;
this.emit("destroyed");
r(null, o || {
ok: true
});
}));
};
if (isRemote(this)) return destroyDb();
this.get("_local/_pouch_dependentDbs", ((s, u) => {
if (s) if (404 !== s.status) return r(s); else return destroyDb();
var g = u.dependentDbs, _ = this.constructor, m = Object.keys(g).map((s => {
var r = o ? s.replace(new RegExp("^" + _.prefix), "") : s;
return new _(r, this.__opts).destroy();
}));
Promise.all(m).then(destroyDb, r);
}));
})).bind(this);
}
_compact(s, r) {
var o, u = {
return_docs: false,
last_seq: s.last_seq || 0
}, g = [], _ = 0;
const onChange = s => {
this.activeTasks.update(o, {
completed_items: ++_
});
g.push(this.compactDocument(s.id, 0));
}, onError = s => {
this.activeTasks.remove(o, s);
r(s);
}, onComplete = s => {
var u = s.last_seq;
Promise.all(g).then((() => upsert(this, "_local/compaction", (s => {
if (!s.last_seq || s.last_seq < u) {
s.last_seq = u;
return s;
}
return false;
})))).then((() => {
this.activeTasks.remove(o);
r(null, {
ok: true
});
})).catch(onError);
};
this.info().then((s => {
o = this.activeTasks.add({
name: "database_compaction",
total_items: s.update_seq - u.last_seq
});
this.changes(u).on("change", onChange).on("complete", onComplete).on("error", onError);
}));
}
changes(s, r) {
if ("function" == typeof s) {
r = s;
s = {};
}
(s = s || {}).return_docs = "return_docs" in s ? s.return_docs : !s.live;
return new Changes2(this, s, r);
}
type() {
return "function" == typeof this._type ? this._type() : this.adapter;
}
};
AbstractPouchDB.prototype.purge = adapterFun("_purge", (function(s, r, o) {
if ("undefined" == typeof this._purge) return o(createError(UNKNOWN_ERROR, "Purge is not implemented in the " + this.adapter + " adapter."));
var u = this;
u._getRevisionTree(s, ((g, _) => {
if (g) return o(g);
if (!_) return o(createError(MISSING_DOC));
let m;
try {
m = findPathToLeaf(_, r);
} catch (s) {
return o(s.message || s);
}
u._purge(s, m, ((g, _) => {
if (g) return o(g); else appendPurgeSeq(u, s, r).then((function() {
return o(null, _);
}));
}));
}));
}));
var TaskQueue = class {
constructor() {
this.isReady = false;
this.failed = false;
this.queue = [];
}
execute() {
var s;
if (this.failed) for (;s = this.queue.shift(); ) s(this.failed); else for (;s = this.queue.shift(); ) s();
}
fail(s) {
this.failed = s;
this.execute();
}
ready(s) {
this.isReady = true;
this.db = s;
this.execute();
}
addTask(s) {
this.queue.push(s);
if (this.failed) this.execute();
}
};
function parseAdapter(s, r) {
var o = s.match(/([a-z-]*):\/\/(.*)/);
if (o) return {
name: /https?/.test(o[1]) ? o[1] + "://" + o[2] : o[2],
adapter: o[1]
};
var u = PouchDB.adapters, g = PouchDB.preferredAdapters, _ = PouchDB.prefix, m = r.adapter;
if (!m) for (var b = 0; b < g.length && "idb" === (m = g[b]) && "websql" in u && hasLocalStorage() && localStorage["_pouch__websqldb_" + _ + s]; ++b) guardedConsole("log", 'PouchDB is downgrading "' + s + '" to WebSQL to avoid data loss, because it was already opened with WebSQL.');
var E = u[m];
return {
name: (E && "use_prefix" in E ? E.use_prefix : true) ? _ + s : s,
adapter: m
};
}
function inherits(s, r) {
s.prototype = Object.create(r.prototype, {
constructor: {
value: s
}
});
}
function createClass(s, r) {
let klass = function(...s) {
if (!(this instanceof klass)) return new klass(...s);
r.apply(this, s);
};
inherits(klass, s);
return klass;
}
function prepareForDestruction(s) {
function onDestroyed(r) {
s.removeListener("closed", onClosed);
if (!r) s.constructor.emit("destroyed", s.name);
}
function onClosed() {
s.removeListener("destroyed", onDestroyed);
s.constructor.emit("unref", s);
}
s.once("destroyed", onDestroyed);
s.once("closed", onClosed);
s.constructor.emit("ref", s);
}
var PouchInternal = class extends AbstractPouchDB {
constructor(s, r) {
super();
this._setup(s, r);
}
_setup(s, r) {
super._setup();
r = r || {};
if (s && "object" == typeof s) {
s = (r = s).name;
delete r.name;
}
if (void 0 === r.deterministic_revs) r.deterministic_revs = true;
this.__opts = r = clone(r);
this.auto_compaction = r.auto_compaction;
this.purged_infos_limit = r.purged_infos_limit || 1e3;
this.prefix = PouchDB.prefix;
if ("string" != typeof s) throw new Error("Missing/invalid DB name");
var o = parseAdapter((r.prefix || "") + s, r);
r.name = o.name;
r.adapter = r.adapter || o.adapter;
this.name = s;
this._adapter = r.adapter;
PouchDB.emit("debug", [ "adapter", "Picked adapter: ", r.adapter ]);
if (!PouchDB.adapters[r.adapter] || !PouchDB.adapters[r.adapter].valid()) throw new Error("Invalid Adapter: " + r.adapter);
if (r.view_adapter) if (!PouchDB.adapters[r.view_adapter] || !PouchDB.adapters[r.view_adapter].valid()) throw new Error("Invalid View Adapter: " + r.view_adapter);
this.taskqueue = new TaskQueue;
this.adapter = r.adapter;
PouchDB.adapters[r.adapter].call(this, r, (s => {
if (s) return this.taskqueue.fail(s);
prepareForDestruction(this);
this.emit("created", this);
PouchDB.emit("created", this.name);
this.taskqueue.ready(this);
}));
}
}, PouchDB = createClass(PouchInternal, (function(s, r) {
PouchInternal.prototype._setup.call(this, s, r);
})), ActiveTasks = class {
constructor() {
this.tasks = {};
}
list() {
return Object.values(this.tasks);
}
add(s) {
const r = v4_default();
this.tasks[r] = {
id: r,
name: s.name,
total_items: s.total_items,
created_at: (new Date).toJSON()
};
return r;
}
get(s) {
return this.tasks[s];
}
remove(s, r) {
delete this.tasks[s];
return this.tasks;
}
update(s, r) {
const o = this.tasks[s];
if ("undefined" != typeof o) {
const u = {
id: o.id,
name: o.name,
created_at: o.created_at,
total_items: r.total_items || o.total_items,
completed_items: r.completed_items || o.completed_items,
updated_at: (new Date).toJSON()
};
this.tasks[s] = u;
}
return this.tasks;
}
};
PouchDB.adapters = {};
PouchDB.preferredAdapters = [];
PouchDB.prefix = "_pouch_";
var eventEmitter = new import_events2.default;
function setUpEventEmitter(s) {
Object.keys(import_events2.default.prototype).forEach((function(r) {
if ("function" == typeof import_events2.default.prototype[r]) s[r] = eventEmitter[r].bind(eventEmitter);
}));
var r = s._destructionListeners = new ExportedMap;
s.on("ref", (function onConstructorRef(s) {
if (!r.has(s.name)) r.set(s.name, []);
r.get(s.name).push(s);
}));
s.on("unref", (function onConstructorUnref(s) {
if (r.has(s.name)) {
var o = r.get(s.name), u = o.indexOf(s);
if (!(u < 0)) {
o.splice(u, 1);
if (o.length > 1) r.set(s.name, o); else r.delete(s.name);
}
}
}));
s.on("destroyed", (function onConstructorDestroyed(s) {
if (r.has(s)) {
var o = r.get(s);
r.delete(s);
o.forEach((function(s) {
s.emit("destroyed", true);
}));
}
}));
}
setUpEventEmitter(PouchDB);
PouchDB.adapter = function(s, r, o) {
if (r.valid()) {
PouchDB.adapters[s] = r;
if (o) PouchDB.preferredAdapters.push(s);
}
};
PouchDB.plugin = function(s) {
if ("function" == typeof s) s(PouchDB); else if ("object" != typeof s || 0 === Object.keys(s).length) throw new Error('Invalid plugin: got "' + s + '", expected an object or a function'); else Object.keys(s).forEach((function(r) {
PouchDB.prototype[r] = s[r];
}));
if (this.__defaults) PouchDB.__defaults = assign$2({}, this.__defaults);
return PouchDB;
};
PouchDB.defaults = function(s) {
let r = createClass(PouchDB, (function(s, o) {
o = o || {};
if (s && "object" == typeof s) {
s = (o = s).name;
delete o.name;
}
o = assign$2({}, r.__defaults, o);
PouchDB.call(this, s, o);
}));
r.preferredAdapters = PouchDB.preferredAdapters.slice();
Object.keys(PouchDB).forEach((function(s) {
if (!(s in r)) r[s] = PouchDB[s];
}));
r.__defaults = assign$2({}, this.__defaults, s);
return r;
};
PouchDB.fetch = function(s, r) {
return f2(s, r);
};
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(s) {
return s.reduce((function(s, r) {
s[r] = true;
return s;
}), {});
}
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(s) {
if (!/^\d+-/.test(s)) return createError(INVALID_REV);
var r = s.indexOf("-"), o = s.substring(0, r), u = s.substring(r + 1);
return {
prefix: parseInt(o, 10),
id: u
};
}
function makeRevTreeFromRevisions(s, r) {
for (var o = s.start - s.ids.length + 1, u = s.ids, g = [ u[0], r, [] ], _ = 1, m = u.length; _ < m; _++) g = [ u[_], {
status: "missing"
}, [ g ] ];
return [ {
pos: o,
ids: g
} ];
}
function parseDoc(s, r, o) {
if (!o) o = {
deterministic_revs: true
};
var u, g, _, m = {
status: "available"
};
if (s._deleted) m.deleted = true;
if (r) {
if (!s._id) s._id = uuid();
g = rev(s, o.deterministic_revs);
if (s._rev) {
if ((_ = parseRevisionInfo(s._rev)).error) return _;
s._rev_tree = [ {
pos: _.prefix,
ids: [ _.id, {
status: "missing"
}, [ [ g, m, [] ] ] ]
} ];
u = _.prefix + 1;
} else {
s._rev_tree = [ {
pos: 1,
ids: [ g, m, [] ]
} ];
u = 1;
}
} else {
if (s._revisions) {
s._rev_tree = makeRevTreeFromRevisions(s._revisions, m);
u = s._revisions.start;
g = s._revisions.ids[0];
}
if (!s._rev_tree) {
if ((_ = parseRevisionInfo(s._rev)).error) return _;
u = _.prefix;
g = _.id;
s._rev_tree = [ {
pos: u,
ids: [ g, m, [] ]
} ];
}
}
invalidIdError(s._id);
s._rev = u + "-" + g;
var b = {
metadata: {},
data: {}
};
for (var E in s) if (Object.prototype.hasOwnProperty.call(s, E)) {
var w = "_" === E[0];
if (w && !reservedWords[E]) {
var S = createError(DOC_VALIDATION, E);
S.message = DOC_VALIDATION.message + ": " + E;
throw S;
} else if (w && !dataWords[E]) b.metadata[E.slice(1)] = s[E]; else b.data[E] = s[E];
}
return b;
}
function parseBase64(s) {
try {
return thisAtob(s);
} catch (s) {
return {
error: createError(BAD_ARG, "Attachment is not a valid base64 string")
};
}
}
function preprocessString(s, r, o) {
var u = parseBase64(s.data);
if (u.error) return o(u.error);
s.length = u.length;
if ("blob" === r) s.data = binStringToBluffer(u, s.content_type); else if ("base64" === r) s.data = thisBtoa(u); else s.data = u;
binaryMd5(u, (function(r) {
s.digest = "md5-" + r;
o();
}));
}
function preprocessBlob(s, r, o) {
binaryMd5(s.data, (function(u) {
s.digest = "md5-" + u;
s.length = s.data.size || s.data.length || 0;
if ("binary" === r) blobToBinaryString(s.data, (function(r) {
s.data = r;
o();
})); else if ("base64" === r) blobToBase64(s.data, (function(r) {
s.data = r;
o();
})); else o();
}));
}
function preprocessAttachment(s, r, o) {
if (s.stub) return o();
if ("string" == typeof s.data) preprocessString(s, r, o); else preprocessBlob(s, r, o);
}
function preprocessAttachments(s, r, o) {
if (!s.length) return o();
var u, g = 0;
s.forEach((function(s) {
var o = s.data && s.data._attachments ? Object.keys(s.data._attachments) : [], g = 0;
if (!o.length) return done();
function processedAttachment(s) {
u = s;
if (++g === o.length) done();
}
for (var _ in s.data._attachments) if (Object.prototype.hasOwnProperty.call(s.data._attachments, _)) preprocessAttachment(s.data._attachments[_], r, processedAttachment);
}));
function done() {
g++;
if (s.length === g) if (u) o(u); else o();
}
}
function updateDoc(s, r, o, u, g, _, m, b) {
if (revExists(r.rev_tree, o.metadata.rev) && !b) {
u[g] = o;
return _();
}
var E = r.winningRev || winningRev(r), w = "deleted" in r ? r.deleted : isDeleted(r, E), S = "deleted" in o.metadata ? o.metadata.deleted : isDeleted(o.metadata), L = /^1-/.test(o.metadata.rev);
if (w && !S && b && L) {
var O = o.data;
O._rev = E;
O._id = o.metadata.id;
o = parseDoc(O, b);
}
var D = merge(r.rev_tree, o.metadata.rev_tree[0], s);
if (b && (w && S && "new_leaf" !== D.conflicts || !w && "new_leaf" !== D.conflicts || w && !S && "new_branch" === D.conflicts)) {
var k = createError(REV_CONFLICT);
u[g] = k;
return _();
}
var C = o.metadata.rev;
o.metadata.rev_tree = D.tree;
o.stemmedRevs = D.stemmedRevs || [];
if (r.rev_map) o.metadata.rev_map = r.rev_map;
var T, I = winningRev(o.metadata), A = isDeleted(o.metadata, I), R = w === A ? 0 : w < A ? -1 : 1;
if (C === I) T = A; else T = isDeleted(o.metadata, C);
m(o, I, A, T, true, R, g, _);
}
function rootIsMissing(s) {
return "missing" === s.metadata.rev_tree[0].ids[1].status;
}
function processDocs(s, r, o, u, g, _, m, b, E) {
s = s || 1e3;
var w = b.new_edits, S = new ExportedMap, L = 0, O = r.length;
function checkAllDocsDone() {
if (++L === O && E) E();
}
r.forEach((function(s, r) {
if (!s._id || !isLocalId(s._id)) {
var u = s.metadata.id;
if (S.has(u)) {
O--;
S.get(u).push([ s, r ]);
} else S.set(u, [ [ s, r ] ]);
} else {
var m = s._deleted ? "_removeLocal" : "_putLocal";
o[m](s, {
ctx: g
}, (function(s, o) {
_[r] = s || o;
checkAllDocsDone();
}));
}
}));
S.forEach((function(r, o) {
var g = 0;
function docWritten() {
if (++g < r.length) nextDoc(); else checkAllDocsDone();
}
function nextDoc() {
var E = r[g], S = E[0], L = E[1];
if (u.has(o)) updateDoc(s, u.get(o), S, _, L, docWritten, m, w); else {
var O = merge([], S.metadata.rev_tree[0], s);
S.metadata.rev_tree = O.tree;
S.stemmedRevs = O.stemmedRevs || [];
(function insertDoc(s, r, o) {
var u = winningRev(s.metadata), g = isDeleted(s.metadata, u);
if ("was_delete" in b && g) {
_[r] = createError(MISSING_DOC, "deleted");
return o();
}
if (w && rootIsMissing(s)) {
var E = createError(REV_CONFLICT);
_[r] = E;
return o();
}
m(s, u, g, g, false, g ? 0 : 1, r, o);
})(S, L, docWritten);
}
}
nextDoc();
}));
}
var import_vuvuzela = __toESM(require_vuvuzela());
function safeJsonParse(s) {
try {
return JSON.parse(s);
} catch (r) {
return import_vuvuzela.default.parse(s);
}
}
function safeJsonStringify(s) {
try {
return JSON.stringify(s);
} catch (r) {
return import_vuvuzela.default.stringify(s);
}
}
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(s) {
return function(r) {
var o = "unknown_error";
if (r.target && r.target.error) o = r.target.error.name || r.target.error.message;
s(createError(IDB_ERROR, o, r.type));
};
}
function encodeMetadata(s, r, o) {
return {
data: safeJsonStringify(s),
winningRev: r,
deletedOrLocal: o ? "1" : "0",
seq: s.seq,
id: s.id
};
}
function decodeMetadata(s) {
if (!s) return null;
var r = safeJsonParse(s.data);
r.winningRev = s.winningRev;
r.deleted = "1" === s.deletedOrLocal;
r.seq = s.seq;
return r;
}
function decodeDoc(s) {
if (!s) return s;
var r = s._doc_id_rev.lastIndexOf(":");
s._id = s._doc_id_rev.substring(0, r - 1);
s._rev = s._doc_id_rev.substring(r + 1);
delete s._doc_id_rev;
return s;
}
function readBlobData(s, r, o, u) {
if (o) if (!s) u(createBlob2([ "" ], {
type: r
})); else if ("string" != typeof s) u(s); else u(b64ToBluffer(s, r)); else if (!s) u(""); else if ("string" != typeof s) readAsBinaryString(s, (function(s) {
u(thisBtoa(s));
})); else u(s);
}
function fetchAttachmentsIfNecessary(s, r, o, u) {
var g = Object.keys(s._attachments || {});
if (!g.length) return u && u();
var _ = 0;
function checkDone() {
if (++_ === g.length && u) u();
}
g.forEach((function(u) {
if (r.attachments && r.include_docs) (function fetchAttachment(s, r) {
var u = s._attachments[r], g = u.digest;
o.objectStore(ATTACH_STORE).get(g).onsuccess = function(s) {
u.body = s.target.result.body;
checkDone();
};
})(s, u); else {
s._attachments[u].stub = true;
checkDone();
}
}));
}
function postProcessAttachments(s, r) {
return Promise.all(s.map((function(s) {
if (s.doc && s.doc._attachments) {
var o = Object.keys(s.doc._attachments);
return Promise.all(o.map((function(o) {
var u = s.doc._attachments[o];
if ("body" in u) {
var g = u.body, _ = u.content_type;
return new Promise((function(m) {
readBlobData(g, _, r, (function(r) {
s.doc._attachments[o] = assign$2(pick(u, [ "digest", "content_type" ]), {
data: r
});
m();
}));
}));
}
})));
}
})));
}
function compactRevs(s, r, o) {
var u = [], g = o.objectStore(BY_SEQ_STORE), _ = o.objectStore(ATTACH_STORE), m = o.objectStore(ATTACH_AND_SEQ_STORE), b = s.length;
function checkDone() {
if (! --b) (function deleteOrphanedAttachments() {
if (u.length) u.forEach((function(s) {
m.index("digestSeq").count(IDBKeyRange.bound(s + "::", s + "::", false, false)).onsuccess = function(r) {
if (!r.target.result) _.delete(s);
};
}));
})();
}
s.forEach((function(s) {
var o = g.index("_doc_id_rev"), _ = r + "::" + s;
o.getKey(_).onsuccess = function(s) {
var r = s.target.result;
if ("number" != typeof r) return checkDone();
g.delete(r);
m.index("seq").openCursor(IDBKeyRange.only(r)).onsuccess = function(s) {
var r = s.target.result;
if (r) {
var o = r.value.digestSeq.split("::")[0];
u.push(o);
m.delete(r.primaryKey);
r.continue();
} else checkDone();
};
};
}));
}
function openTransactionSafely(s, r, o) {
try {
return {
txn: s.transaction(r, o)
};
} catch (s) {
return {
error: s
};
}
}
var changesHandler$1 = new Changes;
function idbBulkDocs(s, r, o, u, g, _) {
for (var m, b, E, w, S, L, O, D, k = r.docs, C = 0, T = k.length; C < T; C++) {
var I = k[C];
if (!I._id || !isLocalId(I._id)) if ((I = k[C] = parseDoc(I, o.new_edits, s)).error && !O) O = I;
}
if (O) return _(O);
var A = false, R = 0, x = new Array(k.length), P = new ExportedMap, N = false, B = u._meta.blobSupport ? "blob" : "base64";
preprocessAttachments(k, B, (function(r) {
if (r) return _(r);
(function startTransaction() {
var r = openTransactionSafely(g, [ DOC_STORE, BY_SEQ_STORE, ATTACH_STORE, LOCAL_STORE, ATTACH_AND_SEQ_STORE, META_STORE ], "readwrite");
if (r.error) return _(r.error);
(m = r.txn).onabort = idbError(_);
m.ontimeout = idbError(_);
m.oncomplete = complete;
b = m.objectStore(DOC_STORE);
E = m.objectStore(BY_SEQ_STORE);
w = m.objectStore(ATTACH_STORE);
S = m.objectStore(ATTACH_AND_SEQ_STORE);
(L = m.objectStore(META_STORE)).get(META_STORE).onsuccess = function(s) {
D = s.target.result;
updateDocCountIfReady();
};
(function verifyAttachments(s) {
var r = [];
k.forEach((function(s) {
if (s.data && s.data._attachments) Object.keys(s.data._attachments).forEach((function(o) {
var u = s.data._attachments[o];
if (u.stub) r.push(u.digest);
}));
}));
if (!r.length) return s();
var o, u = 0;
r.forEach((function(g) {
(function verifyAttachment(s, r) {
w.get(s).onsuccess = function(o) {
if (!o.target.result) {
var u = createError(MISSING_STUB, "unknown stub attachment with digest " + s);
u.status = 412;
r(u);
} else r();
};
})(g, (function(g) {
if (g && !o) o = g;
(function checkDone() {
if (++u === r.length) s(o);
})();
}));
}));
})((function(r) {
if (r) {
N = true;
return _(r);
}
(function fetchExistingDocs() {
if (k.length) for (var r = 0, g = 0, _ = k.length; g < _; g++) {
var E = k[g];
if (!E._id || !isLocalId(E._id)) b.get(E.metadata.id).onsuccess = readMetadata; else checkDone();
}
function checkDone() {
if (++r === k.length) (function idbProcessDocs() {
processDocs(s.revs_limit, k, u, P, m, x, writeDoc, o, onAllDocsProcessed);
})();
}
function readMetadata(s) {
var r = decodeMetadata(s.target.result);
if (r) P.set(r.id, r);
checkDone();
}
})();
}));
})();
}));
function onAllDocsProcessed() {
A = true;
updateDocCountIfReady();
}
function updateDocCountIfReady() {
if (D && A) {
D.docCount += R;
L.put(D);
}
}
function complete() {
if (!N) {
changesHandler$1.notify(u._meta.name);
_(null, x);
}
}
function writeDoc(s, r, o, u, g, _, m, b) {
s.metadata.winningRev = r;
s.metadata.deleted = o;
var E = s.data;
E._id = s.metadata.id;
E._rev = s.metadata.rev;
if (u) E._deleted = true;
if (E._attachments && Object.keys(E._attachments).length) return function writeAttachments(s, r, o, u, g, _) {
var m = s.data, b = 0, E = Object.keys(m._attachments);
function collectResults() {
if (b === E.length) finishDoc(s, r, o, u, g, _);
}
function attachmentSaved() {
b++;
collectResults();
}
E.forEach((function(o) {
var u = s.data._attachments[o];
if (!u.stub) {
var g = u.data;
delete u.data;
u.revpos = parseInt(r, 10);
(function saveAttachment(s, r, o) {
w.count(s).onsuccess = function(u) {
if (u.target.result) return o();
var g = {
digest: s,
body: r
};
w.put(g).onsuccess = o;
};
})(u.digest, g, attachmentSaved);
} else {
b++;
collectResults();
}
}));
}(s, r, o, g, m, b);
R += _;
updateDocCountIfReady();
finishDoc(s, r, o, g, m, b);
}
function finishDoc(s, r, o, g, _, w) {
var L = s.data, O = s.metadata;
L._doc_id_rev = O.id + "::" + O.rev;
delete L._id;
delete L._rev;
function afterPutDoc(_) {
var E = s.stemmedRevs || [];
if (g && u.auto_compaction) E = E.concat(compactTree(s.metadata));
if (E && E.length) compactRevs(E, s.metadata.id, m);
O.seq = _.target.result;
var w = encodeMetadata(O, r, o);
b.put(w).onsuccess = afterPutMetadata;
}
function afterPutMetadata() {
x[_] = {
ok: true,
id: O.id,
rev: O.rev
};
P.set(s.metadata.id, s.metadata);
(function insertAttachmentMappings(s, r, o) {
var u = 0, g = Object.keys(s.data._attachments || {});
if (!g.length) return o();
function checkDone() {
if (++u === g.length) o();
}
function add(o) {
var u = s.data._attachments[o].digest, g = S.put({
seq: r,
digestSeq: u + "::" + r
});
g.onsuccess = checkDone;
g.onerror = function(s) {
s.preventDefault();
s.stopPropagation();
checkDone();
};
}
for (var _ = 0; _ < g.length; _++) add(g[_]);
})(s, O.seq, w);
}
var D = E.put(L);
D.onsuccess = afterPutDoc;
D.onerror = function afterPutDocError(s) {
s.preventDefault();
s.stopPropagation();
E.index("_doc_id_rev").getKey(L._doc_id_rev).onsuccess = function(s) {
E.put(L, s.target.result).onsuccess = afterPutDoc;
};
};
}
}
function runBatchedCursor(s, r, o, u, g) {
if (-1 === u) u = 1e3;
var _, m, b;
function onGetAll(s) {
m = s.target.result;
if (_) g(_, m, b);
}
function onGetAllKeys(s) {
_ = s.target.result;
if (m) g(_, m, b);
}
function onCursor(s) {
var r = s.target.result;
if (!r) return g();
g([ r.key ], [ r.value ], r);
}
if ("function" == typeof s.getAll && "function" == typeof s.getAllKeys && u > 1 && !o) {
b = {
continue: function continuePseudoCursor() {
if (!_.length) return g();
var o, b = _[_.length - 1];
if (r && r.upper) try {
o = IDBKeyRange.bound(b, r.upper, true, r.upperOpen);
} catch (s) {
if ("DataError" === s.name && 0 === s.code) return g();
} else o = IDBKeyRange.lowerBound(b, true);
r = o;
_ = null;
m = null;
s.getAll(r, u).onsuccess = onGetAll;
s.getAllKeys(r, u).onsuccess = onGetAllKeys;
}
};
s.getAll(r, u).onsuccess = onGetAll;
s.getAllKeys(r, u).onsuccess = onGetAllKeys;
} else if (o) s.openCursor(r, "prev").onsuccess = onCursor; else s.openCursor(r).onsuccess = onCursor;
}
function getAll(s, r, o) {
if ("function" != typeof s.getAll) {
var u = [];
s.openCursor(r).onsuccess = function onCursor(s) {
var r = s.target.result;
if (r) {
u.push(r.value);
r.continue();
} else o({
target: {
result: u
}
});
};
} else s.getAll(r).onsuccess = o;
}
function allDocsKeys(s, r, o) {
var u = new Array(s.length), g = 0;
s.forEach((function(_, m) {
r.get(_).onsuccess = function(r) {
if (r.target.result) u[m] = r.target.result; else u[m] = {
key: _,
error: "not_found"
};
if (++g === s.length) o(s, u, {});
};
}));
}
function createKeyRange(s, r, o, u, g) {
try {
if (s && r) if (g) return IDBKeyRange.bound(r, s, !o, false); else return IDBKeyRange.bound(s, r, false, !o); else if (s) if (g) return IDBKeyRange.upperBound(s); else return IDBKeyRange.lowerBound(s); else if (r) if (g) return IDBKeyRange.lowerBound(r, !o); else return IDBKeyRange.upperBound(r, !o); else if (u) return IDBKeyRange.only(u);
} catch (s) {
return {
error: s
};
}
return null;
}
function idbAllDocs(s, r, o) {
var u, g, _ = "startkey" in s ? s.startkey : false, m = "endkey" in s ? s.endkey : false, b = "key" in s ? s.key : false, E = "keys" in s ? s.keys : false, w = s.skip || 0, S = "number" == typeof s.limit ? s.limit : -1, L = false !== s.inclusive_end;
if (!E) if ((g = (u = createKeyRange(_, m, L, b, s.descending)) && u.error) && !("DataError" === g.name && 0 === g.code)) return o(createError(IDB_ERROR, g.name, g.message));
var O = [ DOC_STORE, BY_SEQ_STORE, META_STORE ];
if (s.attachments) O.push(ATTACH_STORE);
var D = openTransactionSafely(r, O, "readonly");
if (D.error) return o(D.error);
var k = D.txn;
k.oncomplete = function onTxnComplete() {
if (s.attachments) postProcessAttachments(P, s.binary).then(onResultsReady); else onResultsReady();
};
k.onabort = idbError(o);
var C, T, I = k.objectStore(DOC_STORE), A = k.objectStore(BY_SEQ_STORE), R = k.objectStore(META_STORE), x = A.index("_doc_id_rev"), P = [];
R.get(META_STORE).onsuccess = function(s) {
C = s.target.result.docCount;
};
if (s.update_seq) (function getMaxUpdateSeq(s, r) {
s.openCursor(null, "prev").onsuccess = function onCursor(s) {
var o = s.target.result, u = void 0;
if (o && o.key) u = o.key;
return r({
target: {
result: [ u ]
}
});
};
})(A, (function(s) {
if (s.target.result && s.target.result.length > 0) T = s.target.result[0];
}));
function allDocsInner(r, o) {
var u = {
id: o.id,
key: o.id,
value: {
rev: r
}
};
if (o.deleted) {
if (E) {
P.push(u);
u.value.deleted = true;
u.doc = null;
}
} else if (w-- <= 0) {
P.push(u);
if (s.include_docs) (function fetchDocAsynchronously(r, o, u) {
var g = r.id + "::" + u;
x.get(g).onsuccess = function onGetDoc(u) {
o.doc = decodeDoc(u.target.result) || {};
if (s.conflicts) {
var g = collectConflicts(r);
if (g.length) o.doc._conflicts = g;
}
fetchAttachmentsIfNecessary(o.doc, s, k);
};
})(o, u, r);
}
}
function processBatch(s) {
for (var r = 0, o = s.length; r < o && P.length !== S; r++) {
var u = s[r];
if (!u.error || !E) {
var g = decodeMetadata(u);
allDocsInner(g.winningRev, g);
} else P.push(u);
}
}
function onBatch(s, r, o) {
if (o) {
processBatch(r);
if (P.length < S) o.continue();
}
}
function onResultsReady() {
var r = {
total_rows: C,
offset: s.skip,
rows: P
};
if (s.update_seq && void 0 !== T) r.update_seq = T;
o(null, r);
}
if (!g && 0 !== S) {
if (E) return allDocsKeys(s.keys, I, onBatch);
if (-1 === S) return getAll(I, u, (function onGetAll(r) {
var o = r.target.result;
if (s.descending) o = o.reverse();
processBatch(o);
}));
runBatchedCursor(I, u, s.descending, S + w, onBatch);
}
}
function checkBlobSupport(s) {
return new Promise((function(r) {
var o = createBlob2([ "" ]), u = s.objectStore(DETECT_BLOB_SUPPORT_STORE).put(o, "key");
u.onsuccess = function() {
var s = navigator.userAgent.match(/Chrome\/(\d+)/), o = navigator.userAgent.match(/Edge\//);
r(o || !s || parseInt(s[1], 10) >= 43);
};
u.onerror = s.onabort = function(s) {
s.preventDefault();
s.stopPropagation();
r(false);
};
})).catch((function() {
return false;
}));
}
function countDocs(s, r) {
s.objectStore(DOC_STORE).index("deletedOrLocal").count(IDBKeyRange.only("0")).onsuccess = function(s) {
r(s.target.result);
};
}
var running = false, queue = [];
function tryCode(s, r, o, u) {
try {
s(r, o);
} catch (s) {
u.emit("error", s);
}
}
function applyNext() {
if (!running && queue.length) {
running = true;
queue.shift()();
}
}
function enqueueTask(s, r, o) {
queue.push((function runAction() {
s((function runCallback(s, u) {
tryCode(r, s, u, o);
running = false;
(0, import_immediate.default)((function runNext() {
applyNext(o);
}));
}));
}));
applyNext();
}
function changes(s, r, o, u) {
if ((s = clone(s)).continuous) {
var g = o + ":" + uuid();
changesHandler$1.addListener(o, g, r, s);
changesHandler$1.notify(o);
return {
cancel: function() {
changesHandler$1.removeListener(o, g);
}
};
}
var _ = s.doc_ids && new ExportedSet(s.doc_ids);
s.since = s.since || 0;
var m = s.since, b = "limit" in s ? s.limit : -1;
if (0 === b) b = 1;
var E, w, S, L, O = [], D = 0, k = filterChange(s), C = new ExportedMap;
function onGetMetadata(s, r, o, u) {
if (o.seq !== r) return u();
if (o.winningRev === s._rev) return u(o, s);
var g = s._id + "::" + o.winningRev;
L.get(g).onsuccess = function(s) {
u(o, decodeDoc(s.target.result));
};
}
function finish() {
s.complete(null, {
results: O,
last_seq: m
});
}
var T = [ DOC_STORE, BY_SEQ_STORE ];
if (s.attachments) T.push(ATTACH_STORE);
var I = openTransactionSafely(u, T, "readonly");
if (I.error) return s.complete(I.error);
(E = I.txn).onabort = idbError(s.complete);
E.oncomplete = function onTxnComplete() {
if (!s.continuous && s.attachments) postProcessAttachments(O).then(finish); else finish();
};
w = E.objectStore(BY_SEQ_STORE);
S = E.objectStore(DOC_STORE);
L = w.index("_doc_id_rev");
runBatchedCursor(w, s.since && !s.descending ? IDBKeyRange.lowerBound(s.since, true) : null, s.descending, b, (function onBatch(r, o, u) {
if (u && r.length) {
var g = new Array(r.length), w = new Array(r.length), L = 0;
o.forEach((function(o, m) {
(function fetchWinningDocAndMetadata(s, r, o) {
if (_ && !_.has(s._id)) return o();
var u = C.get(s._id);
if (u) return onGetMetadata(s, r, u, o);
S.get(s._id).onsuccess = function(g) {
u = decodeMetadata(g.target.result);
C.set(s._id, u);
onGetMetadata(s, r, u, o);
};
})(decodeDoc(o), r[m], (function(o, _) {
w[m] = o;
g[m] = _;
if (++L === r.length) (function onBatchDone() {
for (var r = [], o = 0, _ = g.length; o < _ && D !== b; o++) {
var m = g[o];
if (m) {
var E = w[o];
r.push(processMetadataAndWinningDoc(E, m));
}
}
Promise.all(r).then((function(r) {
for (var o = 0, u = r.length; o < u; o++) if (r[o]) s.onChange(r[o]);
})).catch(s.complete);
if (D !== b) u.continue();
})();
}));
}));
}
function processMetadataAndWinningDoc(r, o) {
var u = s.processChange(o, r, s);
m = u.seq = r.seq;
var g = k(u);
if ("object" == typeof g) return Promise.reject(g);
if (!g) return Promise.resolve();
D++;
if (s.return_docs) O.push(u);
if (s.attachments && s.include_docs) return new Promise((function(r) {
fetchAttachmentsIfNecessary(o, s, E, (function() {
postProcessAttachments([ u ], s.binary).then((function() {
r(u);
}));
}));
})); else return Promise.resolve(u);
}
}));
}
var blobSupportPromise, cachedDBs = new ExportedMap, openReqList = new ExportedMap;
function IdbPouch(s, r) {
var o = this;
enqueueTask((function(r) {
init(o, s, r);
}), r, o.constructor);
}
function init(s, r, o) {
var u = r.name, g = null, _ = null;
s._meta = null;
function enrichCallbackError(s) {
return function(r, o) {
if (r && r instanceof Error && !r.reason) if (_) r.reason = _;
s(r, o);
};
}
function addDeletedOrLocalIndex(s, r) {
var o = s.objectStore(DOC_STORE);
o.createIndex("deletedOrLocal", "deletedOrLocal", {
unique: false
});
o.openCursor().onsuccess = function(s) {
var u = s.target.result;
if (u) {
var g = u.value, _ = isDeleted(g);
g.deletedOrLocal = _ ? "1" : "0";
o.put(g);
u.continue();
} else r();
};
}
function migrateLocalStore(s, r) {
var o = s.objectStore(LOCAL_STORE), u = s.objectStore(DOC_STORE), g = s.objectStore(BY_SEQ_STORE);
u.openCursor().onsuccess = function(s) {
var _ = s.target.result;
if (_) {
var m = _.value, b = m.id, E = isLocalId(b), w = winningRev(m);
if (E) {
var S = b + "::" + w, L = b + "::", O = b + "::~", D = g.index("_doc_id_rev"), k = IDBKeyRange.bound(L, O, false, false), C = D.openCursor(k);
C.onsuccess = function(s) {
if (!(C = s.target.result)) {
u.delete(_.primaryKey);
_.continue();
} else {
var r = C.value;
if (r._doc_id_rev === S) o.put(r);
g.delete(C.primaryKey);
C.continue();
}
};
} else _.continue();
} else if (r) r();
};
}
function migrateAttsAndSeqs(s, r) {
var o = s.objectStore(BY_SEQ_STORE), u = s.objectStore(ATTACH_STORE), g = s.objectStore(ATTACH_AND_SEQ_STORE);
u.count().onsuccess = function(s) {
if (!s.target.result) return r();
o.openCursor().onsuccess = function(s) {
var o = s.target.result;
if (!o) return r();
for (var u = o.value, _ = o.primaryKey, m = Object.keys(u._attachments || {}), b = {}, E = 0; E < m.length; E++) b[u._attachments[m[E]].digest] = true;
var w = Object.keys(b);
for (E = 0; E < w.length; E++) {
var S = w[E];
g.put({
seq: _,
digestSeq: S + "::" + _
});
}
o.continue();
};
};
}
function migrateMetadata(s) {
var r = s.objectStore(BY_SEQ_STORE), o = s.objectStore(DOC_STORE);
o.openCursor().onsuccess = function(s) {
var u = s.target.result;
if (u) {
var g = function decodeMetadataCompat(s) {
if (!s.data) {
s.deleted = "1" === s.deletedOrLocal;
return s;
}
return decodeMetadata(s);
}(u.value);
g.winningRev = g.winningRev || winningRev(g);
if (g.seq) return onGetMetadataSeq();
(function fetchMetadataSeq() {
var s = g.id + "::", o = g.id + "::", u = r.index("_doc_id_rev").openCursor(IDBKeyRange.bound(s, o)), _ = 0;
u.onsuccess = function(s) {
var r = s.target.result;
if (!r) {
g.seq = _;
return onGetMetadataSeq();
}
var o = r.primaryKey;
if (o > _) _ = o;
r.continue();
};
})();
}
function onGetMetadataSeq() {
var s = encodeMetadata(g, g.winningRev, g.deleted);
o.put(s).onsuccess = function() {
u.continue();
};
}
};
}
s._remote = false;
s.type = function() {
return "idb";
};
s._id = toPromise((function(r) {
r(null, s._meta.instanceId);
}));
s._bulkDocs = function idb_bulkDocs(o, u, _) {
idbBulkDocs(r, o, u, s, g, enrichCallbackError(_));
};
s._get = function idb_get(s, r, o) {
var u, _, m, b = r.ctx;
if (!b) {
var E = openTransactionSafely(g, [ DOC_STORE, BY_SEQ_STORE, ATTACH_STORE ], "readonly");
if (E.error) return o(E.error);
b = E.txn;
}
function finish() {
o(m, {
doc: u,
metadata: _,
ctx: b
});
}
b.objectStore(DOC_STORE).get(s).onsuccess = function(s) {
if (!(_ = decodeMetadata(s.target.result))) {
m = createError(MISSING_DOC, "missing");
return finish();
}
var o;
if (!r.rev) {
o = _.winningRev;
if (isDeleted(_)) {
m = createError(MISSING_DOC, "deleted");
return finish();
}
} else o = r.latest ? latest(r.rev, _) : r.rev;
var g = b.objectStore(BY_SEQ_STORE), E = _.id + "::" + o;
g.index("_doc_id_rev").get(E).onsuccess = function(s) {
if (u = s.target.result) u = decodeDoc(u);
if (!u) {
m = createError(MISSING_DOC, "missing");
return finish();
}
finish();
};
};
};
s._getAttachment = function(s, r, o, u, _) {
var m;
if (u.ctx) m = u.ctx; else {
var b = openTransactionSafely(g, [ DOC_STORE, BY_SEQ_STORE, ATTACH_STORE ], "readonly");
if (b.error) return _(b.error);
m = b.txn;
}
var E = o.digest, w = o.content_type;
m.objectStore(ATTACH_STORE).get(E).onsuccess = function(s) {
readBlobData(s.target.result.body, w, u.binary, (function(s) {
_(null, s);
}));
};
};
s._info = function idb_info(r) {
var o, u, _ = openTransactionSafely(g, [ META_STORE, BY_SEQ_STORE ], "readonly");
if (_.error) return r(_.error);
var m = _.txn;
m.objectStore(META_STORE).get(META_STORE).onsuccess = function(s) {
u = s.target.result.docCount;
};
m.objectStore(BY_SEQ_STORE).openCursor(null, "prev").onsuccess = function(s) {
var r = s.target.result;
o = r ? r.key : 0;
};
m.oncomplete = function() {
r(null, {
doc_count: u,
update_seq: o,
idb_attachment_format: s._meta.blobSupport ? "binary" : "base64"
});
};
};
s._allDocs = function idb_allDocs(s, r) {
idbAllDocs(s, g, enrichCallbackError(r));
};
s._changes = function idbChanges2(r) {
return changes(r, s, u, g);
};
s._close = function(s) {
g.close();
cachedDBs.delete(u);
s();
};
s._getRevisionTree = function(s, r) {
var o = openTransactionSafely(g, [ DOC_STORE ], "readonly");
if (o.error) return r(o.error);
o.txn.objectStore(DOC_STORE).get(s).onsuccess = function(s) {
var o = decodeMetadata(s.target.result);
if (!o) r(createError(MISSING_DOC)); else r(null, o.rev_tree);
};
};
s._doCompaction = function(s, r, o) {
var u = openTransactionSafely(g, [ DOC_STORE, BY_SEQ_STORE, ATTACH_STORE, ATTACH_AND_SEQ_STORE ], "readwrite");
if (u.error) return o(u.error);
var _ = u.txn;
_.objectStore(DOC_STORE).get(s).onsuccess = function(o) {
var u = decodeMetadata(o.target.result);
traverseRevTree(u.rev_tree, (function(s, o, u, g, _) {
var m = o + "-" + u;
if (-1 !== r.indexOf(m)) _.status = "missing";
}));
compactRevs(r, s, _);
var g = u.winningRev, m = u.deleted;
_.objectStore(DOC_STORE).put(encodeMetadata(u, g, m));
};
_.onabort = idbError(o);
_.oncomplete = function() {
o();
};
};
s._getLocal = function(s, r) {
var o = openTransactionSafely(g, [ LOCAL_STORE ], "readonly");
if (o.error) return r(o.error);
var u = o.txn.objectStore(LOCAL_STORE).get(s);
u.onerror = idbError(r);
u.onsuccess = function(s) {
var o = s.target.result;
if (!o) r(createError(MISSING_DOC)); else {
delete o["_doc_id_rev"];
r(null, o);
}
};
};
s._putLocal = function(s, r, o) {
if ("function" == typeof r) {
o = r;
r = {};
}
delete s._revisions;
var u = s._rev, _ = s._id;
if (!u) s._rev = "0-1"; else s._rev = "0-" + (parseInt(u.split("-")[1], 10) + 1);
var m, b = r.ctx;
if (!b) {
var E = openTransactionSafely(g, [ LOCAL_STORE ], "readwrite");
if (E.error) return o(E.error);
(b = E.txn).onerror = idbError(o);
b.oncomplete = function() {
if (m) o(null, m);
};
}
var w, S = b.objectStore(LOCAL_STORE);
if (u) (w = S.get(_)).onsuccess = function(g) {
var _ = g.target.result;
if (!_ || _._rev !== u) o(createError(REV_CONFLICT)); else S.put(s).onsuccess = function() {
m = {
ok: true,
id: s._id,
rev: s._rev
};
if (r.ctx) o(null, m);
};
}; else {
(w = S.add(s)).onerror = function(s) {
o(createError(REV_CONFLICT));
s.preventDefault();
s.stopPropagation();
};
w.onsuccess = function() {
m = {
ok: true,
id: s._id,
rev: s._rev
};
if (r.ctx) o(null, m);
};
}
};
s._removeLocal = function(s, r, o) {
if ("function" == typeof r) {
o = r;
r = {};
}
var u, _ = r.ctx;
if (!_) {
var m = openTransactionSafely(g, [ LOCAL_STORE ], "readwrite");
if (m.error) return o(m.error);
(_ = m.txn).oncomplete = function() {
if (u) o(null, u);
};
}
var b = s._id, E = _.objectStore(LOCAL_STORE), w = E.get(b);
w.onerror = idbError(o);
w.onsuccess = function(g) {
var _ = g.target.result;
if (!_ || _._rev !== s._rev) o(createError(MISSING_DOC)); else {
E.delete(b);
u = {
ok: true,
id: b,
rev: "0-0"
};
if (r.ctx) o(null, u);
}
};
};
s._destroy = function(s, r) {
changesHandler$1.removeAllListeners(u);
var o = openReqList.get(u);
if (o && o.result) {
o.result.close();
cachedDBs.delete(u);
}
var g = indexedDB.deleteDatabase(u);
g.onsuccess = function() {
openReqList.delete(u);
if (hasLocalStorage() && u in localStorage) delete localStorage[u];
r(null, {
ok: true
});
};
g.onerror = idbError(r);
};
var m = cachedDBs.get(u);
if (m) {
g = m.idb;
s._meta = m.global;
return (0, import_immediate.default)((function() {
o(null, s);
}));
}
var b = indexedDB.open(u, ADAPTER_VERSION);
openReqList.set(u, b);
b.onupgradeneeded = function(s) {
var r = s.target.result;
if (s.oldVersion < 1) return function createSchema(s) {
var r = s.createObjectStore(DOC_STORE, {
keyPath: "id"
});
s.createObjectStore(BY_SEQ_STORE, {
autoIncrement: true
}).createIndex("_doc_id_rev", "_doc_id_rev", {
unique: true
});
s.createObjectStore(ATTACH_STORE, {
keyPath: "digest"
});
s.createObjectStore(META_STORE, {
keyPath: "id",
autoIncrement: false
});
s.createObjectStore(DETECT_BLOB_SUPPORT_STORE);
r.createIndex("deletedOrLocal", "deletedOrLocal", {
unique: false
});
s.createObjectStore(LOCAL_STORE, {
keyPath: "_id"
});
var o = s.createObjectStore(ATTACH_AND_SEQ_STORE, {
autoIncrement: true
});
o.createIndex("seq", "seq");
o.createIndex("digestSeq", "digestSeq", {
unique: true
});
}(r);
var o = s.currentTarget.transaction;
if (s.oldVersion < 3) (function createLocalStoreSchema(s) {
s.createObjectStore(LOCAL_STORE, {
keyPath: "_id"
}).createIndex("_doc_id_rev", "_doc_id_rev", {
unique: true
});
})(r);
if (s.oldVersion < 4) (function addAttachAndSeqStore(s) {
var r = s.createObjectStore(ATTACH_AND_SEQ_STORE, {
autoIncrement: true
});
r.createIndex("seq", "seq");
r.createIndex("digestSeq", "digestSeq", {
unique: true
});
})(r);
var u = [ addDeletedOrLocalIndex, migrateLocalStore, migrateAttsAndSeqs, migrateMetadata ], g = s.oldVersion;
(function next() {
var s = u[g - 1];
g++;
if (s) s(o, next);
})();
};
b.onsuccess = function(r) {
(g = r.target.result).onversionchange = function() {
g.close();
cachedDBs.delete(u);
};
g.onabort = function(s) {
guardedConsole("error", "Database has a global failure", s.target.error);
_ = s.target.error;
g.close();
cachedDBs.delete(u);
};
var m, b, E, w, S = g.transaction([ META_STORE, DETECT_BLOB_SUPPORT_STORE, DOC_STORE ], "readwrite"), L = false;
function completeSetup() {
if ("undefined" != typeof E && L) {
s._meta = {
name: u,
instanceId: w,
blobSupport: E
};
cachedDBs.set(u, {
idb: g,
global: s._meta
});
o(null, s);
}
}
function storeMetaDocIfReady() {
if ("undefined" != typeof b && "undefined" != typeof m) {
var s = u + "_id";
if (s in m) w = m[s]; else m[s] = w = uuid();
m.docCount = b;
S.objectStore(META_STORE).put(m);
}
}
S.objectStore(META_STORE).get(META_STORE).onsuccess = function(s) {
m = s.target.result || {
id: META_STORE
};
storeMetaDocIfReady();
};
countDocs(S, (function(s) {
b = s;
storeMetaDocIfReady();
}));
if (!blobSupportPromise) blobSupportPromise = checkBlobSupport(S);
blobSupportPromise.then((function(s) {
E = s;
completeSetup();
}));
S.oncomplete = function() {
L = true;
completeSetup();
};
S.onabort = idbError(o);
};
b.onerror = function(s) {
var r = s.target.error && s.target.error.message;
if (!r) r = "Failed to open indexedDB, are you in private browsing mode?"; else if (-1 !== r.indexOf("stored database is a higher version")) r = 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", r);
o(createError(IDB_ERROR, r));
};
}
IdbPouch.valid = function() {
try {
return "undefined" != typeof indexedDB && "undefined" != typeof IDBKeyRange;
} catch (s) {
return false;
}
};
function index(s) {
s.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(s, r) {
if (r) return TEST_PATH_INVALID.test(s); else return TEST_KEY_INVALID.test(s);
}
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(s, r) {
var correctCharacters = function(s) {
for (var o = "", u = 0; u < s.length; u++) {
var g = s.charCodeAt(u);
if (g === IS_DOT && r && 0 === u) o += "."; else if (g === SLASH && r) continue; else o += "_c" + g + "_";
}
return o;
};
if (r) return s.replace(PATH_INVALID, correctCharacters); else return s.replace(KEY_INVALID, correctCharacters);
}
function needsRewrite(s) {
for (var r of Object.keys(s)) if (needsSanitise(r)) return true; else if (null === s[r] || "boolean" == typeof s[r]) return true; else if ("object" == typeof s[r]) return needsRewrite(s[r]);
}
function rewrite(s) {
if (!needsRewrite(s)) return false;
var r = Array.isArray(s), o = r ? [] : {};
Object.keys(s).forEach((function(u) {
var g = r ? u : sanitise(u);
if (null === s[u]) o[g] = IDB_NULL; else if ("boolean" == typeof s[u]) o[g] = s[u] ? IDB_TRUE : IDB_FALSE; else if ("object" == typeof s[u]) o[g] = rewrite(s[u]); else o[g] = s[u];
}));
return o;
}
var DOC_STORE2 = "docs", META_STORE2 = "meta";
function idbError2(s) {
return function(r) {
var o = "unknown_error";
if (r.target && r.target.error) o = r.target.error.name || r.target.error.message;
s(createError(IDB_ERROR, o, r.type));
};
}
function processAttachment(s, r, o, u) {
delete o._attachments[s].stub;
if (u) {
o._attachments[s].data = r.attachments[o._attachments[s].digest].data;
return Promise.resolve();
}
return new Promise((function(u) {
readAsBinaryString(r.attachments[o._attachments[s].digest].data, (function(r) {
o._attachments[s].data = thisBtoa(r);
delete o._attachments[s].length;
u();
}));
}));
}
function rawIndexFields(s, r) {
return (s.views[r].options && s.views[r].options.def && s.views[r].options.def.fields || []).map((function(s) {
if ("string" == typeof s) return s; else return Object.keys(s)[0];
}));
}
function isPartialFilterView(s, r) {
return r in s.views && s.views[r].options && s.views[r].options.def && s.views[r].options.def.partial_filter_selector;
}
function naturalIndexName(s) {
return "_find_idx/" + s.join("/");
}
function correctIndexFields(s) {
return [ "deleted" ].concat(s.map((function(s) {
if ([ "_id", "_rev", "_deleted", "_attachments" ].includes(s)) return s.substr(1); else return "data." + sanitise(s, true);
})));
}
var POUCHDB_IDB_VERSION = 1, versionMultiplier = Math.pow(10, 13);
function createIdbVersion() {
return versionMultiplier * POUCHDB_IDB_VERSION + (new Date).getTime();
}
function getPouchDbVersion(s) {
return Math.floor(s / versionMultiplier);
}
function maintainNativeIndexes(s, r) {
var o = s.transaction.objectStore(DOC_STORE2);
o.getAll(IDBKeyRange.bound("_design/", "_design/")).onsuccess = function(s) {
var u = s.target.result, g = Array.from(o.indexNames), _ = u.filter((function(s) {
return 0 === s.deleted && s.revs[s.rev].data.views;
})).map((function(s) {
return s.revs[s.rev].data;
})).reduce((function(s, r) {
return Object.keys(r.views).reduce((function(s, o) {
var u = rawIndexFields(r, o);
if (u && u.length > 0) s[naturalIndexName(u)] = correctIndexFields(u);
return s;
}), s);
}), {}), m = Object.keys(_), b = [ "seq" ];
g.forEach((function(s) {
if (-1 === b.indexOf(s) && -1 === m.indexOf(s)) o.deleteIndex(s);
}));
var E = m.filter((function(s) {
return -1 === g.indexOf(s);
}));
try {
E.forEach((function(s) {
o.createIndex(s, _[s]);
}));
} catch (s) {
r(s);
}
};
}
function upgradePouchDbSchema(s, r) {
if (r < 1) {
s.createObjectStore(DOC_STORE2, {
keyPath: "id"
}).createIndex("seq", "seq", {
unique: true
});
s.createObjectStore(META_STORE2, {
keyPath: "id"
});
}
}
function openDatabase(s, r, o, u, g) {
var _ = o.versionchanged ? indexedDB.open(o.name) : indexedDB.open(o.name, createIdbVersion());
_.onupgradeneeded = function(s) {
if (s.oldVersion > 0 && s.oldVersion < versionMultiplier) throw new Error('Incorrect adapter: you should specify the "idb" adapter to open this DB'); else if (0 === s.oldVersion && s.newVersion < versionMultiplier) {
indexedDB.deleteDatabase(o.name);
throw new Error("Database was deleted while open");
}
upgradePouchDbSchema(s.target.result, getPouchDbVersion(s.oldVersion));
maintainNativeIndexes(_, g);
};
_.onblocked = function(s) {
console.error("onblocked, this should never happen", s);
};
_.onsuccess = function(r) {
var g = r.target.result;
g.onabort = function(r) {
console.error("Database has a global failure", r.target.error);
delete s[o.name];
g.close();
};
g.onversionchange = function() {
console.log("Database was made stale, closing handle");
s[o.name].versionchanged = true;
g.close();
};
g.onclose = function() {
console.log("Database was made stale, closing handle");
if (o.name in s) s[o.name].versionchanged = true;
};
var _ = {
id: META_STORE2
}, m = g.transaction([ META_STORE2 ], "readwrite");
m.oncomplete = function() {
u({
idb: g,
metadata: _
});
};
var b = m.objectStore(META_STORE2);
b.get(META_STORE2).onsuccess = function(s) {
var r = false;
if (!("doc_count" in (_ = s.target.result || _))) {
r = true;
_.doc_count = 0;
}
if (!("seq" in _)) {
r = true;
_.seq = 0;
}
if (!("db_uuid" in _)) {
r = true;
_.db_uuid = uuid();
}
if (r) b.put(_);
};
};
_.onerror = function(s) {
g(s.target.error);
};
}
function setup(s, r, o) {
if (!s[o.name] || s[o.name].versionchanged) {
o.versionchanged = s[o.name] && s[o.name].versionchanged;
s[o.name] = new Promise((function(u, g) {
openDatabase(s, r, o, u, g);
}));
}
return s[o.name];
}
function info(s, r) {
r(null, {
doc_count: s.doc_count,
update_seq: s.seq
});
}
function get(s, r, o, u) {
if (s.error) return u(s.error);
s.txn.objectStore(DOC_STORE2).get(r).onsuccess = function(r) {
var g, _ = r.target.result;
if (!o.rev) g = _ && _.rev; else g = o.latest ? latest(o.rev, _) : o.rev;
if (_ && (!_.deleted || o.rev) && g in _.revs) {
var m = _.revs[g].data;
m._id = _.id;
m._rev = g;
u(null, {
doc: m,
metadata: _,
ctx: s
});
} else u(createError(MISSING_DOC, "missing"));
};
}
function parseAttachment(s, r, o) {
if (r.binary) return o(null, s); else readAsBinaryString(s, (function(s) {
o(null, thisBtoa(s));
}));
}
function getAttachment(s, r, o, u, g, _) {
if (s.error) return _(s.error);
var m;
s.txn.objectStore(DOC_STORE2).get(r).onsuccess = function(s) {
var r = s.target.result, u = r.revs[g.rev || r.rev].data._attachments[o].digest;
m = r.attachments[u].data;
};
s.txn.oncomplete = function() {
parseAttachment(m, g, _);
};
s.txn.onabort = _;
}
function bulkDocs(s, r, o, u, g, _, m) {
var b, E, w, S = [], L = [], O = g.revs_limit || 1e3, D = -1 === g.name.indexOf("-mrview-");
const k = g.auto_compaction;
function docsRevsLimit(s) {
return /^_local/.test(s.id) ? 1 : O;
}
function revHasAttachment(s, r, o) {
return s.revs[r] && s.revs[r].data._attachments && Object.values(s.revs[r].data._attachments).find((function(s) {
return s.digest === o;
}));
}
function convertDocFormat(s) {
var r = {
id: s.metadata.id,
rev: s.metadata.rev,
rev_tree: s.metadata.rev_tree,
revs: s.metadata.revs || {}
};
r.revs[r.rev] = {
data: s.data,
deleted: s.metadata.deleted
};
return r;
}
function updateSeq(s) {
if (s === w) b.objectStore(META_STORE2).put(u);
}
for (var C = 0, T = r.docs.length; C < T; C++) {
var I;
try {
I = parseDoc(r.docs[C], o.new_edits, g);
} catch (s) {
I = s;
}
if (I.error) return m(I);
L.push(convertDocFormat(I));
}
(function preProcessAttachments() {
var s = L.map((function(s) {
var r = s.revs[s.rev].data;
if (!r._attachments) return Promise.resolve(r);
var o = Object.keys(r._attachments).map((function(s) {
r._attachments[s].name = s;
return function preProcessAttachment(s) {
if (s.stub) return Promise.resolve(s);
var r;
if ("string" == typeof s.data) {
if ((r = function parseBase642(s) {
try {
return atob(s);
} catch (s) {
return {
error: createError(BAD_ARG, "Attachment is not a valid base64 string")
};
}
}(s.data)).error) return Promise.reject(r.error);
s.data = binStringToBluffer(r, s.content_type);
} else r = s.data;
return new Promise((function(o) {
binaryMd5(r, (function(u) {
s.digest = "md5-" + u;
s.length = r.size || r.length || 0;
o(s);
}));
}));
}(r._attachments[s]);
}));
return Promise.all(o).then((function(s) {
var o = {};
s.forEach((function(s) {
o[s.name] = s;
delete s.name;
}));
r._attachments = o;
return r;
}));
}));
return Promise.all(s);
})().then((function() {
s._openTransactionSafely([ DOC_STORE2, META_STORE2 ], "readwrite", (function(s, r) {
if (s) return m(s);
(b = r).onabort = function() {
m(E || createError(UNKNOWN_ERROR, "transaction was aborted"));
};
b.ontimeout = idbError2(m);
b.oncomplete = function() {
_.notify(g.name);
m(null, S);
};
(function fetchExistingDocs(s, r) {
var _ = 0, m = {};
function readDone(b) {
if (b.target.result) m[b.target.result.id] = b.target.result;
if (++_ === r.length) (function processDocs2(s, r, _) {
r.forEach((function(r, m) {
var b;
if ("was_delete" in o && !Object.prototype.hasOwnProperty.call(_, r.id)) b = createError(MISSING_DOC, "deleted"); else if (o.new_edits && !Object.prototype.hasOwnProperty.call(_, r.id) && function rootIsMissing2(s) {
return "missing" === s.rev_tree[0].ids[1].status;
}(r)) b = createError(REV_CONFLICT); else if (Object.prototype.hasOwnProperty.call(_, r.id)) {
b = function update2(s, r, u) {
if (r.rev in u.revs && !o.new_edits) return false;
var _ = /^1-/.test(r.rev);
if (u.deleted && !r.deleted && o.new_edits && _) {
var m = r.revs[r.rev].data;
m._rev = u.rev;
m._id = u.id;
r = convertDocFormat(parseDoc(m, o.new_edits, g));
}
var b = merge(u.rev_tree, r.rev_tree[0], docsRevsLimit(r));
r.stemmedRevs = b.stemmedRevs;
r.rev_tree = b.tree;
var E = u.revs;
E[r.rev] = r.revs[r.rev];
r.revs = E;
r.attachments = u.attachments;
if (o.new_edits && (u.deleted && r.deleted || !u.deleted && "new_leaf" !== b.conflicts || u.deleted && !r.deleted && "new_branch" === b.conflicts || u.rev === r.rev)) return createError(REV_CONFLICT);
r.wasDeleted = u.deleted;
return r;
}(0, r, _[r.id]);
if (false == b) return;
} else {
var L = merge([], r.rev_tree[0], docsRevsLimit(r));
r.rev_tree = L.tree;
r.stemmedRevs = L.stemmedRevs;
(b = r).isNewDoc = true;
b.wasDeleted = r.revs[r.rev].deleted ? 1 : 0;
}
if (b.error) S[m] = b; else {
_[b.id] = b;
w = m;
(function write(s, r, o) {
var g = winningRev(r), _ = r.rev, m = /^_local/.test(r.id), b = r.revs[g].data;
const w = r.isNewDoc;
if (D) {
var L = rewrite(b);
if (L) {
r.data = L;
delete r.data._attachments;
} else r.data = b;
} else r.data = b;
r.rev = g;
r.deleted = r.revs[g].deleted ? 1 : 0;
if (!m) {
r.seq = ++u.seq;
var O = 0;
if (r.isNewDoc) O = r.deleted ? 0 : 1; else if (r.wasDeleted !== r.deleted) O = r.deleted ? -1 : 1;
u.doc_count += O;
}
delete r.isNewDoc;
delete r.wasDeleted;
let C = r.stemmedRevs || [];
if (k && !w) {
const s = compactTree(r);
if (s.length) C = C.concat(s);
}
if (C.length) C.forEach((function(s) {
delete r.revs[s];
}));
delete r.stemmedRevs;
if (!("attachments" in r)) r.attachments = {};
if (b._attachments) for (var T in b._attachments) {
var I = b._attachments[T];
if (I.stub) {
if (!(I.digest in r.attachments)) {
E = createError(MISSING_STUB);
s.abort();
return;
}
if (revHasAttachment(r, _, I.digest)) r.attachments[I.digest].revs[_] = true;
} else {
r.attachments[I.digest] = I;
r.attachments[I.digest].revs = {};
r.attachments[I.digest].revs[_] = true;
b._attachments[T] = {
stub: true,
digest: I.digest,
content_type: I.content_type,
length: I.length,
revpos: parseInt(_, 10)
};
}
}
if (!m || !r.deleted) s.objectStore(DOC_STORE2).put(r).onsuccess = function() {
S[o] = {
ok: true,
id: r.id,
rev: _
};
updateSeq(o);
}; else {
s.objectStore(DOC_STORE2).delete(r.id).onsuccess = function() {
S[o] = {
ok: true,
id: r.id,
rev: "0-0"
};
};
updateSeq(o);
}
})(s, b, m);
}
}));
})(s, r, m);
}
r.forEach((function(r) {
s.objectStore(DOC_STORE2).get(r.id).onsuccess = readDone;
}));
})(b, L);
}));
})).catch((function(s) {
m(s);
}));
}
function allDocsKeys2(s, r, o) {
var u = new Array(s.length), g = 0;
s.forEach((function(_, m) {
r.get(_).onsuccess = function(r) {
if (r.target.result) u[m] = r.target.result; else u[m] = {
key: _,
error: "not_found"
};
if (++g === s.length) u.forEach((function(s) {
o(s);
}));
};
}));
}
function createKeyRange2(s, r, o, u, g) {
try {
if (s && r) if (g) return IDBKeyRange.bound(r, s, !o, false); else return IDBKeyRange.bound(s, r, false, !o); else if (s) if (g) return IDBKeyRange.upperBound(s); else return IDBKeyRange.lowerBound(s); else if (r) if (g) return IDBKeyRange.lowerBound(r, !o); else return IDBKeyRange.upperBound(r, !o); else if (u) return IDBKeyRange.only(u);
} catch (s) {
return {
error: s
};
}
return null;
}
function handleKeyRangeError(s, r, o, u) {
if ("DataError" === o.name && 0 === o.code) {
var g = {
total_rows: r.doc_count,
offset: s.skip,
rows: []
};
if (s.update_seq) g.update_seq = r.seq;
return u(null, g);
}
u(createError(IDB_ERROR, o.name, o.message));
}
function allDocs(s, r, o, u) {
if (s.error) return u(s.error);
if (0 === o.limit) {
var g = {
total_rows: r.doc_count,
offset: o.skip,
rows: []
};
if (o.update_seq) g.update_seq = r.seq;
return u(null, g);
}
var _, m = [], b = [], E = "startkey" in o ? o.startkey : false, w = "endkey" in o ? o.endkey : false, S = "key" in o ? o.key : false, L = "keys" in o ? o.keys : false, O = o.skip || 0, D = "number" == typeof o.limit ? o.limit : -1, k = false !== o.inclusive_end, C = "descending" in o && o.descending ? "prev" : null;
if (!L) if ((_ = createKeyRange2(E, w, k, S, C)) && _.error) return handleKeyRangeError(o, r, _.error, u);
var T = s.txn.objectStore(DOC_STORE2);
s.txn.oncomplete = function onTxnComplete() {
Promise.all(b).then((function() {
var s = {
total_rows: r.doc_count,
offset: 0,
rows: m
};
if (o.update_seq) s.update_seq = r.seq;
u(null, s);
}));
};
if (L) return allDocsKeys2(o.keys, T, allDocsInner);
function allDocsInner(s) {
if (s.error && L) {
m.push(s);
return true;
}
var r = {
id: s.id,
key: s.id,
value: {
rev: s.rev
}
};
if (s.deleted) {
if (L) {
m.push(r);
r.value.deleted = true;
r.doc = null;
}
} else if (O-- <= 0) {
m.push(r);
if (o.include_docs) (function include_doc(s, r) {
var u = r.revs[r.rev].data;
s.doc = u;
s.doc._id = r.id;
s.doc._rev = r.rev;
if (o.conflicts) {
var g = collectConflicts(r);
if (g.length) s.doc._conflicts = g;
}
if (o.attachments && u._attachments) for (var _ in u._attachments) b.push(processAttachment(_, r, s.doc, o.binary));
})(r, s);
if (0 == --D) return false;
}
return true;
}
(C ? T.openCursor(_, C) : T.openCursor(_)).onsuccess = function(s) {
var r = s.target.result && s.target.result.value;
if (r) {
if (/^_local/.test(r.id)) return s.target.result.continue();
if (allDocsInner(r)) s.target.result.continue();
}
};
}
function changes2(s, r, o, u, g) {
if (s.error) return g.complete(s.error);
if (g.continuous) {
var _ = u.name + ":" + uuid();
r.addListener(u.name, _, o, g);
r.notify(u.name);
return {
cancel: function() {
r.removeListener(u.name, _);
}
};
}
var m = "limit" in g ? g.limit : -1;
if (0 === m) m = 1;
var b, E = s.txn.objectStore(DOC_STORE2).index("seq"), w = filterChange(g), S = 0, L = g.since || 0, O = [], D = [];
if (g.descending) b = E.openCursor(null, "prev"); else b = E.openCursor(IDBKeyRange.lowerBound(g.since, true));
s.txn.oncomplete = function onTxnComplete() {
Promise.all(D).then((function() {
g.complete(null, {
results: O,
last_seq: L
});
}));
};
b.onsuccess = function onReqSuccess(s) {
if (s.target.result) {
var r = s.target.result, o = r.value;
o.data = o.revs[o.rev].data;
o.data._id = o.id;
o.data._rev = o.rev;
if (o.deleted) o.data._deleted = true;
if (g.doc_ids && -1 === g.doc_ids.indexOf(o.id)) return r.continue();
var u = g.processChange(o.data, o, g);
u.seq = o.seq;
L = o.seq;
var _ = w(u);
if ("object" == typeof _) return g.complete(_);
if (_) {
S++;
if (g.return_docs) O.push(u);
if (g.include_docs && g.attachments && o.data._attachments) {
var b = [];
for (var E in o.data._attachments) {
var k = processAttachment(E, o, u.doc, g.binary);
b.push(k);
D.push(k);
}
Promise.all(b).then((function() {
g.onChange(u);
}));
} else g.onChange(u);
}
if (S !== m) r.continue();
}
};
}
function getRevisionTree(s, r, o) {
if (s.error) return o(s.error);
s.txn.objectStore(DOC_STORE2).get(r).onsuccess = function(s) {
if (!s.target.result) o(createError(MISSING_DOC)); else o(null, s.target.result.rev_tree);
};
}
function doCompaction(s, r, o, u) {
if (s.error) return u(s.error);
var g = s.txn.objectStore(DOC_STORE2);
g.get(r).onsuccess = function(s) {
var r = s.target.result;
traverseRevTree(r.rev_tree, (function(s, r, u, g, _) {
var m = r + "-" + u;
if (-1 !== o.indexOf(m)) _.status = "missing";
}));
var u = [];
o.forEach((function(s) {
if (s in r.revs) {
if (r.revs[s].data._attachments) for (var o in r.revs[s].data._attachments) u.push(r.revs[s].data._attachments[o].digest);
delete r.revs[s];
}
}));
u.forEach((function(s) {
o.forEach((function(o) {
delete r.attachments[s].revs[o];
}));
if (!Object.keys(r.attachments[s].revs).length) delete r.attachments[s];
}));
g.put(r);
};
s.txn.oncomplete = function() {
u();
};
}
function destroy(s, r, o, u) {
o.removeAllListeners(s.name);
function doDestroy() {
indexedDB.deleteDatabase(s.name).onsuccess = function() {
delete r[s.name];
u(null, {
ok: true
});
};
}
if (s.name in r) r[s.name].then((function(s) {
s.idb.close();
doDestroy();
})); else doDestroy();
}
var COUCH_COLLATE_LO = null, COUCH_COLLATE_HI = "", IDB_COLLATE_LO = Number.NEGATIVE_INFINITY, IDB_COLLATE_HI = [ [ [ [ [ [ [ [ [ [ [ [] ] ] ] ] ] ] ] ] ] ] ];
function externaliseRecord(s) {
var r = s.revs[s.rev].data;
r._id = s.id;
r._rev = s.rev;
if (s.deleted) r._deleted = true;
return r;
}
function generateKeyRange(s) {
function defined(s, r) {
return void 0 !== s[r];
}
function convert(s, r) {
return [ 0 ].concat(s).map((function(s) {
if (null === s && r) return IDB_NULL; else if (true === s) return IDB_TRUE; else if (false === s) return IDB_FALSE;
if (!r) if (s === COUCH_COLLATE_LO) return IDB_COLLATE_LO; else if (Object.prototype.hasOwnProperty.call(s, COUCH_COLLATE_HI)) return IDB_COLLATE_HI;
return s;
}));
}
if (!defined(s, "inclusive_end")) s.inclusive_end = true;
if (!defined(s, "inclusive_start")) s.inclusive_start = true;
if (s.descending) {
var r = s.startkey, o = s.inclusive_start;
s.startkey = s.endkey;
s.endkey = r;
s.inclusive_start = s.inclusive_end;
s.inclusive_end = o;
}
try {
if (defined(s, "key")) return IDBKeyRange.only(convert(s.key, true));
if (defined(s, "startkey") && !defined(s, "endkey")) return IDBKeyRange.bound(convert(s.startkey), [ 1 ], !s.inclusive_start, true);
if (!defined(s, "startkey") && defined(s, "endkey")) return IDBKeyRange.upperBound(convert(s.endkey), !s.inclusive_end);
if (defined(s, "startkey") && defined(s, "endkey")) return IDBKeyRange.bound(convert(s.startkey), convert(s.endkey), !s.inclusive_start, !s.inclusive_end); else return IDBKeyRange.only([ 0 ]);
} catch (r) {
console.error("Could not generate keyRange", r, s);
throw Error("Could not generate key range with " + JSON.stringify(s));
}
}
function getIndexHandle(s, r, o) {
var u = naturalIndexName(r);
return new Promise((function(g) {
s._openTransactionSafely([ DOC_STORE2 ], "readonly", (function(_, m) {
if (_) return idbError2(o)(_);
m.onabort = idbError2(o);
m.ontimeout = idbError2(o);
if (-1 === Array.from(m.objectStore(DOC_STORE2).indexNames).indexOf(u)) s._freshen().then((function() {
return getIndexHandle(s, r, o);
})).then(g); else g(m.objectStore(DOC_STORE2).index(u));
}));
}));
}
function query(s, r, o, u) {
var g = this, _ = r.split("/");
return new Promise((function(s, m) {
g.get("_design/" + _[0]).then((function(b) {
if (isPartialFilterView(b, _[1])) return u(r, o).then(s, m);
var E = rawIndexFields(b, _[1]);
if (!E) throw new Error("ddoc " + b._id + " with view " + _[1] + " does not have map.options.def.fields defined.");
var w = o.skip, S = Number.isInteger(o.limit) && o.limit;
return getIndexHandle(g, E, m).then((function(r) {
var u = generateKeyRange(o), g = r.openCursor(u, o.descending ? "prev" : "next"), _ = [];
g.onerror = idbError2(m);
g.onsuccess = function(r) {
var o = r.target.result;
if (!o || 0 === S) return s({
rows: _
});
if (!w) {
if (S) S -= 1;
_.push({
doc: externaliseRecord(o.value)
});
o.continue();
} else {
o.advance(w);
w = false;
}
};
}));
})).catch(m);
}));
}
function viewCleanup(s, r) {
return r();
}
function purgeAttachments(s, r) {
if (!s.attachments) return {};
for (let o in s.attachments) {
const u = s.attachments[o];
for (let s of r) if (u.revs[s]) delete u.revs[s];
if (0 === Object.keys(u.revs).length) delete s.attachments[o];
}
return s.attachments;
}
function purge(s, r, o, u) {
if (s.error) return u(s.error);
const g = s.txn.objectStore(DOC_STORE2), _ = [];
let m = false;
g.get(r).onsuccess = s => {
const r = s.target.result;
for (const s of o) {
r.rev_tree = removeLeafFromRevTree(r.rev_tree, s);
delete r.revs[s];
_.push(s);
}
if (0 !== r.rev_tree.length) {
r.rev = winningRev(r);
r.data = r.revs[r.rev].data;
r.attachments = purgeAttachments(r, o);
g.put(r);
} else {
g.delete(r.id);
m = true;
}
};
s.txn.oncomplete = function() {
u(null, {
ok: true,
deletedRevs: _,
documentWasRemovedCompletely: m
});
};
}
var ADAPTER_NAME = "indexeddb", idbChanges = new Changes, openDatabases = {};
function IdbPouch2(s, r) {
if (s.view_adapter) console.log("Please note that the indexeddb adapter manages _find indexes itself, therefore it is not using your specified view_adapter");
var o = this, u = {}, $ = function(r) {
return function() {
var g = Array.prototype.slice.call(arguments);
setup(openDatabases, o, s).then((function(s) {
u = s.metadata;
g.unshift(s.idb);
r.apply(o, g);
})).catch((function(s) {
var r = g.pop();
if ("function" == typeof r) r(s); else console.error(s);
}));
};
}, $p = function(r) {
return function() {
var g = Array.prototype.slice.call(arguments);
return setup(openDatabases, o, s).then((function(s) {
u = s.metadata;
g.unshift(s.idb);
return r.apply(o, g);
}));
};
}, $t = function(r, g, _) {
g = g || [ DOC_STORE2 ];
_ = _ || "readonly";
return function() {
var m = Array.prototype.slice.call(arguments), b = {};
setup(openDatabases, o, s).then((function(s) {
u = s.metadata;
b.txn = s.idb.transaction(g, _);
})).catch((function(s) {
console.error("Failed to establish transaction safely");
console.error(s);
b.error = s;
})).then((function() {
m.unshift(b);
r.apply(o, m);
}));
};
};
o._openTransactionSafely = function(s, r, o) {
$t((function(s, r) {
r(s.error, s.txn);
}), s, r)(o);
};
o._remote = false;
o.type = function() {
return ADAPTER_NAME;
};
o._id = $((function(s, r) {
r(null, u.db_uuid);
}));
o._info = $((function(s, r) {
return info(u, r);
}));
o._get = $t(get);
o._bulkDocs = $((function(r, g, _, m) {
bulkDocs(o, g, _, u, s, idbChanges, m);
}));
o._allDocs = $t((function(s, r, o) {
allDocs(s, u, r, o);
}));
o._getAttachment = $t(getAttachment);
o._changes = $t((function(r, u) {
changes2(r, idbChanges, o, s, u);
}));
o._getRevisionTree = $t(getRevisionTree);
o._doCompaction = $t(doCompaction, [ DOC_STORE2 ], "readwrite");
o._customFindAbstractMapper = {
query: $p(query),
viewCleanup: $p(viewCleanup)
};
o._destroy = function(r, o) {
return destroy(s, openDatabases, idbChanges, o);
};
o._close = $((function(r, o) {
delete openDatabases[s.name];
r.close();
o();
}));
o._freshen = function() {
return new Promise((function(s) {
o._close((function() {
$(s)();
}));
}));
};
o._purge = $t(purge, [ DOC_STORE2 ], "readwrite");
setTimeout((function() {
r(null, o);
}));
}
IdbPouch2.valid = function() {
return true;
};
function index2(s) {
s.adapter(ADAPTER_NAME, IdbPouch2, true);
}
var index_es_default3 = index2;
function pool(s, r) {
return new Promise((function(o, u) {
var g, _ = 0, m = 0, b = 0, E = s.length;
function runNext() {
_++;
s[m++]().then(onSuccess, onError);
}
function doNext() {
if (++b === E) if (g) u(g); else o(); else runNextBatch();
}
function onSuccess() {
_--;
doNext();
}
function onError(s) {
_--;
g = g || s;
doNext();
}
function runNextBatch() {
for (;_ < r && m < E; ) runNext();
}
runNextBatch();
}));
}
var CHANGES_BATCH_SIZE = 25, MAX_SIMULTANEOUS_REVS = 50, CHANGES_TIMEOUT_BUFFER = 5e3, DEFAULT_HEARTBEAT = 1e4, supportsBulkGetMap = {};
function readAttachmentsAsBlobOrBuffer(s) {
let r = s.doc || s.ok, o = r && r._attachments;
if (o) Object.keys(o).forEach((function(s) {
let r = o[s];
r.data = b64ToBluffer(r.data, r.content_type);
}));
}
function encodeDocId(s) {
if (/^_design/.test(s)) return "_design/" + encodeURIComponent(s.slice(8));
if (/^_local/.test(s)) return "_local/" + encodeURIComponent(s.slice(7)); else return encodeURIComponent(s);
}
function preprocessAttachments2(s) {
if (!s._attachments || !Object.keys(s._attachments)) return Promise.resolve(); else return Promise.all(Object.keys(s._attachments).map((function(r) {
let o = s._attachments[r];
if (o.data && "string" != typeof o.data) return new Promise((function(s) {
blobToBase64(o.data, s);
})).then((function(s) {
o.data = s;
}));
})));
}
function hasUrlPrefix(s) {
if (!s.prefix) return false;
let r = parseUri(s.prefix).protocol;
return "http" === r || "https" === r;
}
function getHost(s, r) {
if (hasUrlPrefix(r)) {
let o = r.name.substr(r.prefix.length);
s = r.prefix.replace(/\/?$/, "/") + encodeURIComponent(o);
}
let o = parseUri(s);
if (o.user || o.password) o.auth = {
username: o.user,
password: o.password
};
let u = o.path.replace(/(^\/|\/$)/g, "").split("/");
o.db = u.pop();
if (-1 === o.db.indexOf("%")) o.db = encodeURIComponent(o.db);
o.path = u.join("/");
return o;
}
function genDBUrl(s, r) {
return genUrl(s, s.db + "/" + r);
}
function genUrl(s, r) {
let o = !s.path ? "" : "/";
return s.protocol + "://" + s.host + (s.port ? ":" + s.port : "") + "/" + s.path + o + r;
}
function paramsToStr(s) {
return "?" + Object.keys(s).map((function(r) {
return r + "=" + encodeURIComponent(s[r]);
})).join("&");
}
function shouldCacheBust(s) {
let r = "undefined" != typeof navigator && navigator.userAgent ? navigator.userAgent.toLowerCase() : "", o = -1 !== r.indexOf("msie"), u = -1 !== r.indexOf("trident"), g = -1 !== r.indexOf("edge"), _ = !("method" in s) || "GET" === s.method;
return (o || u || g) && _;
}
function HttpPouch(s, r) {
let o = this, u = getHost(s.name, s), g = genDBUrl(u, "");
s = clone(s);
const ourFetch = async function(r, o) {
(o = o || {}).headers = o.headers || new h;
o.credentials = "include";
if (s.auth || u.auth) {
let r = s.auth || u.auth, g = r.username + ":" + r.password, _ = thisBtoa(unescape(encodeURIComponent(g)));
o.headers.set("Authorization", "Basic " + _);
}
let g = s.headers || {};
Object.keys(g).forEach((function(s) {
o.headers.append(s, g[s]);
}));
if (shouldCacheBust(o)) r += (-1 === r.indexOf("?") ? "?" : "&") + "_nonce=" + Date.now();
let _ = s.fetch || f2;
return await _(r, o);
};
function adapterFun$$1(s, r) {
return adapterFun(s, (function(...s) {
setup2().then((function() {
return r.apply(this, s);
})).catch((function(r) {
s.pop()(r);
}));
})).bind(o);
}
async function fetchJSON(s, r) {
let o = {};
(r = r || {}).headers = r.headers || new h;
if (!r.headers.get("Content-Type")) r.headers.set("Content-Type", "application/json");
if (!r.headers.get("Accept")) r.headers.set("Accept", "application/json");
const u = await ourFetch(s, r);
o.ok = u.ok;
o.status = u.status;
const g = await u.json();
o.data = g;
if (!o.ok) {
o.data.status = o.status;
throw generateErrorFromResponse(o.data);
}
if (Array.isArray(o.data)) o.data = o.data.map((function(s) {
if (s.error || s.missing) return generateErrorFromResponse(s); else return s;
}));
return o;
}
let _;
async function setup2() {
if (s.skip_setup) return Promise.resolve();
if (_) return _;
_ = fetchJSON(g).catch((function(s) {
if (s && s.status && 404 === s.status) {
explainError(404, "PouchDB is just detecting if the remote exists.");
return fetchJSON(g, {
method: "PUT"
});
} else return Promise.reject(s);
})).catch((function(s) {
if (s && s.status && 412 === s.status) return true; else return Promise.reject(s);
}));
_.catch((function() {
_ = null;
}));
return _;
}
(0, import_immediate.default)((function() {
r(null, o);
}));
o._remote = true;
o.type = function() {
return "http";
};
o.id = adapterFun$$1("id", (async function(s) {
let r;
try {
const s = await ourFetch(genUrl(u, ""));
r = await s.json();
} catch (s) {
r = {};
}
s(null, r && r.uuid ? r.uuid + u.db : genDBUrl(u, ""));
}));
o.compact = adapterFun$$1("compact", (async function(s, r) {
if ("function" == typeof s) {
r = s;
s = {};
}
s = clone(s);
await fetchJSON(genDBUrl(u, "_compact"), {
method: "POST"
});
(function ping() {
o.info((function(o, u) {
if (u && !u.compact_running) r(null, {
ok: true
}); else setTimeout(ping, s.interval || 200);
}));
})();
}));
o.bulkGet = adapterFun("bulkGet", (function(s, r) {
let o = this;
async function doBulkGet(r) {
let o = {};
if (s.revs) o.revs = true;
if (s.attachments) o.attachments = true;
if (s.latest) o.latest = true;
try {
const g = await fetchJSON(genDBUrl(u, "_bulk_get" + paramsToStr(o)), {
method: "POST",
body: JSON.stringify({
docs: s.docs
})
});
if (s.attachments && s.binary) g.data.results.forEach((function(s) {
s.docs.forEach(readAttachmentsAsBlobOrBuffer);
}));
r(null, g.data);
} catch (s) {
r(s);
}
}
function doBulkGetShim() {
let u = MAX_SIMULTANEOUS_REVS, g = Math.ceil(s.docs.length / u), _ = 0, m = new Array(g);
function onResult(s) {
return function(o, u) {
m[s] = u.results;
if (++_ === g) r(null, {
results: flatten(m)
});
};
}
for (let r = 0; r < g; r++) {
let g = pick(s, [ "revs", "attachments", "binary", "latest" ]);
g.docs = s.docs.slice(r * u, Math.min(s.docs.length, (r + 1) * u));
bulkGet(o, g, onResult(r));
}
}
let g = genUrl(u, ""), _ = supportsBulkGetMap[g];
if ("boolean" != typeof _) doBulkGet((function(s, o) {
if (s) {
supportsBulkGetMap[g] = false;
explainError(s.status, "PouchDB is just detecting if the remote supports the _bulk_get API.");
doBulkGetShim();
} else {
supportsBulkGetMap[g] = true;
r(null, o);
}
})); else if (_) doBulkGet(r); else doBulkGetShim();
}));
o._info = async function(s) {
try {
await setup2();
const r = await ourFetch(genDBUrl(u, "")), o = await r.json();
o.host = genDBUrl(u, "");
s(null, o);
} catch (r) {
s(r);
}
};
o.fetch = async function(s, r) {
await setup2();
const o = "/" === s.substring(0, 1) ? genUrl(u, s.substring(1)) : genDBUrl(u, s);
return ourFetch(o, r);
};
o.get = adapterFun$$1("get", (async function(s, r, o) {
if ("function" == typeof r) {
o = r;
r = {};
}
let g = {};
if ((r = clone(r)).revs) g.revs = true;
if (r.revs_info) g.revs_info = true;
if (r.latest) g.latest = true;
if (r.open_revs) {
if ("all" !== r.open_revs) r.open_revs = JSON.stringify(r.open_revs);
g.open_revs = r.open_revs;
}
if (r.rev) g.rev = r.rev;
if (r.conflicts) g.conflicts = r.conflicts;
if (r.update_seq) g.update_seq = r.update_seq;
s = encodeDocId(s);
function fetchAttachments(s) {
let o = s._attachments, g = o && Object.keys(o);
if (o && g.length) return pool(g.map((function(g) {
return function() {
return async function fetchData(g) {
const _ = o[g], m = encodeDocId(s._id) + "/" + encodeAttachmentId(g) + "?rev=" + s._rev, b = await ourFetch(genDBUrl(u, m));
let E, w;
if ("buffer" in b) E = await b.buffer(); else E = await b.blob();
if (r.binary) {
let s = Object.getOwnPropertyDescriptor(E.__proto__, "type");
if (!s || s.set) E.type = _.content_type;
w = E;
} else w = await new Promise((function(s) {
blobToBase64(E, s);
}));
delete _.stub;
delete _.length;
_.data = w;
}(g);
};
})), 5);
}
const _ = genDBUrl(u, s + paramsToStr(g));
try {
const s = await fetchJSON(_);
if (r.attachments) await function fetchAllAttachments(s) {
if (Array.isArray(s)) return Promise.all(s.map((function(s) {
if (s.ok) return fetchAttachments(s.ok);
}))); else return fetchAttachments(s);
}(s.data);
o(null, s.data);
} catch (r) {
r.docId = s;
o(r);
}
}));
o.remove = adapterFun$$1("remove", (async function(s, r, o, g) {
let _;
if ("string" == typeof r) {
_ = {
_id: s,
_rev: r
};
if ("function" == typeof o) {
g = o;
o = {};
}
} else {
_ = s;
if ("function" == typeof r) {
g = r;
o = {};
} else {
g = o;
o = r;
}
}
const m = _._rev || o.rev, b = genDBUrl(u, encodeDocId(_._id)) + "?rev=" + m;
try {
g(null, (await fetchJSON(b, {
method: "DELETE"
})).data);
} catch (s) {
g(s);
}
}));
function encodeAttachmentId(s) {
return s.split("/").map(encodeURIComponent).join("/");
}
o.getAttachment = adapterFun$$1("getAttachment", (async function(s, r, o, g) {
if ("function" == typeof o) {
g = o;
o = {};
}
const _ = o.rev ? "?rev=" + o.rev : "", m = genDBUrl(u, encodeDocId(s)) + "/" + encodeAttachmentId(r) + _;
let b;
try {
const s = await ourFetch(m, {
method: "GET"
});
if (!s.ok) throw s;
b = s.headers.get("content-type");
let r;
if ("undefined" != typeof process && !process.browser && "function" == typeof s.buffer) r = await s.buffer(); else r = await s.blob();
if ("undefined" != typeof process && !process.browser) {
var E = Object.getOwnPropertyDescriptor(r.__proto__, "type");
if (!E || E.set) r.type = b;
}
g(null, r);
} catch (s) {
g(s);
}
}));
o.removeAttachment = adapterFun$$1("removeAttachment", (async function(s, r, o, g) {
const _ = genDBUrl(u, encodeDocId(s) + "/" + encodeAttachmentId(r)) + "?rev=" + o;
try {
g(null, (await fetchJSON(_, {
method: "DELETE"
})).data);
} catch (s) {
g(s);
}
}));
o.putAttachment = adapterFun$$1("putAttachment", (async function(s, r, o, g, _, m) {
if ("function" == typeof _) {
m = _;
_ = g;
g = o;
o = null;
}
const b = encodeDocId(s) + "/" + encodeAttachmentId(r);
let E = genDBUrl(u, b);
if (o) E += "?rev=" + o;
if ("string" == typeof g) {
let s;
try {
s = thisAtob(g);
} catch (s) {
return m(createError(BAD_ARG, "Attachment is not a valid base64 string"));
}
g = s ? binStringToBluffer(s, _) : "";
}
try {
m(null, (await fetchJSON(E, {
headers: new h({
"Content-Type": _
}),
method: "PUT",
body: g
})).data);
} catch (s) {
m(s);
}
}));
o._bulkDocs = async function(s, r, o) {
s.new_edits = r.new_edits;
try {
await setup2();
await Promise.all(s.docs.map(preprocessAttachments2));
o(null, (await fetchJSON(genDBUrl(u, "_bulk_docs"), {
method: "POST",
body: JSON.stringify(s)
})).data);
} catch (s) {
o(s);
}
};
o._put = async function(s, r, o) {
try {
await setup2();
await preprocessAttachments2(s);
o(null, (await fetchJSON(genDBUrl(u, encodeDocId(s._id)), {
method: "PUT",
body: JSON.stringify(s)
})).data);
} catch (r) {
r.docId = s && s._id;
o(r);
}
};
o.allDocs = adapterFun$$1("allDocs", (async function(s, r) {
if ("function" == typeof s) {
r = s;
s = {};
}
let o, g = {}, _ = "GET";
if ((s = clone(s)).conflicts) g.conflicts = true;
if (s.update_seq) g.update_seq = true;
if (s.descending) g.descending = true;
if (s.include_docs) g.include_docs = true;
if (s.attachments) g.attachments = true;
if (s.key) g.key = JSON.stringify(s.key);
if (s.start_key) s.startkey = s.start_key;
if (s.startkey) g.startkey = JSON.stringify(s.startkey);
if (s.end_key) s.endkey = s.end_key;
if (s.endkey) g.endkey = JSON.stringify(s.endkey);
if ("undefined" != typeof s.inclusive_end) g.inclusive_end = !!s.inclusive_end;
if ("undefined" != typeof s.limit) g.limit = s.limit;
if ("undefined" != typeof s.skip) g.skip = s.skip;
let m = paramsToStr(g);
if ("undefined" != typeof s.keys) {
_ = "POST";
o = {
keys: s.keys
};
}
try {
const g = await fetchJSON(genDBUrl(u, "_all_docs" + m), {
method: _,
body: JSON.stringify(o)
});
if (s.include_docs && s.attachments && s.binary) g.data.rows.forEach(readAttachmentsAsBlobOrBuffer);
r(null, g.data);
} catch (s) {
r(s);
}
}));
o._changes = function(s) {
let r = "batch_size" in s ? s.batch_size : CHANGES_BATCH_SIZE;
if ((s = clone(s)).continuous && !("heartbeat" in s)) s.heartbeat = DEFAULT_HEARTBEAT;
let o = "timeout" in s ? s.timeout : 3e4;
if ("timeout" in s && s.timeout && o - s.timeout < CHANGES_TIMEOUT_BUFFER) o = s.timeout + CHANGES_TIMEOUT_BUFFER;
if ("heartbeat" in s && s.heartbeat && o - s.heartbeat < CHANGES_TIMEOUT_BUFFER) o = s.heartbeat + CHANGES_TIMEOUT_BUFFER;
let g = {};
if ("timeout" in s && s.timeout) g.timeout = s.timeout;
let _ = "undefined" != typeof s.limit ? s.limit : false, m = _;
if (s.style) g.style = s.style;
if (s.include_docs || s.filter && "function" == typeof s.filter) g.include_docs = true;
if (s.attachments) g.attachments = true;
if (s.continuous) g.feed = "longpoll";
if (s.seq_interval) g.seq_interval = s.seq_interval;
if (s.conflicts) g.conflicts = true;
if (s.descending) g.descending = true;
if (s.update_seq) g.update_seq = true;
if ("heartbeat" in s) if (s.heartbeat) g.heartbeat = s.heartbeat;
if (s.filter && "string" == typeof s.filter) g.filter = s.filter;
if (s.view && "string" == typeof s.view) {
g.filter = "_view";
g.view = s.view;
}
if (s.query_params && "object" == typeof s.query_params) for (let r in s.query_params) if (Object.prototype.hasOwnProperty.call(s.query_params, r)) g[r] = s.query_params[r];
let b, E = "GET";
if (s.doc_ids) {
g.filter = "_doc_ids";
E = "POST";
b = {
doc_ids: s.doc_ids
};
} else if (s.selector) {
g.filter = "_selector";
E = "POST";
b = {
selector: s.selector
};
}
let w, S = new a;
const fetchData = async function(o, L) {
if (s.aborted) return;
g.since = o;
if ("object" == typeof g.since) g.since = JSON.stringify(g.since);
if (s.descending) {
if (_) g.limit = m;
} else g.limit = !_ || m > r ? r : m;
let O = genDBUrl(u, "_changes" + paramsToStr(g)), D = {
signal: S.signal,
method: E,
body: JSON.stringify(b)
};
w = o;
if (!s.aborted) try {
await setup2();
L(null, (await fetchJSON(O, D)).data);
} catch (s) {
L(s);
}
};
let L = {
results: []
};
const fetched = function(o, u) {
if (s.aborted) return;
let g = 0;
if (u && u.results) {
g = u.results.length;
L.last_seq = u.last_seq;
let r = null, o = null;
if ("number" == typeof u.pending) r = u.pending;
if ("string" == typeof L.last_seq || "number" == typeof L.last_seq) o = L.last_seq;
({}).query = s.query_params;
u.results = u.results.filter((function(u) {
m--;
let g = filterChange(s)(u);
if (g) {
if (s.include_docs && s.attachments && s.binary) readAttachmentsAsBlobOrBuffer(u);
if (s.return_docs) L.results.push(u);
s.onChange(u, r, o);
}
return g;
}));
} else if (o) {
s.aborted = true;
s.complete(o);
return;
}
if (u && u.last_seq) w = u.last_seq;
let b = _ && m <= 0 || u && g < r || s.descending;
if (s.continuous && !(_ && m <= 0) || !b) (0, import_immediate.default)((function() {
fetchData(w, fetched);
})); else s.complete(null, L);
};
fetchData(s.since || 0, fetched);
return {
cancel: function() {
s.aborted = true;
S.abort();
}
};
};
o.revsDiff = adapterFun$$1("revsDiff", (async function(s, r, o) {
if ("function" == typeof r) {
o = r;
r = {};
}
try {
o(null, (await fetchJSON(genDBUrl(u, "_revs_diff"), {
method: "POST",
body: JSON.stringify(s)
})).data);
} catch (s) {
o(s);
}
}));
o._close = function(s) {
s();
};
o._destroy = async function(s, r) {
try {
r(null, await fetchJSON(genDBUrl(u, ""), {
method: "DELETE"
}));
} catch (s) {
if (404 === s.status) r(null, {
ok: true
}); else r(s);
}
};
}
HttpPouch.valid = function() {
return true;
};
function index3(s) {
s.adapter("http", HttpPouch, false);
s.adapter("https", HttpPouch, false);
}
var index_es_default4 = index3, QueryParseError = class _QueryParseError extends Error {
constructor(s) {
super();
this.status = 400;
this.name = "query_parse_error";
this.message = s;
this.error = true;
try {
Error.captureStackTrace(this, _QueryParseError);
} catch (s) {}
}
}, NotFoundError = class _NotFoundError extends Error {
constructor(s) {
super();
this.status = 404;
this.name = "not_found";
this.message = s;
this.error = true;
try {
Error.captureStackTrace(this, _NotFoundError);
} catch (s) {}
}
}, BuiltInError = class _BuiltInError extends Error {
constructor(s) {
super();
this.status = 500;
this.name = "invalid_value";
this.message = s;
this.error = true;
try {
Error.captureStackTrace(this, _BuiltInError);
} catch (s) {}
}
};
function promisedCallback(s, r) {
if (r) s.then((function(s) {
(0, import_immediate.default)((function() {
r(null, s);
}));
}), (function(s) {
(0, import_immediate.default)((function() {
r(s);
}));
}));
return s;
}
function callbackify(s) {
return function(...r) {
var o = r.pop(), u = s.apply(this, r);
if ("function" == typeof o) promisedCallback(u, o);
return u;
};
}
function fin(s, r) {
return s.then((function(s) {
return r().then((function() {
return s;
}));
}), (function(s) {
return r().then((function() {
throw s;
}));
}));
}
function sequentialize(s, r) {
return function() {
var o = arguments, u = this;
return s.add((function() {
return r.apply(u, o);
}));
};
}
function uniq(s) {
var r = new ExportedSet(s), o = new Array(r.size), u = -1;
r.forEach((function(s) {
o[++u] = s;
}));
return o;
}
function mapToKeysArray(s) {
var r = new Array(s.size), o = -1;
s.forEach((function(s, u) {
r[++o] = u;
}));
return r;
}
var TaskQueue2 = class {
constructor() {
this.promise = new Promise((function(s) {
s();
}));
}
add(s) {
this.promise = this.promise.catch((function() {})).then((function() {
return s();
}));
return this.promise;
}
finish() {
return this.promise;
}
};
function stringify2(s) {
if (!s) return "undefined";
switch (typeof s) {
case "function":
return s.toString();
case "string":
return s.toString();
default:
return JSON.stringify(s);
}
}
function createViewSignature(s, r) {
return stringify2(s) + stringify2(r) + "undefined";
}
async function createView(s, r, o, u, g, _) {
const m = createViewSignature(o, u);
let b;
if (!g) {
b = s._cachedViews = s._cachedViews || {};
if (b[m]) return b[m];
}
const E = s.info().then((async function(E) {
const w = E.db_name + "-mrview-" + (g ? "temp" : stringMd5(m));
await upsert(s, "_local/" + _, (function diffFunction(s) {
s.views = s.views || {};
let o = r;
if (-1 === o.indexOf("/")) o = r + "/" + r;
const u = s.views[o] = s.views[o] || {};
if (!u[w]) {
u[w] = true;
return s;
}
}));
const S = (await s.registerDependentDatabase(w)).db;
S.auto_compaction = true;
const L = {
name: w,
db: S,
sourceDB: s,
adapter: s.adapter,
mapFun: o,
reduceFun: u
};
let O;
try {
O = await L.db.get("_local/lastSeq");
} catch (s) {
if (404 !== s.status) throw s;
}
L.seq = O ? O.seq : 0;
if (b) L.db.once("destroyed", (function() {
delete b[m];
}));
return L;
}));
if (b) b[m] = E;
return E;
}
var persistentQueues = {}, tempViewQueue = new TaskQueue2, CHANGES_BATCH_SIZE2 = 50;
function parseViewName(s) {
return -1 === s.indexOf("/") ? [ s, s ] : s.split("/");
}
function isGenOne(s) {
return 1 === s.length && /^1-/.test(s[0].rev);
}
function emitError(s, r, o) {
try {
s.emit("error", r);
} catch (s) {
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", r, o);
}
}
function createAbstractMapReduce(s, r, o, u) {
function tryMap(s, r, o) {
try {
r(o);
} catch (u) {
emitError(s, u, {
fun: r,
doc: o
});
}
}
function tryReduce(s, r, o, u, g) {
try {
return {
output: r(o, u, g)
};
} catch (_) {
emitError(s, _, {
fun: r,
keys: o,
values: u,
rereduce: g
});
return {
error: _
};
}
}
function sortByKeyThenValue(s, r) {
const o = collate(s.key, r.key);
return 0 !== o ? o : collate(s.value, r.value);
}
function sliceResults(s, r, o) {
o = o || 0;
if ("number" == typeof r) return s.slice(o, r + o); else if (o > 0) return s.slice(o);
return s;
}
function rowToDocId(s) {
const r = s.value;
return r && "object" == typeof r && r._id || s.id;
}
function postprocessAttachments(s) {
return function(r) {
if (s.include_docs && s.attachments && s.binary) (function readAttachmentsAsBlobOrBuffer2(s) {
s.rows.forEach((function(s) {
const r = s.doc && s.doc._attachments;
if (r) Object.keys(r).forEach((function(s) {
const o = r[s];
r[s].data = b64ToBluffer(o.data, o.content_type);
}));
}));
})(r);
return r;
};
}
function addHttpParam(s, r, o, u) {
let g = r[s];
if ("undefined" != typeof g) {
if (u) g = encodeURIComponent(JSON.stringify(g));
o.push(s + "=" + g);
}
}
function coerceInteger(s) {
if ("undefined" != typeof s) {
const r = Number(s);
if (!isNaN(r) && r === parseInt(s, 10)) return r; else return s;
}
}
function checkQueryParseError(s, r) {
const o = s.descending ? "endkey" : "startkey", u = s.descending ? "startkey" : "endkey";
if ("undefined" != typeof s[o] && "undefined" != typeof s[u] && collate(s[o], s[u]) > 0) throw new QueryParseError("No rows can match your key range, reverse your start_key and end_key or set {descending : true}"); else if (r.reduce && false !== s.reduce) if (s.include_docs) throw new QueryParseError("{include_docs:true} is invalid for reduce"); else if (s.keys && s.keys.length > 1 && !s.group && !s.group_level) throw new QueryParseError("Multi-key fetches for reduce views must use {group: true}");
[ "group_level", "limit", "skip" ].forEach((function(r) {
const o = function checkPositiveInteger(s) {
if (s) {
if ("number" != typeof s) return new QueryParseError(`Invalid value for integer: "${s}"`);
if (s < 0) return new QueryParseError(`Invalid value for positive integer: "${s}"`);
}
}(s[r]);
if (o) throw o;
}));
}
function defaultsTo(s) {
return function(r) {
if (404 === r.status) return s; else throw r;
};
}
function getQueue(s) {
const r = "string" == typeof s ? s : s.name;
let o = persistentQueues[r];
if (!o) o = persistentQueues[r] = new TaskQueue2;
return o;
}
async function updateView(s, o) {
return sequentialize(getQueue(s), (function() {
return async function updateViewInQueue(s, o) {
let u, g, _;
const m = r(s.mapFun, (function emit2(s, r) {
const o = {
id: g._id,
key: normalizeKey(s)
};
if ("undefined" != typeof r && null !== r) o.value = normalizeKey(r);
u.push(o);
}));
let b = s.seq || 0, E = 0;
const w = {
view: s.name,
indexed_docs: E
};
s.sourceDB.emit("indexing", w);
const S = new TaskQueue2;
function createIndexableKeysToKeyValues(s) {
const r = new ExportedMap;
let o;
for (let u = 0, g = s.length; u < g; u++) {
const g = s[u], _ = [ g.key, g.id ];
if (u > 0 && 0 === collate(g.key, o)) _.push(u);
r.set(toIndexableString(_), g);
o = g.key;
}
return r;
}
try {
await function createTask() {
return s.sourceDB.info().then((function(r) {
_ = s.sourceDB.activeTasks.add({
name: "view_indexing",
total_items: r.update_seq - b
});
}));
}();
await async function processNextBatch() {
return function processBatch(r, w) {
var L = r.results;
if (!L.length && !w.length) return;
for (let s of w) if (L.findIndex((function(r) {
return r.id === s.docId;
})) < 0) {
const r = {
_id: s.docId,
doc: {
_id: s.docId,
_deleted: 1
},
changes: []
};
if (s.doc) {
r.doc = s.doc;
r.changes.push({
rev: s.doc._rev
});
}
L.push(r);
}
var O = function createDocIdsToChangesAndEmits(r) {
const o = new ExportedMap;
for (let _ = 0, E = r.length; _ < E; _++) {
const E = r[_];
if ("_" !== E.doc._id[0]) {
u = [];
g = E.doc;
if (!g._deleted) tryMap(s.sourceDB, m, g);
u.sort(sortByKeyThenValue);
const r = createIndexableKeysToKeyValues(u);
o.set(E.doc._id, [ r, E.changes ]);
}
b = E.seq;
}
return o;
}(L);
S.add(function processChange2(r, o) {
return function() {
return function saveKeyValues(s, r, o) {
var u = "_local/lastSeq";
return s.db.get(u).catch(defaultsTo({
_id: u,
seq: 0
})).then((function(u) {
var g = mapToKeysArray(r);
return Promise.all(g.map((function(o) {
return async function getDocsToPersist(s, r, o) {
const u = "_local/doc_" + s, g = {
_id: u,
keys: []
}, _ = o.get(s), m = _[0], b = _[1], E = await function getMetaDoc() {
if (isGenOne(b)) return Promise.resolve(g); else return r.db.get(u).catch(defaultsTo(g));
}();
return function processKeyValueDocs(s, r) {
const o = [], u = new ExportedSet;
for (let s = 0, g = r.rows.length; s < g; s++) {
const g = r.rows[s].doc;
if (g) {
o.push(g);
u.add(g._id);
g._deleted = !m.has(g._id);
if (!g._deleted) {
const s = m.get(g._id);
if ("value" in s) g.value = s.value;
}
}
}
const g = mapToKeysArray(m);
g.forEach((function(s) {
if (!u.has(s)) {
const r = {
_id: s
}, u = m.get(s);
if ("value" in u) r.value = u.value;
o.push(r);
}
}));
s.keys = uniq(g.concat(s.keys));
o.push(s);
return o;
}(E, await function getKeyValueDocs(s) {
if (!s.keys.length) return Promise.resolve({
rows: []
}); else return r.db.allDocs({
keys: s.keys,
include_docs: true
});
}(E));
}(o, s, r);
}))).then((function(r) {
var g = flatten(r);
u.seq = o;
g.push(u);
return s.db.bulkDocs({
docs: g
});
})).then((() => function updatePurgeSeq(s) {
return s.sourceDB.get("_local/purges").then((function(r) {
const o = r.purgeSeq;
return s.db.get("_local/purgeSeq").then((function(s) {
return s._rev;
})).catch((function(s) {
if (404 !== s.status) throw s;
})).then((function(r) {
return s.db.put({
_id: "_local/purgeSeq",
_rev: r,
purgeSeq: o
});
}));
})).catch((function(s) {
if (404 !== s.status) throw s;
}));
}(s)));
}));
}(s, r, o);
};
}(O, b));
E += L.length;
const D = {
view: s.name,
last_seq: r.last_seq,
results_count: L.length,
indexed_docs: E
};
s.sourceDB.emit("indexing", D);
s.sourceDB.activeTasks.update(_, {
completed_items: E
});
if (!(L.length < o.changes_batch_size)) return processNextBatch(); else return;
}(await s.sourceDB.changes({
return_docs: true,
conflicts: true,
include_docs: true,
style: "all_docs",
since: b,
limit: o.changes_batch_size
}), await function getRecentPurges() {
return s.db.get("_local/purgeSeq").then((function(s) {
return s.purgeSeq;
})).catch((function(s) {
if (s && 404 !== s.status) throw s;
return -1;
})).then((function(r) {
return s.sourceDB.get("_local/purges").then((function(o) {
const u = o.purges.filter((function(s, o) {
return o > r;
})).map((s => s.docId)), g = u.filter((function(s, r) {
return u.indexOf(s) === r;
}));
return Promise.all(g.map((function(r) {
return s.sourceDB.get(r).then((function(s) {
return {
docId: r,
doc: s
};
})).catch((function(s) {
if (404 !== s.status) throw s;
return {
docId: r
};
}));
})));
})).catch((function(s) {
if (s && 404 !== s.status) throw s;
return [];
}));
}));
}());
}();
await S.finish();
s.seq = b;
s.sourceDB.activeTasks.remove(_);
} catch (r) {
s.sourceDB.activeTasks.remove(_, r);
}
}(s, o);
}))();
}
function queryView(s, r) {
return sequentialize(getQueue(s), (function() {
return async function queryViewInQueue(s, r) {
let u;
const g = s.reduceFun && false !== r.reduce, _ = r.skip || 0;
if ("undefined" != typeof r.keys && !r.keys.length) {
r.limit = 0;
delete r.keys;
}
async function fetchFromView(r) {
r.include_docs = true;
const o = await s.db.allDocs(r);
u = o.total_rows;
return o.rows.map((function(s) {
if ("value" in s.doc && "object" == typeof s.doc.value && null !== s.doc.value) {
const r = Object.keys(s.doc.value).sort(), o = [ "id", "key", "value" ];
if (!(r < o || r > o)) return s.doc.value;
}
const r = parseIndexableString(s.doc._id);
return {
key: r[0],
id: r[1],
value: "value" in s.doc ? s.doc.value : null
};
}));
}
async function onMapResultsReady(m) {
let b;
if (g) b = function reduceView(s, r, u) {
if (0 === u.group_level) delete u.group_level;
const g = u.group || u.group_level, _ = o(s.reduceFun), m = [], b = isNaN(u.group_level) ? Number.POSITIVE_INFINITY : u.group_level;
r.forEach((function(s) {
const r = m[m.length - 1];
let o = g ? s.key : null;
if (g && Array.isArray(o)) o = o.slice(0, b);
if (!r || 0 !== collate(r.groupKey, o)) m.push({
keys: [ [ s.key, s.id ] ],
values: [ s.value ],
groupKey: o
}); else {
r.keys.push([ s.key, s.id ]);
r.values.push(s.value);
}
}));
r = [];
for (let o = 0, u = m.length; o < u; o++) {
const u = m[o], g = tryReduce(s.sourceDB, _, u.keys, u.values, false);
if (g.error && g.error instanceof BuiltInError) throw g.error;
r.push({
value: g.error ? null : g.output,
key: u.groupKey
});
}
return {
rows: sliceResults(r, u.limit, u.skip)
};
}(s, m, r); else if ("undefined" == typeof r.keys) b = {
total_rows: u,
offset: _,
rows: m
}; else b = {
total_rows: u,
offset: _,
rows: sliceResults(m, r.limit, r.skip)
};
if (r.update_seq) b.update_seq = s.seq;
if (r.include_docs) {
const o = uniq(m.map(rowToDocId)), u = await s.sourceDB.allDocs({
keys: o,
include_docs: true,
conflicts: r.conflicts,
attachments: r.attachments,
binary: r.binary
});
var E = new ExportedMap;
u.rows.forEach((function(s) {
E.set(s.id, s.doc);
}));
m.forEach((function(s) {
var r = rowToDocId(s), o = E.get(r);
if (o) s.doc = o;
}));
return b;
} else return b;
}
if ("undefined" != typeof r.keys) {
const s = r.keys.map((function(s) {
const o = {
startkey: toIndexableString([ s ]),
endkey: toIndexableString([ s, {} ])
};
if (r.update_seq) o.update_seq = true;
return fetchFromView(o);
}));
return onMapResultsReady(flatten(await Promise.all(s)));
} else {
const s = {
descending: r.descending
};
if (r.update_seq) s.update_seq = true;
let o, u;
if ("start_key" in r) o = r.start_key;
if ("startkey" in r) o = r.startkey;
if ("end_key" in r) u = r.end_key;
if ("endkey" in r) u = r.endkey;
if ("undefined" != typeof o) s.startkey = r.descending ? toIndexableString([ o, {} ]) : toIndexableString([ o ]);
if ("undefined" != typeof u) {
let o = false !== r.inclusive_end;
if (r.descending) o = !o;
s.endkey = toIndexableString(o ? [ u, {} ] : [ u ]);
}
if ("undefined" != typeof r.key) {
const o = toIndexableString([ r.key ]), u = toIndexableString([ r.key, {} ]);
if (s.descending) {
s.endkey = o;
s.startkey = u;
} else {
s.startkey = o;
s.endkey = u;
}
}
if (!g) {
if ("number" == typeof r.limit) s.limit = r.limit;
s.skip = _;
}
return onMapResultsReady(await fetchFromView(s));
}
}(s, r);
}))();
}
return {
query: function abstractQuery(r, o, g) {
const _ = this;
if ("function" == typeof o) {
g = o;
o = {};
}
o = o ? function coerceOptions(s) {
s.group_level = coerceInteger(s.group_level);
s.limit = coerceInteger(s.limit);
s.skip = coerceInteger(s.skip);
return s;
}(o) : {};
if ("function" == typeof r) r = {
map: r
};
const m = Promise.resolve().then((function() {
return async function queryPromised(r, o, g) {
if ("function" == typeof r._query) return function customQuery(s, r, o) {
return new Promise((function(u, g) {
s._query(r, o, (function(s, r) {
if (s) return g(s);
u(r);
}));
}));
}(r, o, g);
if (isRemote(r)) return async function httpQuery(s, r, o) {
let u, g, _ = [], m = "GET";
addHttpParam("reduce", o, _);
addHttpParam("include_docs", o, _);
addHttpParam("attachments", o, _);
addHttpParam("limit", o, _);
addHttpParam("descending", o, _);
addHttpParam("group", o, _);
addHttpParam("group_level", o, _);
addHttpParam("skip", o, _);
addHttpParam("stale", o, _);
addHttpParam("conflicts", o, _);
addHttpParam("startkey", o, _, true);
addHttpParam("start_key", o, _, true);
addHttpParam("endkey", o, _, true);
addHttpParam("end_key", o, _, true);
addHttpParam("inclusive_end", o, _);
addHttpParam("key", o, _, true);
addHttpParam("update_seq", o, _);
_ = _.join("&");
_ = "" === _ ? "" : "?" + _;
if ("undefined" != typeof o.keys) {
const s = 2e3, g = `keys=${encodeURIComponent(JSON.stringify(o.keys))}`;
if (g.length + _.length + 1 <= s) _ += ("?" === _[0] ? "&" : "?") + g; else {
m = "POST";
if ("string" == typeof r) u = {
keys: o.keys
}; else r.keys = o.keys;
}
}
if ("string" == typeof r) {
const b = parseViewName(r), E = await s.fetch("_design/" + b[0] + "/_view/" + b[1] + _, {
headers: new h({
"Content-Type": "application/json"
}),
method: m,
body: JSON.stringify(u)
});
g = E.ok;
const w = await E.json();
if (!g) {
w.status = E.status;
throw generateErrorFromResponse(w);
}
w.rows.forEach((function(s) {
if (s.value && s.value.error && "builtin_reduce_error" === s.value.error) throw new Error(s.reason);
}));
return new Promise((function(s) {
s(w);
})).then(postprocessAttachments(o));
}
u = u || {};
Object.keys(r).forEach((function(s) {
if (Array.isArray(r[s])) u[s] = r[s]; else u[s] = r[s].toString();
}));
const b = await s.fetch("_temp_view" + _, {
headers: new h({
"Content-Type": "application/json"
}),
method: "POST",
body: JSON.stringify(u)
});
g = b.ok;
const E = await b.json();
if (!g) {
E.status = b.status;
throw generateErrorFromResponse(E);
}
return new Promise((function(s) {
s(E);
})).then(postprocessAttachments(o));
}(r, o, g);
const _ = {
changes_batch_size: r.__opts.view_update_changes_batch_size || CHANGES_BATCH_SIZE2
};
if ("string" != typeof o) {
checkQueryParseError(g, o);
tempViewQueue.add((async function() {
const u = await createView(r, "temp_view/temp_view", o.map, o.reduce, true, s);
return fin(updateView(u, _).then((function() {
return queryView(u, g);
})), (function() {
return u.db.destroy();
}));
}));
return tempViewQueue.finish();
} else {
const m = o, b = parseViewName(m), E = b[0], w = b[1], S = await r.get("_design/" + E);
if (!(o = S.views && S.views[w])) throw new NotFoundError(`ddoc ${S._id} has no view named ${w}`);
u(S, w);
checkQueryParseError(g, o);
const L = await createView(r, m, o.map, o.reduce, false, s);
if ("ok" === g.stale || "update_after" === g.stale) {
if ("update_after" === g.stale) (0, import_immediate.default)((function() {
updateView(L, _);
}));
return queryView(L, g);
} else {
await updateView(L, _);
return queryView(L, g);
}
}
}(_, r, o);
}));
promisedCallback(m, g);
return m;
},
viewCleanup: callbackify((function() {
const r = this;
if ("function" == typeof r._viewCleanup) return function customViewCleanup(s) {
return new Promise((function(r, o) {
s._viewCleanup((function(s, u) {
if (s) return o(s);
r(u);
}));
}));
}(r);
if (isRemote(r)) return async function httpViewCleanup(s) {
return (await s.fetch("_view_cleanup", {
headers: new h({
"Content-Type": "application/json"
}),
method: "POST"
})).json();
}(r); else return async function localViewCleanup(r) {
try {
const o = await r.get("_local/" + s), u = new ExportedMap;
Object.keys(o.views).forEach((function(s) {
const r = parseViewName(s), o = "_design/" + r[0], g = r[1];
let _ = u.get(o);
if (!_) {
_ = new ExportedSet;
u.set(o, _);
}
_.add(g);
}));
const g = {
keys: mapToKeysArray(u),
include_docs: true
}, _ = await r.allDocs(g), m = {};
_.rows.forEach((function(s) {
const r = s.key.substring(8);
u.get(s.key).forEach((function(u) {
let g = r + "/" + u;
if (!o.views[g]) g = u;
const _ = Object.keys(o.views[g]), b = s.doc && s.doc.views && s.doc.views[u];
_.forEach((function(s) {
m[s] = m[s] || b;
}));
}));
}));
const b = Object.keys(m).filter((function(s) {
return !m[s];
})).map((function(s) {
return sequentialize(getQueue(s), (function() {
return new r.constructor(s, r.__opts).destroy();
}))();
}));
return Promise.all(b).then((function() {
return {
ok: true
};
}));
} catch (s) {
if (404 === s.status) return {
ok: true
}; else throw s;
}
}(r);
}))
};
}
var index_es_default5 = createAbstractMapReduce;
function createBuiltInError(s) {
return new BuiltInError("builtin " + s + " function requires map values to be numbers or number arrays");
}
function sum(s) {
for (var r = 0, o = 0, u = s.length; o < u; o++) {
var g = s[o];
if ("number" != typeof g) if (Array.isArray(g)) {
r = "number" == typeof r ? [ r ] : r;
for (var _ = 0, m = g.length; _ < m; _++) {
var b = g[_];
if ("number" != typeof b) throw createBuiltInError("_sum"); else if ("undefined" == typeof r[_]) r.push(b); else r[_] += b;
}
} else throw createBuiltInError("_sum"); else if ("number" == typeof r) r += g; else r[0] += g;
}
return r;
}
var log = guardedConsole.bind(null, "log"), isArray = Array.isArray, toJSON = JSON.parse;
function evalFunctionWithEval(s, r) {
return scopeEval("return (" + s.replace(/;\s*$/, "") + ");", {
emit: r,
sum,
log,
isArray,
toJSON
});
}
var builtInReduce = {
_sum: function(s, r) {
return sum(r);
},
_count: function(s, r) {
return r.length;
},
_stats: function(s, r) {
return {
sum: sum(r),
min: Math.min.apply(null, r),
max: Math.max.apply(null, r),
count: r.length,
sumsqr: function sumsqr(s) {
for (var r = 0, o = 0, u = s.length; o < u; o++) {
var g = s[o];
r += g * g;
}
return r;
}(r)
};
}
};
function getBuiltIn(s) {
if (/^_sum/.test(s)) return builtInReduce._sum; else if (/^_count/.test(s)) return builtInReduce._count; else if (/^_stats/.test(s)) return builtInReduce._stats; else if (/^_/.test(s)) throw new Error(s + " is not a supported reduce function.");
}
function mapper(s, r) {
if ("function" == typeof s && 2 === s.length) {
var o = s;
return function(s) {
return o(s, r);
};
} else return evalFunctionWithEval(s.toString(), r);
}
function reducer(s) {
var r = s.toString(), o = getBuiltIn(r);
if (o) return o; else return evalFunctionWithEval(r);
}
function ddocValidator(s, r) {
var o = s.views && s.views[r];
if ("string" != typeof o.map) throw new NotFoundError("ddoc " + s._id + " has no string view named " + r + ", instead found object of type: " + typeof o.map);
}
var localDocName = "mrviews", abstract = index_es_default5(localDocName, mapper, reducer, ddocValidator);
function query2(s, r, o) {
return abstract.query.call(this, s, r, o);
}
function viewCleanup2(s) {
return abstract.viewCleanup.call(this, s);
}
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(s, r, o, u, g) {
return s.get(r).catch((function(o) {
if (404 === o.status) {
if ("http" === s.adapter || "https" === s.adapter) explainError(404, "PouchDB is just checking if a remote checkpoint exists.");
return {
session_id: u,
_id: r,
history: [],
replicator: REPLICATOR,
version: CHECKPOINT_VERSION
};
}
throw o;
})).then((function(_) {
if (!g.cancelled) if (_.last_seq !== o) {
_.history = (_.history || []).filter((function(s) {
return s.session_id !== u;
}));
_.history.unshift({
last_seq: o,
session_id: u
});
_.history = _.history.slice(0, CHECKPOINT_HISTORY_SIZE);
_.version = CHECKPOINT_VERSION;
_.replicator = REPLICATOR;
_.session_id = u;
_.last_seq = o;
return s.put(_).catch((function(_) {
if (409 === _.status) return updateCheckpoint(s, r, o, u, g);
throw _;
}));
}
}));
}
var CheckpointerInternal = class {
constructor(s, r, o, u, g) {
this.src = s;
this.target = r;
this.id = o;
this.returnValue = u;
this.opts = g || {};
}
writeCheckpoint(s, r) {
var o = this;
return this.updateTarget(s, r).then((function() {
return o.updateSource(s, r);
}));
}
updateTarget(s, r) {
if (this.opts.writeTargetCheckpoint) return updateCheckpoint(this.target, this.id, s, r, this.returnValue); else return Promise.resolve(true);
}
updateSource(s, r) {
if (this.opts.writeSourceCheckpoint) {
var o = this;
return updateCheckpoint(this.src, this.id, s, r, this.returnValue).catch((function(s) {
if (isForbiddenError(s)) {
o.opts.writeSourceCheckpoint = false;
return true;
}
throw s;
}));
} else return Promise.resolve(true);
}
getCheckpoint() {
var s = this;
if (s.opts && s.opts.writeSourceCheckpoint && !s.opts.writeTargetCheckpoint) return s.src.get(s.id).then((function(s) {
return s.last_seq || LOWEST_SEQ;
})).catch((function(s) {
if (404 !== s.status) throw s;
return LOWEST_SEQ;
})); else return s.target.get(s.id).then((function(r) {
if (s.opts && s.opts.writeTargetCheckpoint && !s.opts.writeSourceCheckpoint) return r.last_seq || LOWEST_SEQ; else return s.src.get(s.id).then((function(s) {
if (r.version !== s.version) return LOWEST_SEQ;
var o;
if (r.version) o = r.version.toString(); else o = "undefined";
if (o in comparisons) return comparisons[o](r, s); else return LOWEST_SEQ;
}), (function(o) {
if (404 === o.status && r.last_seq) return s.src.put({
_id: s.id,
last_seq: LOWEST_SEQ
}).then((function() {
return LOWEST_SEQ;
}), (function(o) {
if (isForbiddenError(o)) {
s.opts.writeSourceCheckpoint = false;
return r.last_seq;
}
return LOWEST_SEQ;
}));
throw o;
}));
})).catch((function(s) {
if (404 !== s.status) throw s;
return LOWEST_SEQ;
}));
}
}, comparisons = {
undefined: function(s, r) {
if (0 === collate(s.last_seq, r.last_seq)) return r.last_seq; else return 0;
},
1: function(s, r) {
return compareReplicationLogs(r, s).last_seq;
}
};
function compareReplicationLogs(s, r) {
if (s.session_id === r.session_id) return {
last_seq: s.last_seq,
history: s.history
}; else return compareReplicationHistory(s.history, r.history);
}
function compareReplicationHistory(s, r) {
var o = s[0], u = s.slice(1), g = r[0], _ = r.slice(1);
if (!o || 0 === r.length) return {
last_seq: LOWEST_SEQ,
history: []
};
if (hasSessionId(o.session_id, r)) return {
last_seq: o.last_seq,
history: s
};
if (hasSessionId(g.session_id, u)) return {
last_seq: g.last_seq,
history: _
}; else return compareReplicationHistory(u, _);
}
function hasSessionId(s, r) {
var o = r[0], u = r.slice(1);
if (!s || 0 === r.length) return false;
if (s === o.session_id) return true; else return hasSessionId(s, u);
}
function isForbiddenError(s) {
return "number" == typeof s.status && 4 === Math.floor(s.status / 100);
}
function Checkpointer(s, r, o, u, g) {
if (!(this instanceof CheckpointerInternal)) return new CheckpointerInternal(s, r, o, u, g); else return Checkpointer;
}
var index_es_default6 = Checkpointer;
function sortObjectPropertiesByKey(s) {
return Object.keys(s).sort(collate).reduce((function(r, o) {
r[o] = s[o];
return r;
}), {});
}
function generateReplicationId(s, r, o) {
var u = o.doc_ids ? o.doc_ids.sort(collate) : "", g = o.filter ? o.filter.toString() : "", _ = "", m = "", b = "";
if (o.selector) b = JSON.stringify(o.selector);
if (o.filter && o.query_params) _ = JSON.stringify(sortObjectPropertiesByKey(o.query_params));
if (o.filter && "_view" === o.filter) m = o.view.toString();
return Promise.all([ s.id(), r.id() ]).then((function(s) {
var r = s[0] + s[1] + g + m + _ + u + b;
return new Promise((function(s) {
binaryMd5(r, s);
}));
})).then((function(s) {
return "_local/" + (s = s.replace(/\//g, ".").replace(/\+/g, "_"));
}));
}
var index_es_default7 = generateReplicationId, import_events3 = __toESM(require_events());
function fileHasChanged(s, r, o) {
return !s._attachments || !s._attachments[o] || s._attachments[o].digest !== r._attachments[o].digest;
}
function getDocAttachments(s, r) {
var o = Object.keys(r._attachments);
return Promise.all(o.map((function(o) {
return s.getAttachment(r._id, o, {
rev: r._rev
});
})));
}
function getDocAttachmentsFromTargetOrSource(s, r, o) {
var u = isRemote(r) && !isRemote(s), g = Object.keys(o._attachments);
if (!u) return getDocAttachments(r, o); else return s.get(o._id).then((function(u) {
return Promise.all(g.map((function(g) {
if (fileHasChanged(u, o, g)) return r.getAttachment(o._id, g); else return s.getAttachment(u._id, g);
})));
})).catch((function(s) {
if (404 !== s.status) throw s;
return getDocAttachments(r, o);
}));
}
function createBulkGetOpts(s) {
var r = [];
Object.keys(s).forEach((function(o) {
s[o].missing.forEach((function(s) {
r.push({
id: o,
rev: s
});
}));
}));
return {
docs: r,
revs: true,
latest: true
};
}
function getDocs(s, r, o, u) {
o = clone(o);
var g = [], _ = true;
return Promise.resolve().then((function getAllDocs() {
var m = createBulkGetOpts(o);
if (m.docs.length) return s.bulkGet(m).then((function(o) {
if (u.cancelled) throw new Error("cancelled");
return Promise.all(o.results.map((function(o) {
return Promise.all(o.docs.map((function(o) {
var u = o.ok;
if (o.error) _ = false;
if (!u || !u._attachments) return u; else return getDocAttachmentsFromTargetOrSource(r, s, u).then((function(s) {
var r = Object.keys(u._attachments);
s.forEach((function(s, o) {
var g = u._attachments[r[o]];
delete g.stub;
delete g.length;
g.data = s;
}));
return u;
}));
})));
}))).then((function(s) {
g = g.concat(flatten(s).filter(Boolean));
}));
}));
})).then((function returnResult() {
return {
ok: _,
docs: g
};
}));
}
var STARTING_BACK_OFF = 0;
function backOff(s, r, o, u) {
if (false !== s.retry) {
if ("function" != typeof s.back_off_function) s.back_off_function = defaultBackOff;
r.emit("requestError", o);
if ("active" === r.state || "pending" === r.state) {
r.emit("paused", o);
r.state = "stopped";
var g = function backoffTimeSet() {
s.current_back_off = STARTING_BACK_OFF;
};
r.once("paused", (function removeBackOffTimeSet() {
r.removeListener("active", g);
}));
r.once("active", g);
}
s.current_back_off = s.current_back_off || STARTING_BACK_OFF;
s.current_back_off = s.back_off_function(s.current_back_off);
setTimeout(u, s.current_back_off);
} else {
r.emit("error", o);
r.removeAllListeners();
}
}
function replicate(s, r, o, u, g) {
var _, m, b, E, w = [], S = {
seq: 0,
changes: [],
docs: []
}, L = false, O = false, D = false, k = 0, C = 0, T = o.continuous || o.live || false, I = o.batch_size || 100, A = o.batches_limit || 10, R = o.style || "all_docs", x = false, P = o.doc_ids, N = o.selector, B = [], F = uuid();
g = g || {
ok: true,
start_time: (new Date).toISOString(),
docs_read: 0,
docs_written: 0,
doc_write_failures: 0,
errors: []
};
var M = {};
u.ready(s, r);
function initCheckpointer() {
if (b) return Promise.resolve(); else return index_es_default7(s, r, o).then((function(g) {
m = g;
var _ = {};
if (false === o.checkpoint) _ = {
writeSourceCheckpoint: false,
writeTargetCheckpoint: false
}; else if ("source" === o.checkpoint) _ = {
writeSourceCheckpoint: true,
writeTargetCheckpoint: false
}; else if ("target" === o.checkpoint) _ = {
writeSourceCheckpoint: false,
writeTargetCheckpoint: true
}; else _ = {
writeSourceCheckpoint: true,
writeTargetCheckpoint: true
};
b = new index_es_default6(s, r, m, u, _);
}));
}
function writeDocs() {
B = [];
if (0 !== _.docs.length) {
var s = _.docs, m = {
timeout: o.timeout
};
return r.bulkDocs({
docs: s,
new_edits: false
}, m).then((function(r) {
if (u.cancelled) {
completeReplication();
throw new Error("cancelled");
}
var o = Object.create(null);
r.forEach((function(s) {
if (s.error) o[s.id] = s;
}));
var _ = Object.keys(o).length;
g.doc_write_failures += _;
g.docs_written += s.length - _;
s.forEach((function(s) {
var r = o[s._id];
if (r) {
g.errors.push(r);
var _ = (r.name || "").toLowerCase();
if ("unauthorized" === _ || "forbidden" === _) u.emit("denied", clone(r)); else throw r;
} else B.push(s);
}));
}), (function(r) {
g.doc_write_failures += s.length;
throw r;
}));
}
}
function finishBatch() {
if (_.error) throw new Error("There was a problem getting docs.");
g.last_seq = C = _.seq;
var r = clone(g);
if (B.length) {
r.docs = B;
if ("number" == typeof _.pending) {
r.pending = _.pending;
delete _.pending;
}
u.emit("change", r);
}
L = true;
s.info().then((function(r) {
var o = s.activeTasks.get(E);
if (_ && o) {
var u = o.completed_items || 0, g = parseInt(r.update_seq, 10) - parseInt(k, 10);
s.activeTasks.update(E, {
completed_items: u + _.changes.length,
total_items: g
});
}
}));
return b.writeCheckpoint(_.seq, F).then((function() {
u.emit("checkpoint", {
checkpoint: _.seq
});
L = false;
if (u.cancelled) {
completeReplication();
throw new Error("cancelled");
}
_ = void 0;
getChanges();
})).catch((function(s) {
onCheckpointError(s);
throw s;
}));
}
function getBatchDocs() {
return getDocs(s, r, _.diffs, u).then((function(s) {
_.error = !s.ok;
s.docs.forEach((function(s) {
delete _.diffs[s._id];
g.docs_read++;
_.docs.push(s);
}));
}));
}
function startNextBatch() {
if (!u.cancelled && !_) if (0 !== w.length) {
_ = w.shift();
u.emit("checkpoint", {
start_next_batch: _.seq
});
(function getDiffs() {
var s = {};
_.changes.forEach((function(r) {
u.emit("checkpoint", {
revs_diff: r
});
if ("_user/" !== r.id) s[r.id] = r.changes.map((function(s) {
return s.rev;
}));
}));
return r.revsDiff(s).then((function(s) {
if (u.cancelled) {
completeReplication();
throw new Error("cancelled");
}
_.diffs = s;
}));
})().then(getBatchDocs).then(writeDocs).then(finishBatch).then(startNextBatch).catch((function(s) {
abortReplication("batch processing terminated with error", s);
}));
} else processPendingBatch(true);
}
function processPendingBatch(s) {
if (0 !== S.changes.length) {
if (s || O || S.changes.length >= I) {
w.push(S);
S = {
seq: 0,
changes: [],
docs: []
};
if ("pending" === u.state || "stopped" === u.state) {
u.state = "active";
u.emit("active");
}
startNextBatch();
}
} else if (0 === w.length && !_) {
if (T && M.live || O) {
u.state = "pending";
u.emit("paused");
}
if (O) completeReplication();
}
}
function abortReplication(s, r) {
if (!D) {
if (!r.message) r.message = s;
g.ok = false;
g.status = "aborting";
w = [];
S = {
seq: 0,
changes: [],
docs: []
};
completeReplication(r);
}
}
function completeReplication(_) {
if (!D) {
if (u.cancelled) {
g.status = "cancelled";
if (L) return;
}
g.status = g.status || "complete";
g.end_time = (new Date).toISOString();
g.last_seq = C;
D = true;
s.activeTasks.remove(E, _);
if (_) {
(_ = createError(_)).result = g;
var m = (_.name || "").toLowerCase();
if ("unauthorized" === m || "forbidden" === m) {
u.emit("error", _);
u.removeAllListeners();
} else backOff(o, u, _, (function() {
replicate(s, r, o, u);
}));
} else {
u.emit("complete", g);
u.removeAllListeners();
}
}
}
function onChange(r, g, _) {
if (u.cancelled) return completeReplication();
if ("number" == typeof g) S.pending = g;
if (filterChange(o)(r)) {
S.seq = r.seq || _;
S.changes.push(r);
u.emit("checkpoint", {
pending_batch: S.seq
});
(0, import_immediate.default)((function() {
processPendingBatch(0 === w.length && M.live);
}));
} else {
var m = s.activeTasks.get(E);
if (m) {
var b = m.completed_items || 0;
s.activeTasks.update(E, {
completed_items: ++b
});
}
}
}
function onChangesComplete(s) {
x = false;
if (u.cancelled) return completeReplication();
if (s.results.length > 0) {
M.since = s.results[s.results.length - 1].seq;
getChanges();
processPendingBatch(true);
} else {
var complete = function() {
if (T) {
M.live = true;
getChanges();
} else O = true;
processPendingBatch(true);
};
if (!_ && 0 === s.results.length) {
L = true;
b.writeCheckpoint(s.last_seq, F).then((function() {
L = false;
g.last_seq = C = s.last_seq;
if (u.cancelled) {
completeReplication();
throw new Error("cancelled");
} else complete();
})).catch(onCheckpointError);
} else complete();
}
}
function onChangesError(s) {
x = false;
if (u.cancelled) return completeReplication();
abortReplication("changes rejected", s);
}
function getChanges() {
if (!x && !O && w.length < A) {
x = true;
if (u._changes) {
u.removeListener("cancel", u._abortChanges);
u._changes.cancel();
}
u.once("cancel", abortChanges);
var r = s.changes(M).on("change", onChange);
r.then(removeListener, removeListener);
r.then(onChangesComplete).catch(onChangesError);
if (o.retry) {
u._changes = r;
u._abortChanges = abortChanges;
}
}
function abortChanges() {
r.cancel();
}
function removeListener() {
u.removeListener("cancel", abortChanges);
}
}
function createTask(r) {
return s.info().then((function(u) {
var g = "undefined" == typeof o.since ? parseInt(u.update_seq, 10) - parseInt(r, 10) : parseInt(u.update_seq, 10);
E = s.activeTasks.add({
name: `${T ? "continuous " : ""}replication from ${u.db_name}`,
total_items: g
});
return r;
}));
}
function startChanges() {
initCheckpointer().then((function() {
if (!u.cancelled) return b.getCheckpoint().then(createTask).then((function(s) {
k = s;
M = {
since: C = s,
limit: I,
batch_size: I,
style: R,
doc_ids: P,
selector: N,
return_docs: true
};
if (o.filter) if ("string" != typeof o.filter) M.include_docs = true; else M.filter = o.filter;
if ("heartbeat" in o) M.heartbeat = o.heartbeat;
if ("timeout" in o) M.timeout = o.timeout;
if (o.query_params) M.query_params = o.query_params;
if (o.view) M.view = o.view;
getChanges();
})); else completeReplication();
})).catch((function(s) {
abortReplication("getCheckpoint rejected with ", s);
}));
}
function onCheckpointError(s) {
L = false;
abortReplication("writeCheckpoint completed with error", s);
}
if (!u.cancelled) {
if (!u._addedListeners) {
u.once("cancel", completeReplication);
if ("function" == typeof o.complete) {
u.once("error", o.complete);
u.once("complete", (function(s) {
o.complete(null, s);
}));
}
u._addedListeners = true;
}
if ("undefined" == typeof o.since) startChanges(); else initCheckpointer().then((function() {
L = true;
return b.writeCheckpoint(o.since, F);
})).then((function() {
L = false;
if (!u.cancelled) {
C = o.since;
startChanges();
} else completeReplication();
})).catch(onCheckpointError);
} else completeReplication();
}
var Replication = class extends import_events3.default {
constructor() {
super();
this.cancelled = false;
this.state = "pending";
const s = new Promise(((s, r) => {
this.once("complete", s);
this.once("error", r);
}));
this.then = function(r, o) {
return s.then(r, o);
};
this.catch = function(r) {
return s.catch(r);
};
this.catch((function() {}));
}
cancel() {
this.cancelled = true;
this.state = "cancelled";
this.emit("cancel");
}
ready(s, r) {
if (this._readyCalled) return;
this._readyCalled = true;
const onDestroy2 = () => {
this.cancel();
};
s.once("destroyed", onDestroy2);
r.once("destroyed", onDestroy2);
function cleanup() {
s.removeListener("destroyed", onDestroy2);
r.removeListener("destroyed", onDestroy2);
}
this.once("complete", cleanup);
this.once("error", cleanup);
}
};
function toPouch(s, r) {
var o = r.PouchConstructor;
if ("string" == typeof s) return new o(s, r); else return s;
}
function replicateWrapper(s, r, o, u) {
if ("function" == typeof o) {
u = o;
o = {};
}
if ("undefined" == typeof o) o = {};
if (o.doc_ids && !Array.isArray(o.doc_ids)) throw createError(BAD_REQUEST, "`doc_ids` filter parameter is not a list.");
o.complete = u;
(o = clone(o)).continuous = o.continuous || o.live;
o.retry = "retry" in o ? o.retry : false;
o.PouchConstructor = o.PouchConstructor || this;
var g = new Replication(o);
replicate(toPouch(s, o), toPouch(r, o), o, g);
return g;
}
function sync(s, r, o, u) {
if ("function" == typeof o) {
u = o;
o = {};
}
if ("undefined" == typeof o) o = {};
(o = clone(o)).PouchConstructor = o.PouchConstructor || this;
s = toPouch(s, o);
r = toPouch(r, o);
return new Sync(s, r, o, u);
}
var Sync = class extends import_events3.default {
constructor(s, r, o, u) {
super();
this.canceled = false;
const g = o.push ? assign$2({}, o, o.push) : o, _ = o.pull ? assign$2({}, o, o.pull) : o;
this.push = replicateWrapper(s, r, g);
this.pull = replicateWrapper(r, s, _);
this.pushPaused = true;
this.pullPaused = true;
const pullChange = s => {
this.emit("change", {
direction: "pull",
change: s
});
}, pushChange = s => {
this.emit("change", {
direction: "push",
change: s
});
}, pushDenied = s => {
this.emit("denied", {
direction: "push",
doc: s
});
}, pullDenied = s => {
this.emit("denied", {
direction: "pull",
doc: s
});
}, 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 m = {};
const removeAll = s => (r, o) => {
if ("change" === r && (o === pullChange || o === pushChange) || "denied" === r && (o === pullDenied || o === pushDenied) || "paused" === r && (o === pullPaused || o === pushPaused) || "active" === r && (o === pullActive || o === pushActive)) {
if (!(r in m)) m[r] = {};
m[r][s] = true;
if (2 === Object.keys(m[r]).length) this.removeAllListeners(r);
}
};
if (o.live) {
this.push.on("complete", this.pull.cancel.bind(this.pull));
this.pull.on("complete", this.push.cancel.bind(this.push));
}
function addOneListener(s, r, o) {
if (-1 == s.listeners(r).indexOf(o)) s.on(r, o);
}
this.on("newListener", (function(s) {
if ("change" === s) {
addOneListener(this.pull, "change", pullChange);
addOneListener(this.push, "change", pushChange);
} else if ("denied" === s) {
addOneListener(this.pull, "denied", pullDenied);
addOneListener(this.push, "denied", pushDenied);
} else if ("active" === s) {
addOneListener(this.pull, "active", pullActive);
addOneListener(this.push, "active", pushActive);
} else if ("paused" === s) {
addOneListener(this.pull, "paused", pullPaused);
addOneListener(this.push, "paused", pushPaused);
}
}));
this.on("removeListener", (function(s) {
if ("change" === s) {
this.pull.removeListener("change", pullChange);
this.push.removeListener("change", pushChange);
} else if ("denied" === s) {
this.pull.removeListener("denied", pullDenied);
this.push.removeListener("denied", pushDenied);
} else if ("active" === s) {
this.pull.removeListener("active", pullActive);
this.push.removeListener("active", pushActive);
} else if ("paused" === s) {
this.pull.removeListener("paused", pullPaused);
this.push.removeListener("paused", pushPaused);
}
}));
this.pull.on("removeListener", removeAll("pull"));
this.push.on("removeListener", removeAll("push"));
const b = Promise.all([ this.push, this.pull ]).then((s => {
const r = {
push: s[0],
pull: s[1]
};
this.emit("complete", r);
if (u) u(null, r);
this.removeAllListeners();
return r;
}), (s => {
this.cancel();
if (u) u(s); else this.emit("error", s);
this.removeAllListeners();
if (u) throw s;
}));
this.then = function(s, r) {
return b.then(s, r);
};
this.catch = function(s) {
return b.catch(s);
};
}
cancel() {
if (!this.canceled) {
this.canceled = true;
this.push.cancel();
this.pull.cancel();
}
}
};
function replication(s) {
s.replicate = replicateWrapper;
s.sync = sync;
Object.defineProperty(s.prototype, "replicate", {
get: function() {
var s = this;
if ("undefined" == typeof this.replicateMethods) this.replicateMethods = {
from: function(r, o, u) {
return s.constructor.replicate(r, s, o, u);
},
to: function(r, o, u) {
return s.constructor.replicate(s, r, o, u);
}
};
return this.replicateMethods;
}
});
s.prototype.sync = function(s, r, o) {
return this.constructor.sync(this, s, r, o);
};
}
var index_es_default8 = replication;
function massageCreateIndexRequest(s) {
if (!(s = clone(s)).index) s.index = {};
[ "type", "name", "ddoc" ].forEach((function(r) {
if (s.index[r]) {
s[r] = s.index[r];
delete s.index[r];
}
}));
if (s.fields) {
s.index.fields = s.fields;
delete s.fields;
}
if (!s.type) s.type = "json";
return s;
}
function checkFieldValueType(s, r, o) {
var u = "", g = r, _ = true;
if (-1 !== [ "$in", "$nin", "$or", "$and", "$mod", "$nor", "$all" ].indexOf(s)) if (!Array.isArray(r)) u = "Query operator " + s + " must be an array.";
if (-1 !== [ "$not", "$elemMatch", "$allMatch" ].indexOf(s)) if (!(!Array.isArray(r) && "object" == typeof r && null !== r)) u = "Query operator " + s + " must be an object.";
if ("$mod" === s && Array.isArray(r)) if (2 !== r.length) u = "Query operator $mod must be in the format [divisor, remainder], where divisor and remainder are both integers."; else {
var m = r[0], b = r[1];
if (0 === m) {
u = "Query operator $mod's divisor cannot be 0, cannot divide by zero.";
_ = false;
}
if ("number" != typeof m || parseInt(m, 10) !== m) {
u = "Query operator $mod's divisor is not an integer.";
g = m;
}
if (parseInt(b, 10) !== b) {
u = "Query operator $mod's remainder is not an integer.";
g = b;
}
}
if ("$exists" === s) if ("boolean" != typeof r) u = "Query operator $exists must be a boolean.";
if ("$type" === s) {
var E = [ "null", "boolean", "number", "string", "array", "object" ], w = '"' + E.slice(0, E.length - 1).join('", "') + '", or "' + E[E.length - 1] + '"';
if ("string" != typeof r) u = "Query operator $type must be a string. Supported values: " + w + "."; else if (-1 == E.indexOf(r)) u = "Query operator $type must be a string. Supported values: " + w + ".";
}
if ("$size" === s) if (parseInt(r, 10) !== r) u = "Query operator $size must be a integer.";
if ("$regex" === s) if ("string" != typeof r) if (o) u = "Query operator $regex must be a string."; else if (!(r instanceof RegExp)) u = "Query operator $regex must be a string or an instance of a javascript regular expression.";
if (u) {
if (_) u += " Received" + (null === g ? " " : Array.isArray(g) ? " array" : " " + typeof g) + ": " + ("object" == typeof g && null !== g ? JSON.stringify(g, null, "\t") : g);
throw new Error(u);
}
}
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(s, r) {
if (Array.isArray(s)) {
for (var o of s) if ("object" == typeof o && null !== m) validateSelector(o, r);
} else for (var u = Object.keys(s), g = 0; g < u.length; g++) {
var _ = u[g], m = s[_];
if (-1 !== requireValidation.indexOf(_)) checkFieldValueType(_, m, r);
if (-1 === equalityOperators.indexOf(_)) if (-1 === arrayTypeComparisonOperators.indexOf(_)) if ("object" == typeof m && null !== m) validateSelector(m, r);
}
}
function dbFetch(s, r, o, u) {
var g, _;
o.headers = new h({
"Content-type": "application/json"
});
s.fetch(r, o).then((function(s) {
g = s.status;
_ = s.ok;
return s.json();
})).then((function(s) {
if (!_) {
s.status = g;
var r = generateErrorFromResponse(s);
u(r);
} else u(null, s);
})).catch(u);
}
function createIndex(s, r, o) {
r = massageCreateIndexRequest(r);
dbFetch(s, "_index", {
method: "POST",
body: JSON.stringify(r)
}, o);
}
function find(s, r, o) {
validateSelector(r.selector, true);
dbFetch(s, "_find", {
method: "POST",
body: JSON.stringify(r)
}, o);
}
function explain(s, r, o) {
dbFetch(s, "_explain", {
method: "POST",
body: JSON.stringify(r)
}, o);
}
function getIndexes(s, r) {
dbFetch(s, "_index", {
method: "GET"
}, r);
}
function deleteIndex(s, r, o) {
var u = r.ddoc, g = r.type || "json", _ = r.name;
if (!u) return o(new Error("you must provide an index's ddoc"));
if (!_) return o(new Error("you must provide an index's name"));
dbFetch(s, "_index/" + [ u, g, _ ].map(encodeURIComponent).join("/"), {
method: "DELETE"
}, o);
}
function callbackify2(s) {
return function(...r) {
var o = r.pop(), u = s.apply(this, r);
promisedCallback2(u, o);
return u;
};
}
function promisedCallback2(s, r) {
s.then((function(s) {
(0, import_immediate.default)((function() {
r(null, s);
}));
}), (function(s) {
(0, import_immediate.default)((function() {
r(s);
}));
}));
return s;
}
var flatten2 = function(...s) {
for (var r = [], o = 0, u = s.length; o < u; o++) {
var g = s[o];
if (Array.isArray(g)) r = r.concat(flatten2.apply(null, g)); else r.push(g);
}
return r;
};
function mergeObjects(s) {
for (var r = {}, o = 0, u = s.length; o < u; o++) r = assign$2(r, s[o]);
return r;
}
function pick2(s, r) {
for (var o = {}, u = 0, g = r.length; u < g; u++) {
var _ = parseField(r[u]), m = getFieldFromDoc(s, _);
if ("undefined" != typeof m) setFieldInDoc(o, _, m);
}
return o;
}
function oneArrayIsSubArrayOfOther(s, r) {
for (var o = 0, u = Math.min(s.length, r.length); o < u; o++) if (s[o] !== r[o]) return false;
return true;
}
function oneArrayIsStrictSubArrayOfOther(s, r) {
if (s.length > r.length) return false; else return oneArrayIsSubArrayOfOther(s, r);
}
function oneSetIsSubArrayOfOther(s, r) {
s = s.slice();
for (var o = 0, u = r.length; o < u; o++) {
var g = r[o];
if (!s.length) break;
var _ = s.indexOf(g);
if (-1 === _) return false; else s.splice(_, 1);
}
return true;
}
function arrayToObject(s) {
for (var r = {}, o = 0, u = s.length; o < u; o++) r[s[o]] = true;
return r;
}
function max(s, r) {
for (var o = null, u = -1, g = 0, _ = s.length; g < _; g++) {
var m = s[g], b = r(m);
if (b > u) {
u = b;
o = m;
}
}
return o;
}
function arrayEquals(s, r) {
if (s.length !== r.length) return false;
for (var o = 0, u = s.length; o < u; o++) if (s[o] !== r[o]) return false;
return true;
}
function uniq2(s) {
for (var r = {}, o = 0; o < s.length; o++) r["$" + s[o]] = true;
return Object.keys(r).map((function(s) {
return s.substring(1);
}));
}
function createDeepMultiMapper(s, r, o) {
return function(u) {
if (!o || matchesSelector(u, o)) {
for (var g = [], _ = 0, m = s.length; _ < m; _++) {
for (var b = parseField(s[_]), E = u, w = 0, S = b.length; w < S; w++) if ("undefined" == typeof (E = E[b[w]])) return;
g.push(E);
}
r(g);
}
};
}
function createDeepSingleMapper(s, r, o) {
var u = parseField(s);
return function(s) {
if (!o || matchesSelector(s, o)) {
for (var g = s, _ = 0, m = u.length; _ < m; _++) if ("undefined" == typeof (g = g[u[_]])) return;
r(g);
}
};
}
function createShallowSingleMapper(s, r, o) {
return function(u) {
if (!o || matchesSelector(u, o)) r(u[s]);
};
}
function createShallowMultiMapper(s, r, o) {
return function(u) {
if (!o || matchesSelector(u, o)) {
for (var g = [], _ = 0, m = s.length; _ < m; _++) g.push(u[s[_]]);
r(g);
}
};
}
function checkShallow(s) {
for (var r = 0, o = s.length; r < o; r++) if (-1 !== s[r].indexOf(".")) return false;
return true;
}
function createMapper(s, r, o) {
var u = checkShallow(s), g = 1 === s.length;
if (u) if (g) return createShallowSingleMapper(s[0], r, o); else return createShallowMultiMapper(s, r, o); else if (g) return createDeepSingleMapper(s[0], r, o); else return createDeepMultiMapper(s, r, o);
}
function mapper2(s, r) {
return createMapper(Object.keys(s.fields), r, s.partial_filter_selector);
}
function reducer2() {
throw new Error("reduce not supported");
}
function ddocValidator2(s, r) {
var o = s.views[r];
if (!o.map || !o.map.fields) throw new Error("ddoc " + s._id + " with view " + r + " 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(s) {
if (s._customFindAbstractMapper) return {
query: function addQueryFallback(r, o) {
var u = abstractMapper.query.bind(this);
return s._customFindAbstractMapper.query.call(this, r, o, u);
},
viewCleanup: function addViewCleanupFallback() {
var r = abstractMapper.viewCleanup.bind(this);
return s._customFindAbstractMapper.viewCleanup.call(this, r);
}
}; else return abstractMapper;
}
function massageSort(s) {
if (!Array.isArray(s)) throw new Error("invalid sort json - should be an array");
return s.map((function(s) {
if ("string" == typeof s) {
var r = {};
r[s] = "asc";
return r;
} else return s;
}));
}
function massageUseIndex(s) {
var r = [];
if ("string" == typeof s) r.push(s); else r = s;
return r.map((function(s) {
return s.replace("_design/", "");
}));
}
function massageIndexDef(s) {
s.fields = s.fields.map((function(s) {
if ("string" == typeof s) {
var r = {};
r[s] = "asc";
return r;
}
return s;
}));
if (s.partial_filter_selector) s.partial_filter_selector = massageSelector(s.partial_filter_selector);
return s;
}
function getKeyFromDoc(s, r) {
for (var o = [], u = 0; u < r.def.fields.length; u++) {
var g = getKey(r.def.fields[u]);
o.push(getFieldFromDoc(s, parseField(g)));
}
return o;
}
function filterInclusiveStart(s, r, o) {
for (var u = o.def.fields, g = 0, _ = s.length; g < _; g++) {
var m = getKeyFromDoc(s[g].doc, o);
if (1 === u.length) m = m[0]; else for (;m.length > r.length; ) m.pop();
if (Math.abs(collate(m, r)) > 0) break;
}
return g > 0 ? s.slice(g) : s;
}
function reverseOptions(s) {
var r = clone(s);
delete r.startkey;
delete r.endkey;
delete r.inclusive_start;
delete r.inclusive_end;
if ("endkey" in s) r.startkey = s.endkey;
if ("startkey" in s) r.endkey = s.startkey;
if ("inclusive_start" in s) r.inclusive_end = s.inclusive_start;
if ("inclusive_end" in s) r.inclusive_start = s.inclusive_end;
return r;
}
function validateIndex(s) {
var r = s.fields.filter((function(s) {
return "asc" === getValue(s);
}));
if (0 !== r.length && r.length !== s.fields.length) throw new Error("unsupported mixed sorting");
}
function validateSort(s, r) {
if (r.defaultUsed && s.sort) {
var o = s.sort.filter((function(s) {
return "_id" !== Object.keys(s)[0];
})).map((function(s) {
return Object.keys(s)[0];
}));
if (o.length > 0) throw new Error('Cannot sort on field(s) "' + o.join(",") + '" when using the default index');
}
if (!r.defaultUsed) ;
}
function validateFindRequest(s) {
if ("object" != typeof s.selector) throw new Error("you must provide a selector when you find()");
}
function getUserFields(s, r) {
var o, u = Object.keys(s), g = r ? r.map(getKey) : [];
if (u.length >= g.length) o = u; else o = g;
if (0 === g.length) return {
fields: o
}; else return {
fields: o = o.sort((function(s, r) {
var o = g.indexOf(s);
if (-1 === o) o = Number.MAX_VALUE;
var u = g.indexOf(r);
if (-1 === u) u = Number.MAX_VALUE;
return o < u ? -1 : o > u ? 1 : 0;
})),
sortOrder: r.map(getKey)
};
}
function createIndex$1(s, r) {
var o, u = clone((r = massageCreateIndexRequest(r)).index);
r.index = massageIndexDef(r.index);
validateIndex(r.index);
function getMd5() {
return o || (o = stringMd5(JSON.stringify(r)));
}
var g = r.name || "idx-" + getMd5(), _ = r.ddoc || "idx-" + getMd5(), m = "_design/" + _, b = false, E = false;
s.constructor.emit("debug", [ "find", "creating index", m ]);
return upsert(s, m, (function updateDdoc(s) {
if (s._rev && "query" !== s.language) b = true;
s.language = "query";
s.views = s.views || {};
if (E = !!s.views[g]) return false;
s.views[g] = {
map: {
fields: mergeObjects(r.index.fields),
partial_filter_selector: r.index.partial_filter_selector
},
reduce: "_count",
options: {
def: u
}
};
return s;
})).then((function() {
if (b) throw new Error('invalid language for ddoc with id "' + m + '" (should be "query")');
})).then((function() {
var r = _ + "/" + g;
return abstractMapper$1(s).query.call(s, r, {
limit: 0,
reduce: false
}).then((function() {
return {
id: m,
name: g,
result: E ? "exists" : "created"
};
}));
}));
}
function getIndexes$1(s) {
return s.allDocs({
startkey: "_design/",
endkey: "_design/",
include_docs: true
}).then((function(s) {
var r = {
indexes: [ {
ddoc: null,
name: "_all_docs",
type: "special",
def: {
fields: [ {
_id: "asc"
} ]
}
} ]
};
r.indexes = flatten2(r.indexes, s.rows.filter((function(s) {
return "query" === s.doc.language;
})).map((function(s) {
return (void 0 !== s.doc.views ? Object.keys(s.doc.views) : []).map((function(r) {
var o = s.doc.views[r];
return {
ddoc: s.id,
name: r,
type: "json",
def: massageIndexDef(o.options.def)
};
}));
})));
r.indexes.sort((function(s, r) {
return compare(s.name, r.name);
}));
r.total_rows = r.indexes.length;
return r;
}));
}
var COLLATE_LO = null, COLLATE_HI = {
"": {}
}, SHORT_CIRCUIT_QUERY = {
queryOpts: {
limit: 0,
startkey: COLLATE_HI,
endkey: COLLATE_LO
},
inMemoryFields: []
};
function checkFieldInIndex(s, r) {
for (var o = s.def.fields.map(getKey), u = 0, g = o.length; u < g; u++) if (r === o[u]) return true;
return false;
}
function userOperatorLosesPrecision(s, r) {
return "$eq" !== getKey(s[r]);
}
function sortFieldsByIndex(s, r) {
var o = r.def.fields.map(getKey);
return s.slice().sort((function(s, r) {
var u = o.indexOf(s), g = o.indexOf(r);
if (-1 === u) u = Number.MAX_VALUE;
if (-1 === g) g = Number.MAX_VALUE;
return compare(u, g);
}));
}
function getBasicInMemoryFields(s, r, o) {
for (var u = false, g = 0, _ = (o = sortFieldsByIndex(o, s)).length; g < _; g++) {
var m = o[g];
if (u || !checkFieldInIndex(s, m)) return o.slice(g);
if (g < _ - 1 && userOperatorLosesPrecision(r, m)) u = true;
}
return [];
}
function getInMemoryFieldsFromNe(s) {
var r = [];
Object.keys(s).forEach((function(o) {
var u = s[o];
Object.keys(u).forEach((function(s) {
if ("$ne" === s) r.push(o);
}));
}));
return r;
}
function getInMemoryFields(s, r, o, u) {
return sortFieldsByIndex(uniq2(flatten2(s, getBasicInMemoryFields(r, o, u), getInMemoryFieldsFromNe(o))), r);
}
function checkIndexFieldsMatch(s, r, o) {
if (r) {
var u = oneArrayIsStrictSubArrayOfOther(r, s), g = oneArrayIsSubArrayOfOther(o, s);
return u && g;
}
return oneSetIsSubArrayOfOther(o, s);
}
var logicalMatchers = [ "$eq", "$gt", "$gte", "$lt", "$lte" ];
function isNonLogicalMatcher(s) {
return -1 === logicalMatchers.indexOf(s);
}
function checkFieldsLogicallySound(s, r) {
var o = r[s[0]];
if ("undefined" == typeof o) return true; else return !(1 === Object.keys(o).length && "$ne" === getKey(o));
}
function checkIndexMatches(s, r, o, u) {
var g = s.def.fields.map(getKey);
if (!checkIndexFieldsMatch(g, r, o)) return false; else return checkFieldsLogicallySound(g, u);
}
function findMatchingIndexes(s, r, o, u) {
return u.filter((function(u) {
return checkIndexMatches(u, o, r, s);
}));
}
function findBestMatchingIndex(s, r, o, u, g) {
var _ = findMatchingIndexes(s, r, o, u);
if (0 === _.length) {
if (g) throw {
error: "no_usable_index",
message: "There is no index available for this selector."
};
var m = u[0];
m.defaultUsed = true;
return m;
}
if (1 === _.length && !g) return _[0];
var b = arrayToObject(r);
if (g) {
var E = "_design/" + g[0], w = 2 === g.length ? g[1] : false, S = _.find((function(s) {
if (w && s.ddoc === E && w === s.name) return true;
if (s.ddoc === E) return true; else return false;
}));
if (!S) throw {
error: "unknown_error",
message: "Could not find that index or could not use that index for the query"
};
return S;
}
return max(_, (function scoreIndex(s) {
for (var r = s.def.fields.map(getKey), o = 0, u = 0, g = r.length; u < g; u++) {
var _ = r[u];
if (b[_]) o++;
}
return o;
}));
}
function getSingleFieldQueryOptsFor(s, r) {
switch (s) {
case "$eq":
return {
key: r
};
case "$lte":
return {
endkey: r
};
case "$gte":
return {
startkey: r
};
case "$lt":
return {
endkey: r,
inclusive_end: false
};
case "$gt":
return {
startkey: r,
inclusive_start: false
};
}
return {
startkey: COLLATE_LO
};
}
function getSingleFieldCoreQueryPlan(s, r) {
var o, u = getKey(r.def.fields[0]), g = s[u] || {}, _ = [];
Object.keys(g).forEach((function(s) {
if (isNonLogicalMatcher(s)) _.push(u);
var r = getSingleFieldQueryOptsFor(s, g[s]);
if (o) o = mergeObjects([ o, r ]); else o = r;
}));
return {
queryOpts: o,
inMemoryFields: _
};
}
function getMultiFieldCoreQueryPlan(s, r) {
switch (s) {
case "$eq":
return {
startkey: r,
endkey: r
};
case "$lte":
return {
endkey: r
};
case "$gte":
return {
startkey: r
};
case "$lt":
return {
endkey: r,
inclusive_end: false
};
case "$gt":
return {
startkey: r,
inclusive_start: false
};
}
}
function getMultiFieldQueryOpts(s, r) {
var o, u, g = r.def.fields.map(getKey), _ = [], m = [], b = [];
function finish(s) {
if (false !== o) m.push(COLLATE_LO);
if (false !== u) b.push(COLLATE_HI);
_ = g.slice(s);
}
for (var E = 0, w = g.length; E < w; E++) {
var S = s[g[E]];
if (!S || !Object.keys(S).length) {
finish(E);
break;
} else if (Object.keys(S).some(isNonLogicalMatcher)) {
finish(E);
break;
} else if (E > 0) {
var L = "$gt" in S || "$gte" in S || "$lt" in S || "$lte" in S, O = Object.keys(s[g[E - 1]]), D = arrayEquals(O, [ "$eq" ]), k = arrayEquals(O, Object.keys(S));
if (L && !D && !k) {
finish(E);
break;
}
}
for (var C = Object.keys(S), T = null, I = 0; I < C.length; I++) {
var A = C[I], R = getMultiFieldCoreQueryPlan(A, S[A]);
if (T) T = mergeObjects([ T, R ]); else T = R;
}
m.push("startkey" in T ? T.startkey : COLLATE_LO);
b.push("endkey" in T ? T.endkey : COLLATE_HI);
if ("inclusive_start" in T) o = T.inclusive_start;
if ("inclusive_end" in T) u = T.inclusive_end;
}
var x = {
startkey: m,
endkey: b
};
if ("undefined" != typeof o) x.inclusive_start = o;
if ("undefined" != typeof u) x.inclusive_end = u;
return {
queryOpts: x,
inMemoryFields: _
};
}
function shouldShortCircuit(s) {
return Object.keys(s).map((function(r) {
return s[r];
})).some((function(s) {
return "object" == typeof s && 0 === Object.keys(s).length;
}));
}
function getDefaultQueryPlan(s) {
return {
queryOpts: {
startkey: null
},
inMemoryFields: [ Object.keys(s) ]
};
}
function getCoreQueryPlan(s, r) {
if (r.defaultUsed) return getDefaultQueryPlan(s, r);
if (1 === r.def.fields.length) return getSingleFieldCoreQueryPlan(s, r); else return getMultiFieldQueryOpts(s, r);
}
function planQuery(s, r) {
var o = s.selector, u = s.sort;
if (shouldShortCircuit(o)) return assign$2({}, SHORT_CIRCUIT_QUERY, {
index: r[0]
});
var g = getUserFields(o, u), _ = g.fields, m = findBestMatchingIndex(o, _, g.sortOrder, r, s.use_index), b = getCoreQueryPlan(o, m);
return {
queryOpts: b.queryOpts,
index: m,
inMemoryFields: getInMemoryFields(b.inMemoryFields, m, o, _)
};
}
function indexToSignature(s) {
return s.ddoc.substring(8) + "/" + s.name;
}
function doAllDocs(s, r) {
var o = clone(r);
if (o.descending) {
if ("endkey" in o && "string" != typeof o.endkey) o.endkey = "";
if ("startkey" in o && "string" != typeof o.startkey) o.limit = 0;
} else {
if ("startkey" in o && "string" != typeof o.startkey) o.startkey = "";
if ("endkey" in o && "string" != typeof o.endkey) o.limit = 0;
}
if ("key" in o && "string" != typeof o.key) o.limit = 0;
if (o.limit > 0 && o.indexes_count) {
o.original_limit = o.limit;
o.limit += o.indexes_count;
}
return s.allDocs(o).then((function(s) {
s.rows = s.rows.filter((function(s) {
return !/^_design\//.test(s.id);
}));
if (o.original_limit) o.limit = o.original_limit;
s.rows = s.rows.slice(0, o.limit);
return s;
}));
}
function find$1(s, r, o) {
if (r.selector) {
validateSelector(r.selector, false);
r.selector = massageSelector(r.selector);
}
if (r.sort) r.sort = massageSort(r.sort);
if (r.use_index) r.use_index = massageUseIndex(r.use_index);
validateFindRequest(r);
return getIndexes$1(s).then((function(u) {
s.constructor.emit("debug", [ "find", "planning query", r ]);
var g = planQuery(r, u.indexes);
s.constructor.emit("debug", [ "find", "query plan", g ]);
var _ = g.index;
validateSort(r, _);
var m = assign$2({
include_docs: true,
reduce: false,
indexes_count: u.total_rows
}, g.queryOpts);
if ("startkey" in m && "endkey" in m && collate(m.startkey, m.endkey) > 0) return {
docs: []
};
if (r.sort && "string" != typeof r.sort[0] && "desc" === getValue(r.sort[0])) {
m.descending = true;
m = reverseOptions(m);
}
if (!g.inMemoryFields.length) {
if ("limit" in r) m.limit = r.limit;
if ("skip" in r) m.skip = r.skip;
}
if (o) return Promise.resolve(g, m); else return Promise.resolve().then((function() {
if ("_all_docs" === _.name) return doAllDocs(s, m); else {
var r = indexToSignature(_);
return abstractMapper$1(s).query.call(s, r, m);
}
})).then((function(s) {
if (false === m.inclusive_start) s.rows = filterInclusiveStart(s.rows, m.startkey, _);
if (g.inMemoryFields.length) s.rows = filterInMemoryFields(s.rows, r, g.inMemoryFields);
var o = {
docs: s.rows.map((function(s) {
var o = s.doc;
if (r.fields) return pick2(o, r.fields); else return o;
}))
};
if (_.defaultUsed) o.warning = "No matching index found, create an index to optimize query time.";
return o;
}));
}));
}
function explain$1(s, r) {
return find$1(s, r, true).then((function(o) {
return {
dbname: s.name,
index: o.index,
selector: r.selector,
range: {
start_key: o.queryOpts.startkey,
end_key: o.queryOpts.endkey
},
opts: {
use_index: r.use_index || [],
bookmark: "nil",
limit: r.limit,
skip: r.skip,
sort: r.sort || {},
fields: r.fields,
conflicts: false,
r: [ 49 ]
},
limit: r.limit,
skip: r.skip || 0,
fields: r.fields
};
}));
}
function deleteIndex$1(s, r) {
if (!r.ddoc) throw new Error("you must supply an index.ddoc when deleting");
if (!r.name) throw new Error("you must supply an index.name when deleting");
var o = r.ddoc, u = r.name;
return upsert(s, o, (function deltaFun(s) {
if (1 === Object.keys(s.views).length && s.views[u]) return {
_id: o,
_deleted: true
};
delete s.views[u];
return s;
})).then((function() {
return abstractMapper$1(s).viewCleanup.apply(s);
})).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(s, r) {
if ("object" != typeof s) return r(new Error("you must provide an index to create"));
(isRemote(this) ? createIndex : createIndexAsCallback)(this, s, r);
}));
plugin.find = toPromise((function(s, r) {
if ("undefined" == typeof r) {
r = s;
s = void 0;
}
if ("object" != typeof s) return r(new Error("you must provide search parameters to find()"));
(isRemote(this) ? find : findAsCallback)(this, s, r);
}));
plugin.explain = toPromise((function(s, r) {
if ("undefined" == typeof r) {
r = s;
s = void 0;
}
if ("object" != typeof s) return r(new Error("you must provide search parameters to explain()"));
(isRemote(this) ? explain : explainAsCallback)(this, s, r);
}));
plugin.getIndexes = toPromise((function(s) {
(isRemote(this) ? getIndexes : getIndexesAsCallback)(this, s);
}));
plugin.deleteIndex = toPromise((function(s, r) {
if ("object" != typeof s) return r(new Error("you must provide an index to delete"));
(isRemote(this) ? deleteIndex : deleteIndexAsCallback)(this, s, r);
}));
var index_browser_es_default3 = plugin, import_transform_pouch = __toESM(require_transform_pouch(), 1);
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(s, r) {
return s.get("_local/purges").then((function(o) {
for (const [u, g] of r) {
const r = o.purgeSeq + 1;
o.purges.push({
docId: u,
rev: g,
purgeSeq: r
});
if (o.purges.length > s.purged_infos_limit) o.purges.splice(0, o.purges.length - s.purged_infos_limit);
o.purgeSeq = r;
}
return o;
})).catch((function(s) {
if (404 !== s.status) throw s;
return {
_id: "_local/purges",
purges: r.map((([s, r], o) => ({
docId: s,
rev: r,
purgeSeq: o
}))),
purgeSeq: r.length
};
})).then((function(r) {
return s.put(r);
}));
}
index_es_default.prototype.purgeMulti = adapterFun("_purgeMulti", (function(s, r) {
if ("undefined" == typeof this._purge) return r(createError(UNKNOWN_ERROR, "Purge is not implemented in the " + this.adapter + " adapter."));
const o = this, u = s.map((s => () => new Promise(((r, u) => {
const [g, _] = s;
o._getRevisionTree(g, ((u, m) => {
if (u) return r([ s, u ]);
if (!m) return r([ s, createError(MISSING_DOC) ]);
let b;
try {
b = findPathToLeaf(m, _);
} catch (o) {
return r([ s, o.message || o ]);
}
o._purge(g, b, ((o, u) => {
if (o) return r([ s, o ]); else return r([ s, u ]);
}));
}));
}))));
(async () => {
const s = (await mapAllTasksWithConcurrencyLimit(1, u)).map((s => unwrapTaskResult(s)));
await appendPurgeSeqs(o, s.filter((s => "ok" in s[1])).map((s => s[0])));
return Object.fromEntries(s.map((s => [ s[0][0], s[1] ])));
})().then((s => r(void 0, s))).catch((s => r(s)));
}));
var import_diff_match_patch2 = __toESM(require_diff_match_patch(), 1), ConflictResolveModal = class extends import_obsidian.Modal {
constructor(s, r, o) {
super(s);
this.response = CANCELLED;
this.isClosed = false;
this.consumed = false;
this.result = o;
this.filename = r;
sendValue("cancel-resolve-conflict:" + this.filename, true);
}
onOpen() {
const {contentEl: s} = 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");
s.empty();
s.createEl("span", {
text: this.filename
});
const r = s.createDiv("");
r.addClass("op-scrollable");
let o = "";
for (const s of this.result.diff) {
const r = s[0], u = s[1];
if (r == import_diff_match_patch2.DIFF_DELETE) o += "" + escapeStringToHTML(u).replace(/\n/g, "\n") + ""; else if (r == import_diff_match_patch2.DIFF_EQUAL) o += "" + escapeStringToHTML(u).replace(/\n/g, "\n") + ""; else if (r == import_diff_match_patch2.DIFF_INSERT) o += "" + escapeStringToHTML(u).replace(/\n/g, "\n") + "";
}
o = o.replace(/\n/g, "
");
r.innerHTML = o;
const u = s.createDiv(""), g = new Date(this.result.left.mtime).toLocaleString() + (this.result.left.deleted ? " (Deleted)" : ""), _ = new Date(this.result.right.mtime).toLocaleString() + (this.result.right.deleted ? " (Deleted)" : "");
u.innerHTML = `\nA:${g}
B:${_}
\n `;
s.createEl("button", {
text: "Keep A"
}, (s => s.addEventListener("click", (() => this.sendResponse(this.result.right.rev)))));
s.createEl("button", {
text: "Keep B"
}, (s => s.addEventListener("click", (() => this.sendResponse(this.result.left.rev)))));
s.createEl("button", {
text: "Concat both"
}, (s => s.addEventListener("click", (() => this.sendResponse(LEAVE_TO_SUBSEQUENT)))));
s.createEl("button", {
text: "Not now"
}, (s => s.addEventListener("click", (() => this.sendResponse(CANCELLED)))));
}
sendResponse(s) {
this.response = s;
this.close();
}
onClose() {
const {contentEl: s} = this;
s.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 s = await waitForValue("close-resolve-conflict:" + this.filename);
if (s === RESULT_TIMED_OUT) return CANCELLED; else return s;
}
}, import_obsidian4 = require("obsidian");
function noop() {}
function assign(s, r) {
for (const o in r) s[o] = r[o];
return s;
}
function run(s) {
return s();
}
function blank_object() {
return Object.create(null);
}
function run_all(s) {
s.forEach(run);
}
function is_function(s) {
return "function" == typeof s;
}
function safe_not_equal(s, r) {
return s != s ? r == r : s !== r || s && "object" == typeof s || "function" == typeof s;
}
function is_empty(s) {
return 0 === Object.keys(s).length;
}
function null_to_empty(s) {
return null == s ? "" : s;
}
var globals = "undefined" != typeof window ? window : "undefined" != typeof globalThis ? globalThis : window, ResizeObserverSingleton = class _ResizeObserverSingleton {
constructor(s) {
__publicField(this, "_listeners", "WeakMap" in globals ? new WeakMap : void 0);
__publicField(this, "_observer");
__publicField(this, "options");
this.options = s;
}
observe(s, r) {
this._listeners.set(s, r);
this._getObserver().observe(s, this.options);
return () => {
this._listeners.delete(s);
this._observer.unobserve(s);
};
}
_getObserver() {
var s;
return null != (s = this._observer) ? s : this._observer = new ResizeObserver((s => {
var r;
for (const o of s) {
_ResizeObserverSingleton.entries.set(o.target, o);
null == (r = this._listeners.get(o.target)) || r(o);
}
}));
}
};
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(s, r) {
s.appendChild(r);
}
function append_styles(s, r, o) {
const u = get_root_for_style(s);
if (!u.getElementById(r)) {
const s = element("style");
s.id = r;
s.textContent = o;
append_stylesheet(u, s);
}
}
function get_root_for_style(s) {
if (!s) return document;
const r = s.getRootNode ? s.getRootNode() : s.ownerDocument;
if (r && r.host) return r; else return s.ownerDocument;
}
function append_stylesheet(s, r) {
append(s.head || s, r);
return r.sheet;
}
function insert(s, r, o) {
s.insertBefore(r, o || null);
}
function detach(s) {
if (s.parentNode) s.parentNode.removeChild(s);
}
function destroy_each(s, r) {
for (let o = 0; o < s.length; o += 1) if (s[o]) s[o].d(r);
}
function element(s) {
return document.createElement(s);
}
function text(s) {
return document.createTextNode(s);
}
function space() {
return text(" ");
}
function empty() {
return text("");
}
function comment(s) {
return document.createComment(s);
}
function listen(s, r, o, u) {
s.addEventListener(r, o, u);
return () => s.removeEventListener(r, o, u);
}
function attr(s, r, o) {
if (null == o) s.removeAttribute(r); else if (s.getAttribute(r) !== o) s.setAttribute(r, o);
}
function init_binding_group(s) {
let r;
return {
p(...o) {
r = o;
r.forEach((r => s.push(r)));
},
r() {
r.forEach((r => s.splice(s.indexOf(r), 1)));
}
};
}
function children(s) {
return Array.from(s.childNodes);
}
function set_data(s, r) {
r = "" + r;
if (s.data !== r) s.data = r;
}
function set_input_value(s, r) {
s.value = null == r ? "" : r;
}
function select_option(s, r, o) {
for (let o = 0; o < s.options.length; o += 1) {
const u = s.options[o];
if (u.__value === r) {
u.selected = true;
return;
}
}
if (!o || void 0 !== r) s.selectedIndex = -1;
}
function select_value(s) {
const r = s.querySelector(":checked");
return r && r.__value;
}
function toggle_class(s, r, o) {
s.classList.toggle(r, !!o);
}
function get_custom_elements_slots(s) {
const r = {};
s.childNodes.forEach((s => {
r[s.slot || "default"] = true;
}));
return r;
}
function set_current_component(s) {
current_component = s;
}
function get_current_component() {
if (!current_component) throw new Error("Function called outside component initialization");
return current_component;
}
function onMount(s) {
get_current_component().$$.on_mount.push(s);
}
function onDestroy(s) {
get_current_component().$$.on_destroy.push(s);
}
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(s) {
render_callbacks.push(s);
}
var seen_callbacks = new Set, flushidx = 0;
function flush() {
if (0 !== flushidx) return;
const s = current_component;
do {
try {
for (;flushidx < dirty_components.length; ) {
const s = dirty_components[flushidx];
flushidx++;
set_current_component(s);
update(s.$$);
}
} catch (s) {
dirty_components.length = 0;
flushidx = 0;
throw s;
}
set_current_component(null);
dirty_components.length = 0;
flushidx = 0;
for (;binding_callbacks.length; ) binding_callbacks.pop()();
for (let s = 0; s < render_callbacks.length; s += 1) {
const r = render_callbacks[s];
if (!seen_callbacks.has(r)) {
seen_callbacks.add(r);
r();
}
}
render_callbacks.length = 0;
} while (dirty_components.length);
for (;flush_callbacks.length; ) flush_callbacks.pop()();
update_scheduled = false;
seen_callbacks.clear();
set_current_component(s);
}
function update(s) {
if (null !== s.fragment) {
s.update();
run_all(s.before_update);
const r = s.dirty;
s.dirty = [ -1 ];
s.fragment && s.fragment.p(s.ctx, r);
s.after_update.forEach(add_render_callback);
}
}
function flush_render_callbacks(s) {
const r = [], o = [];
render_callbacks.forEach((u => -1 === s.indexOf(u) ? r.push(u) : o.push(u)));
o.forEach((s => s()));
render_callbacks = r;
}
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(s, r) {
if (s && s.i) {
outroing.delete(s);
s.i(r);
}
}
function transition_out(s, r, o, u) {
if (s && s.o) {
if (outroing.has(s)) return;
outroing.add(s);
outros.c.push((() => {
outroing.delete(s);
if (u) {
if (o) s.d(1);
u();
}
}));
s.o(r);
} else if (u) u();
}
function ensure_array_like(s) {
return void 0 !== (null == s ? void 0 : s.length) ? s : Array.from(s);
}
function get_spread_update(s, r) {
const o = {}, u = {}, g = {
$$scope: 1
};
let _ = s.length;
for (;_--; ) {
const m = s[_], b = r[_];
if (b) {
for (const s in m) if (!(s in b)) u[s] = 1;
for (const s in b) if (!g[s]) {
o[s] = b[s];
g[s] = 1;
}
s[_] = b;
} else for (const s in m) g[s] = 1;
}
for (const s in u) if (!(s in o)) o[s] = void 0;
return o;
}
function get_spread_object(s) {
return "object" == typeof s && null !== s ? s : {};
}
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(s) {
s && s.c();
}
function mount_component(s, r, o) {
const {fragment: u, after_update: g} = s.$$;
u && u.m(r, o);
add_render_callback((() => {
const r = s.$$.on_mount.map(run).filter(is_function);
if (s.$$.on_destroy) s.$$.on_destroy.push(...r); else run_all(r);
s.$$.on_mount = [];
}));
g.forEach(add_render_callback);
}
function destroy_component(s, r) {
const o = s.$$;
if (null !== o.fragment) {
flush_render_callbacks(o.after_update);
run_all(o.on_destroy);
o.fragment && o.fragment.d(r);
o.on_destroy = o.fragment = null;
o.ctx = [];
}
}
function make_dirty(s, r) {
if (-1 === s.$$.dirty[0]) {
dirty_components.push(s);
schedule_update();
s.$$.dirty.fill(0);
}
s.$$.dirty[r / 31 | 0] |= 1 << r % 31;
}
function init2(s, r, o, u, g, _, m = null, b = [ -1 ]) {
const E = current_component;
set_current_component(s);
const w = s.$$ = {
fragment: null,
ctx: [],
props: _,
update: noop,
not_equal: g,
bound: blank_object(),
on_mount: [],
on_destroy: [],
on_disconnect: [],
before_update: [],
after_update: [],
context: new Map(r.context || (E ? E.$$.context : [])),
callbacks: blank_object(),
dirty: b,
skip_bound: false,
root: r.target || E.$$.root
};
m && m(w.root);
let S = false;
w.ctx = o ? o(s, r.props || {}, ((r, o, ...u) => {
const _ = u.length ? u[0] : o;
if (w.ctx && g(w.ctx[r], w.ctx[r] = _)) {
if (!w.skip_bound && w.bound[r]) w.bound[r](_);
if (S) make_dirty(s, r);
}
return o;
})) : [];
w.update();
S = true;
run_all(w.before_update);
w.fragment = u ? u(w.ctx) : false;
if (r.target) {
if (r.hydrate) {
start_hydrating();
const s = children(r.target);
w.fragment && w.fragment.l(s);
s.forEach(detach);
} else w.fragment && w.fragment.c();
if (r.intro) transition_in(s.$$.fragment);
mount_component(s, r.target, r.anchor);
end_hydrating();
flush();
}
set_current_component(E);
}
if ("function" == typeof HTMLElement) SvelteElement = class extends HTMLElement {
constructor(s, r, o) {
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 = s;
this.$$s = r;
if (o) this.attachShadow({
mode: "open"
});
}
addEventListener(s, r, o) {
this.$$l[s] = this.$$l[s] || [];
this.$$l[s].push(r);
if (this.$$c) {
const o = this.$$c.$on(s, r);
this.$$l_u.set(r, o);
}
super.addEventListener(s, r, o);
}
removeEventListener(s, r, o) {
super.removeEventListener(s, r, o);
if (this.$$c) {
const s = this.$$l_u.get(r);
if (s) {
s();
this.$$l_u.delete(r);
}
}
}
async connectedCallback() {
this.$$cn = true;
if (!this.$$c) {
let create_slot = function(s) {
return () => {
let r;
return {
c: function create() {
r = element("slot");
if ("default" !== s) attr(r, "name", s);
},
m: function mount(s, o) {
insert(s, r, o);
},
d: function destroy2(s) {
if (s) detach(r);
}
};
};
};
await Promise.resolve();
if (!this.$$cn || this.$$c) return;
const s = {}, r = get_custom_elements_slots(this);
for (const o of this.$$s) if (o in r) s[o] = [ create_slot(o) ];
for (const s of this.attributes) {
const r = this.$$g_p(s.name);
if (!(r in this.$$d)) this.$$d[r] = get_custom_element_value(r, s.value, this.$$p_d, "toProp");
}
for (const s in this.$$p_d) if (!(s in this.$$d) && void 0 !== this[s]) {
this.$$d[s] = this[s];
delete this[s];
}
this.$$c = new this.$$ctor({
target: this.shadowRoot || this,
props: {
...this.$$d,
$$slots: s,
$$scope: {
ctx: []
}
}
});
const reflect_attributes = () => {
this.$$r = true;
for (const s in this.$$p_d) {
this.$$d[s] = this.$$c.$$.ctx[this.$$c.$$.props[s]];
if (this.$$p_d[s].reflect) {
const r = get_custom_element_value(s, this.$$d[s], this.$$p_d, "toAttribute");
if (null == r) this.removeAttribute(this.$$p_d[s].attribute || s); else this.setAttribute(this.$$p_d[s].attribute || s, r);
}
}
this.$$r = false;
};
this.$$c.$$.after_update.push(reflect_attributes);
reflect_attributes();
for (const s in this.$$l) for (const r of this.$$l[s]) {
const o = this.$$c.$on(s, r);
this.$$l_u.set(r, o);
}
this.$$l = {};
}
}
attributeChangedCallback(s, r, o) {
var u;
if (!this.$$r) {
s = this.$$g_p(s);
this.$$d[s] = get_custom_element_value(s, o, this.$$p_d, "toProp");
null == (u = this.$$c) || u.$set({
[s]: this.$$d[s]
});
}
}
disconnectedCallback() {
this.$$cn = false;
Promise.resolve().then((() => {
if (!this.$$cn) {
this.$$c.$destroy();
this.$$c = void 0;
}
}));
}
$$g_p(s) {
return Object.keys(this.$$p_d).find((r => this.$$p_d[r].attribute === s || !this.$$p_d[r].attribute && r.toLowerCase() === s)) || s;
}
};
function get_custom_element_value(s, r, o, u) {
var g;
const _ = null == (g = o[s]) ? void 0 : g.type;
r = "Boolean" === _ && "boolean" != typeof r ? null != r : r;
if (!u || !o[s]) return r; else if ("toAttribute" === u) switch (_) {
case "Object":
case "Array":
return null == r ? null : JSON.stringify(r);
case "Boolean":
return r ? "" : null;
case "Number":
return null == r ? null : r;
default:
return r;
} else switch (_) {
case "Object":
case "Array":
return r && JSON.parse(r);
case "Boolean":
return r;
case "Number":
return null != r ? +r : r;
default:
return r;
}
}
var SvelteComponent = class {
constructor() {
__publicField(this, "$$");
__publicField(this, "$$set");
}
$destroy() {
destroy_component(this, 1);
this.$destroy = noop;
}
$on(s, r) {
if (!is_function(r)) return noop;
const o = this.$$.callbacks[s] || (this.$$.callbacks[s] = []);
o.push(r);
return () => {
const s = o.indexOf(r);
if (-1 !== s) o.splice(s, 1);
};
}
$set(s) {
if (this.$$set && !is_empty(s)) {
this.$$.skip_bound = true;
this.$$set(s);
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(s, r = noop) {
let o;
const u = new Set;
function set(r) {
if (safe_not_equal(s, r)) {
s = r;
if (o) {
const r = !subscriber_queue.length;
for (const r of u) {
r[1]();
subscriber_queue.push(r, s);
}
if (r) {
for (let s = 0; s < subscriber_queue.length; s += 2) subscriber_queue[s][0](subscriber_queue[s + 1]);
subscriber_queue.length = 0;
}
}
}
}
function update2(r) {
set(r(s));
}
return {
set,
update: update2,
subscribe: function subscribe2(g, _ = noop) {
const m = [ g, _ ];
u.add(m);
if (1 === u.size) o = r(set, update2) || noop;
g(s);
return () => {
u.delete(m);
if (0 === u.size && o) {
o();
o = null;
}
};
}
};
}
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(s, r, o) {
return this.plugin.id2path(s, r, o);
}
async path2id(s, r) {
return await this.plugin.path2id(s, r);
}
getPath(s) {
return this.plugin.getPath(s);
}
constructor(s) {
this.plugin = s;
}
};
function add_css(s) {
append_styles(s, "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(s, r, o) {
const u = s.slice();
u[25] = r[o];
return u;
}
function get_each_context_1(s, r, o) {
const u = s.slice();
u[28] = r[o];
return u;
}
function create_else_block(s) {
let r, o, u, g, _, m, b, E, w, S, L, O, D, k, C, T, I, A, R, x, P, N, B, F, M, V = new Date(s[3].mtime).toLocaleString() + "", G = s[5].length + "", j = new Date(s[4].mtime).toLocaleString() + "", q = s[6].length + "", U = ensure_array_like(s[11]), z = [];
for (let r = 0; r < U.length; r += 1) z[r] = create_each_block_1(get_each_context_1(s, U, r));
function select_block_type_1(s, r) {
if (false != s[8]) return create_if_block_3; else return create_else_block_1;
}
let W = select_block_type_1(s), H = W(s), K = s[3]._id == s[4]._id && create_if_block_2(s), Q = s[3]._id == s[4]._id && create_if_block_1(s);
return {
c() {
r = element("div");
for (let s = 0; s < z.length; s += 1) z[s].c();
o = space();
H.c();
u = space();
g = element("div");
_ = text(s[1]);
m = space();
if (K) K.c();
b = text(" ,");
E = text(V);
w = space();
S = text(G);
L = text(" letters");
O = space();
D = element("div");
k = text(s[2]);
C = space();
if (Q) Q.c();
T = text(" ,");
I = text(j);
A = space();
R = text(q);
x = text(" letters");
P = space();
N = element("div");
B = element("button");
B.textContent = "Apply";
attr(r, "class", "options svelte-guf68w");
attr(g, "class", "svelte-guf68w");
attr(D, "class", "svelte-guf68w");
attr(B, "class", "svelte-guf68w");
attr(N, "class", "buttons svelte-guf68w");
},
m(V, G) {
insert(V, r, G);
for (let s = 0; s < z.length; s += 1) if (z[s]) z[s].m(r, null);
insert(V, o, G);
H.m(V, G);
insert(V, u, G);
insert(V, g, G);
append(g, _);
append(g, m);
if (K) K.m(g, null);
append(g, b);
append(g, E);
append(g, w);
append(g, S);
append(g, L);
insert(V, O, G);
insert(V, D, G);
append(D, k);
append(D, C);
if (Q) Q.m(D, null);
append(D, T);
append(D, I);
append(D, A);
append(D, R);
append(D, x);
insert(V, P, G);
insert(V, N, G);
append(N, B);
if (!F) {
M = listen(B, "click", s[12]);
F = true;
}
},
p(s, o) {
if (2688 & o) {
U = ensure_array_like(s[11]);
let u;
for (u = 0; u < U.length; u += 1) {
const g = get_each_context_1(s, U, u);
if (z[u]) z[u].p(g, o); else {
z[u] = create_each_block_1(g);
z[u].c();
z[u].m(r, null);
}
}
for (;u < z.length; u += 1) z[u].d(1);
z.length = U.length;
}
if (W === (W = select_block_type_1(s)) && H) H.p(s, o); else {
H.d(1);
H = W(s);
if (H) {
H.c();
H.m(u.parentNode, u);
}
}
if (2 & o) set_data(_, s[1]);
if (s[3]._id == s[4]._id) if (K) K.p(s, o); else {
K = create_if_block_2(s);
K.c();
K.m(g, b);
} else if (K) {
K.d(1);
K = null;
}
if (8 & o && V !== (V = new Date(s[3].mtime).toLocaleString() + "")) set_data(E, V);
if (32 & o && G !== (G = s[5].length + "")) set_data(S, G);
if (4 & o) set_data(k, s[2]);
if (s[3]._id == s[4]._id) if (Q) Q.p(s, o); else {
Q = create_if_block_1(s);
Q.c();
Q.m(D, T);
} else if (Q) {
Q.d(1);
Q = null;
}
if (16 & o && j !== (j = new Date(s[4].mtime).toLocaleString() + "")) set_data(I, j);
if (64 & o && q !== (q = s[6].length + "")) set_data(R, q);
},
d(s) {
if (s) {
detach(r);
detach(o);
detach(u);
detach(g);
detach(O);
detach(D);
detach(P);
detach(N);
}
destroy_each(z, s);
H.d(s);
if (K) K.d();
if (Q) Q.d();
F = false;
M();
}
};
}
function create_if_block(s) {
let r, o, u, g, _, m;
return {
c() {
r = element("div");
r.textContent = "Just for a minute, please!";
o = space();
u = element("div");
g = element("button");
g.textContent = "Dismiss";
attr(r, "class", "message svelte-guf68w");
attr(g, "class", "svelte-guf68w");
attr(u, "class", "buttons svelte-guf68w");
},
m(b, E) {
insert(b, r, E);
insert(b, o, E);
insert(b, u, E);
append(u, g);
if (!_) {
m = listen(g, "click", s[12]);
_ = true;
}
},
p: noop,
d(s) {
if (s) {
detach(r);
detach(o);
detach(u);
}
_ = false;
m();
}
};
}
function create_if_block_4(s) {
let r, o, u, g, _, m, b, E, w, S, L = false, O = s[28][1] + "";
E = init_binding_group(s[21][0]);
return {
c() {
r = element("label");
o = element("input");
g = space();
_ = element("div");
m = text(O);
attr(o, "type", "radio");
attr(o, "name", "disp");
o.__value = u = s[28][0];
set_input_value(o, o.__value);
attr(o, "class", "sls-setting-tab svelte-guf68w");
attr(_, "class", "sls-setting-menu-btn svelte-guf68w");
attr(r, "class", b = null_to_empty("sls-setting-label " + (s[28][0] == s[7] ? "selected" : "")) + " svelte-guf68w");
E.p(o);
},
m(u, b) {
insert(u, r, b);
append(r, o);
o.checked = o.__value === s[7];
append(r, g);
append(r, _);
append(_, m);
if (!w) {
S = listen(o, "change", s[20]);
w = true;
}
},
p(s, g) {
if (2048 & g && u !== (u = s[28][0])) {
o.__value = u;
set_input_value(o, o.__value);
L = true;
}
if (L || 2176 & g) o.checked = o.__value === s[7];
if (2048 & g && O !== (O = s[28][1] + "")) set_data(m, O);
if (2176 & g && b !== (b = null_to_empty("sls-setting-label " + (s[28][0] == s[7] ? "selected" : "")) + " svelte-guf68w")) attr(r, "class", b);
},
d(s) {
if (s) detach(r);
E.r();
w = false;
S();
}
};
}
function create_each_block_1(s) {
let r, o = ("" == s[28][0] || false != s[9][s[28][0]]) && create_if_block_4(s);
return {
c() {
if (o) o.c();
r = empty();
},
m(s, u) {
if (o) o.m(s, u);
insert(s, r, u);
},
p(s, u) {
if ("" == s[28][0] || false != s[9][s[28][0]]) if (o) o.p(s, u); else {
o = create_if_block_4(s);
o.c();
o.m(r.parentNode, r);
} else if (o) {
o.d(1);
o = null;
}
},
d(s) {
if (s) detach(r);
if (o) o.d(s);
}
};
}
function create_else_block_1(s) {
let r;
return {
c() {
r = text("NO PREVIEW");
},
m(s, o) {
insert(s, r, o);
},
p: noop,
d(s) {
if (s) detach(r);
}
};
}
function create_if_block_3(s) {
let r, o = ensure_array_like(s[10]), u = [];
for (let r = 0; r < o.length; r += 1) u[r] = create_each_block(get_each_context(s, o, r));
return {
c() {
r = element("div");
for (let s = 0; s < u.length; s += 1) u[s].c();
attr(r, "class", "op-scrollable json-source svelte-guf68w");
},
m(s, o) {
insert(s, r, o);
for (let s = 0; s < u.length; s += 1) if (u[s]) u[s].m(r, null);
},
p(s, g) {
if (1024 & g) {
o = ensure_array_like(s[10]);
let _;
for (_ = 0; _ < o.length; _ += 1) {
const m = get_each_context(s, o, _);
if (u[_]) u[_].p(m, g); else {
u[_] = create_each_block(m);
u[_].c();
u[_].m(r, null);
}
}
for (;_ < u.length; _ += 1) u[_].d(1);
u.length = o.length;
}
},
d(s) {
if (s) detach(r);
destroy_each(u, s);
}
};
}
function create_each_block(s) {
let r, o, u, g = s[25][1] + "";
return {
c() {
r = element("span");
o = text(g);
attr(r, "class", u = null_to_empty(s[25][0] == import_diff_match_patch.DIFF_DELETE ? "deleted" : s[25][0] == import_diff_match_patch.DIFF_INSERT ? "added" : "normal") + " svelte-guf68w");
},
m(s, u) {
insert(s, r, u);
append(r, o);
},
p(s, _) {
if (1024 & _ && g !== (g = s[25][1] + "")) set_data(o, g);
if (1024 & _ && u !== (u = null_to_empty(s[25][0] == import_diff_match_patch.DIFF_DELETE ? "deleted" : s[25][0] == import_diff_match_patch.DIFF_INSERT ? "added" : "normal") + " svelte-guf68w")) attr(r, "class", u);
},
d(s) {
if (s) detach(r);
}
};
}
function create_if_block_2(s) {
let r, o, u = revStringToRevNumber(s[3]._rev) + "";
return {
c() {
r = text("Rev:");
o = text(u);
},
m(s, u) {
insert(s, r, u);
insert(s, o, u);
},
p(s, r) {
if (8 & r && u !== (u = revStringToRevNumber(s[3]._rev) + "")) set_data(o, u);
},
d(s) {
if (s) {
detach(r);
detach(o);
}
}
};
}
function create_if_block_1(s) {
let r, o, u = revStringToRevNumber(s[4]._rev) + "";
return {
c() {
r = text("Rev:");
o = text(u);
},
m(s, u) {
insert(s, r, u);
insert(s, o, u);
},
p(s, r) {
if (16 & r && u !== (u = revStringToRevNumber(s[4]._rev) + "")) set_data(o, u);
},
d(s) {
if (s) {
detach(r);
detach(o);
}
}
};
}
function create_fragment(s) {
let r, o, u, g;
function select_block_type(s, r) {
if (!s[3] || !s[4]) return create_if_block; else return create_else_block;
}
let _ = select_block_type(s), m = _(s);
return {
c() {
r = element("h2");
o = text(s[0]);
u = space();
m.c();
g = empty();
attr(r, "class", "svelte-guf68w");
},
m(s, _) {
insert(s, r, _);
append(r, o);
insert(s, u, _);
m.m(s, _);
insert(s, g, _);
},
p(s, [r]) {
if (1 & r) set_data(o, s[0]);
if (_ === (_ = select_block_type(s)) && m) m.p(s, r); else {
m.d(1);
m = _(s);
if (m) {
m.c();
m.m(g.parentNode, g);
}
}
},
i: noop,
o: noop,
d(s) {
if (s) {
detach(r);
detach(u);
detach(g);
}
m.d(s);
}
};
}
function revStringToRevNumber(s) {
if (!s) return ""; else return s.split("-")[0];
}
function instance(s, r, o) {
let u, g, _, m, b, E, {docs: w = []} = r, {callback: S = (async (s, r) => {
Promise.resolve();
})} = r, {filename: L = ""} = r, {nameA: O = "A"} = r, {nameB: D = "B"} = r, {defaultSelect: k = ""} = r, C = "", T = "", I = {}, A = {}, R = {}, x = {}, P = k;
function docToString(s) {
return "plain" == s.datatype ? getDocData(s.data) : readString(new Uint8Array(decodeBinary(s.data)));
}
s.$$set = s => {
if ("docs" in s) o(13, w = s.docs);
if ("callback" in s) o(14, S = s.callback);
if ("filename" in s) o(0, L = s.filename);
if ("nameA" in s) o(1, O = s.nameA);
if ("nameB" in s) o(2, D = s.nameB);
if ("defaultSelect" in s) o(15, k = s.defaultSelect);
};
s.$$.update = () => {
if (991352 & s.$$.dirty) if (w && w.length >= 1) {
if (w[0].mtime < w[1].mtime) {
o(3, m = w[0]);
o(4, b = w[1]);
} else {
o(3, m = w[1]);
o(4, b = w[0]);
}
o(5, C = docToString(m));
o(6, T = docToString(b));
try {
o(16, I = false);
o(17, A = false);
o(16, I = JSON.parse(C));
o(17, A = JSON.parse(T));
o(18, R = mergeObject(I, A));
o(19, x = mergeObject(A, I));
if (JSON.stringify(R) == JSON.stringify(x)) o(19, x = false);
} catch (s) {
o(19, x = false);
o(18, R = false);
}
}
if (983040 & s.$$.dirty) o(9, u = {
"": false,
A: I,
B: A,
AB: R,
BA: x
});
if (640 & s.$$.dirty) o(8, g = P in u ? u[P] : {});
if (65792 & s.$$.dirty) o(10, E = function getJsonDiff(s, r) {
return function getDiff(s, r) {
const o = new import_diff_match_patch.diff_match_patch, u = o.diff_linesToChars_(s, r), g = o.diff_main(u.chars1, u.chars2, false);
o.diff_charsToLines_(g, u.lineArray);
return g;
}(JSON.stringify(s, null, 2), JSON.stringify(r, null, 2));
}(I, g));
if (6 & s.$$.dirty) o(11, _ = [ [ "", "Not now" ], [ "A", O || "A" ], [ "B", D || "B" ], [ "AB", `${O || "A"} + ${D || "B"}` ], [ "BA", `${D || "B"} + ${O || "A"}` ] ]);
};
return [ L, O, D, m, b, C, T, P, g, u, E, _, function apply() {
if (m._id == b._id) {
if ("A" == P) return S(m._rev, void 0);
if ("B" == P) return S(b._rev, void 0);
} else {
if ("A" == P) return S(void 0, docToString(m));
if ("B" == P) return S(void 0, docToString(b));
}
if ("BA" == P) return S(void 0, JSON.stringify(x, null, 2));
if ("AB" == P) return S(void 0, JSON.stringify(R, null, 2));
S(void 0, void 0);
}, w, S, k, I, A, R, x, function input_change_handler() {
P = this.__value;
o(7, P);
}, [ [] ] ];
}
var context, JsonResolvePane = class extends SvelteComponent {
constructor(s) {
super();
init2(this, s, 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(s, r, o, u, g, _, m) {
super(s);
this.callback = u;
this.filename = r;
this.docs = o;
this.nameA = g;
this.nameB = _;
this.defaultSelect = m;
waitForSignal(`cancel-internal-conflict:${r}`).then((() => this.close()));
}
async UICallback(s, r) {
this.close();
await this.callback(s, r);
this.callback = null;
}
onOpen() {
const {contentEl: s} = this;
this.titleEl.setText("Conflicted Setting");
s.empty();
if (null == this.component) this.component = new JsonResolvePane_default({
target: s,
props: {
docs: this.docs,
filename: this.filename,
nameA: this.nameA,
nameB: this.nameB,
defaultSelect: this.defaultSelect,
callback: (s, r) => this.UICallback(s, r)
}
});
}
onClose() {
const {contentEl: s} = this;
s.empty();
if (null != this.callback) this.callback(null);
if (null != this.component) {
this.component.$destroy();
this.component = null;
}
}
};
function reactiveSource(s) {
return _reactive({
initialValue: s
});
}
function reactive(s, r) {
return _reactive({
expression: s,
initialValue: r
});
}
function _reactive({expression: s, initialValue: r}) {
let o, u = false;
const g = new Set, _ = {
depends: new Set,
evalCount: 0,
readCount: 0,
markDirty() {
u = true;
_.markDependedDirty();
g.forEach((s => s(_)));
},
markClean() {
u = false;
},
markDependedDirty() {
_.depends.forEach((s => s.markDirty()));
},
get value() {
if (context) _.depends.add(context);
if (!s) return o;
if (u) {
const r = o, u = s();
if (isObjectDifferent(r, u)) {
o = u;
_.markClean();
_.markDependedDirty();
}
}
return o;
},
set value(s) {
if (isObjectDifferent(o, s)) {
o = s;
_.markDirty();
}
},
onChanged(s) {
g.add(s);
},
offChanged(s) {
g.delete(s);
}
};
o = function initialize() {
const o = context;
context = _;
const u = s ? s(r) : r;
context = o;
return u;
}();
return _;
}
var lockStats = reactiveSource({
pending: [],
running: [],
count: 0
}), collectingChunks = reactiveSource(0), pluginScanningCount = reactiveSource(0), hiddenFilesProcessingCount = reactiveSource(0), hiddenFilesEventCount = reactiveSource(0), logStore = new QueueProcessor((s => s), {
batchSize: 1,
suspended: false,
keepResultUntilDownstreamConnected: true
}), logMessages = reactiveSource([]), d = "", d2 = "\n";
function serialize(s) {
var r, o, u, g, _;
let m = "";
m += ":";
m += s.category + d + s.name + d + s.term + d2;
m += (null != (r = s.version) ? r : "") + d2;
m += s.mtime + d2;
for (const r of s.files) {
m += r.filename + d + (null != (o = r.displayName) ? o : "") + d + (null != (u = r.version) ? u : "") + d2;
const s = digestHash((null != (g = r.data) ? g : []).join());
m += r.mtime + d + r.size + d + s + d2;
for (const s of null != (_ = r.data) ? _ : []) m += s + d;
m += d2;
}
return m;
}
function fetchToken(s, r) {
const o = s.indexOf(d2, r), u = -1 == o ? s.length : o, g = s.indexOf(d, r), _ = -1 == g ? s.length : g, m = Math.min(u, _);
let b = m;
if (u < _) b = m; else b = m + 1;
return [ b, s.substring(r, m) ];
}
function getTokenizer(s) {
return {
pos: 1,
next() {
const [r, o] = fetchToken(s, this.pos);
this.pos = r;
return o;
},
nextLine() {
const r = s.indexOf(d2, this.pos);
if (-1 == r) this.pos = s.length; else this.pos = r + 1;
}
};
}
function deserialize2(s) {
const r = getTokenizer(s), o = r.next(), u = r.next(), g = r.next();
r.nextLine();
const _ = r.next();
r.nextLine();
const m = Number(r.next());
r.nextLine();
const b = Object.assign({}, {
category: o,
name: u,
term: g,
version: _,
mtime: m,
files: []
});
let E = "";
do {
E = r.next();
if (!E) break;
const s = r.next(), o = r.next();
r.nextLine();
const u = Number(r.next()), g = Number(r.next()), _ = r.next();
r.nextLine();
const m = [];
let w = "";
do {
w = r.next();
if ("" == w) break;
m.push(w);
} while ("" != w);
b.files.push({
filename: E,
displayName: s,
version: o,
mtime: u,
size: g,
data: m,
hash: _
});
r.nextLine();
} while (E);
return b;
}
function deserialize(s, r) {
try {
if (":" == s[0]) return deserialize2(s); else return JSON.parse(s);
} catch (o) {
try {
return (0, import_obsidian.parseYaml)(s);
} catch (s) {
return r;
}
}
}
var pluginList = writable([]), pluginIsEnumerating = writable(false), ConfigSync = class extends LiveSyncCommands {
constructor(s) {
super(s);
this.pluginDialog = void 0;
this.periodicPluginSweepProcessor = new PeriodicProcessor(this.plugin, (async () => await this.scanAllConfigFiles(false)));
this.pluginList = [];
this.pluginScanProcessor = new QueueProcessor((async s => {
const r = s[0], o = r.path || this.getPath(r), u = this.pluginList.find((s => s.documentPath == o));
if (u && u.mtime == r.mtime) return [];
try {
const s = await this.loadPluginData(o);
if (s) {
let r = [ ...this.pluginList ];
r = r.filter((r => r.documentPath != s.documentPath));
r.push(s);
this.pluginList = r;
pluginList.set(r);
}
return [];
} catch (s) {
Logger(`Something happened at enumerating customization :${o}`, LOG_LEVEL_NOTICE);
Logger(s, LOG_LEVEL_VERBOSE);
}
return [];
}), {
suspended: false,
batchSize: 1,
concurrentLimit: 10,
delay: 100,
yieldThreshold: 10,
maintainDelay: false,
totalRemainingReactiveSource: pluginScanningCount
}).startPipeline().root.onIdle((() => {
this.createMissingConfigurationEntry();
}));
this.recentProcessedInternalFiles = [];
pluginScanningCount.onChanged((s => {
const r = s.value;
pluginIsEnumerating.set(0 != r);
}));
}
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 s;
this.hidePluginSyncModal();
null == (s = this.periodicPluginSweepProcessor) || s.disable();
}
onload() {
this.plugin.addCommand({
id: "livesync-plugin-dialog-ex",
name: "Show customization sync dialog",
callback: () => {
this.showPluginSyncModal();
}
});
}
getFileCategory(s) {
if (2 == s.split("/").length && s.endsWith(".json")) return "CONFIG";
if (4 == s.split("/").length && s.startsWith(`${this.app.vault.configDir}/themes/`)) return "THEME";
if (s.startsWith(`${this.app.vault.configDir}/snippets/`) && s.endsWith(".css")) return "SNIPPET";
if (s.startsWith(`${this.app.vault.configDir}/plugins/`)) if (s.endsWith("/styles.css") || s.endsWith("/manifest.json") || s.endsWith("/main.js")) return "PLUGIN_MAIN"; else if (s.endsWith("/data.json")) return "PLUGIN_DATA"; else return "";
return "";
}
isTargetPath(s) {
if (!s.startsWith(this.app.vault.configDir)) return false; else return "" != this.getFileCategory(s);
}
async onInitializeDatabase(s) {
if (this.settings.usePluginSync) try {
Logger("Scanning customizations...");
await this.scanAllConfigFiles(s);
Logger("Scanning customizations : done");
} catch (s) {
Logger("Scanning customizations : failed");
Logger(s, LOG_LEVEL_VERBOSE);
}
}
async beforeReplicate(s) {
if (this.settings.autoSweepPlugins && this.settings.usePluginSync) await this.scanAllConfigFiles(s);
}
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(s) {
this.pluginList = [];
pluginList.set(this.pluginList);
await this.updatePluginList(s);
}
async loadPluginData(s) {
const r = await this.localDatabase.getDBEntry(s, void 0, false, false);
if (r) {
const o = deserialize(getDocData(r.data), {}), u = [];
let g = false;
for (const s of o.files) {
const r = {
...s,
data: []
};
if (!s.hash) {
const o = digestHash(getDocData(r.data));
s.hash = o;
g = true;
}
r.data = [ s.hash ];
u.push(r);
}
if (g) {
Logger(`Digest created for ${s} to improve checking`, LOG_LEVEL_VERBOSE);
r.data = serialize(o);
fireAndForget((() => this.localDatabase.putDBEntry(createSavingEntryFromLoadedEntry(r))));
}
return {
...o,
documentPath: this.getPath(r),
files: u
};
}
return false;
}
createMissingConfigurationEntry() {
let s = false;
for (const r of this.pluginList) {
const o = `${r.category}/${r.name}`;
if (!(o in this.plugin.settings.pluginSyncExtendedSetting)) this.plugin.settings.pluginSyncExtendedSetting[o] = {
key: o,
mode: MODE_SELECTIVE,
files: []
};
if (this.plugin.settings.pluginSyncExtendedSetting[o].files.sort().join(",").toLowerCase() != r.files.map((s => s.filename)).sort().join(",").toLowerCase()) {
this.plugin.settings.pluginSyncExtendedSetting[o].files = r.files.map((s => s.filename)).sort();
s = true;
}
}
if (s) this.plugin.saveSettingData();
}
async updatePluginList(s, r) {
if (this.settings.usePluginSync) {
try {
const s = r ? await this.path2id(r) : "", o = r ? this.localDatabase.findEntries(s, s + "", {
include_docs: true,
key: s,
limit: 1
}) : this.localDatabase.findEntries(ICXHeader + "", `${ICXHeader}`, {
include_docs: true
});
for await (const s of o) {
const o = s.path || this.getPath(s);
if (!r || r == o) this.pluginScanProcessor.enqueue(s);
}
} finally {
pluginIsEnumerating.set(false);
}
pluginIsEnumerating.set(false);
} else {
this.pluginScanProcessor.clearQueue();
this.pluginList = [];
pluginList.set(this.pluginList);
}
}
async compareUsingDisplayData(s, r) {
const o = await this.localDatabase.getDBEntry(s.documentPath), u = await this.localDatabase.getDBEntry(r.documentPath);
if (o && u) {
const g = deserialize(getDocData(o.data), {});
g.documentPath = s.documentPath;
const _ = deserialize(getDocData(u.data), {});
_.documentPath = r.documentPath;
return await this.showJSONMergeDialogAndMerge(o, u, g, _);
}
return false;
}
showJSONMergeDialogAndMerge(s, r, o, u) {
const g = {
...o.files[0],
ctime: o.files[0].mtime,
_id: `${o.documentPath}`
}, _ = u.files[0], m = {
...s,
...g,
datatype: "newnote"
}, b = {
...r,
..._,
datatype: "newnote"
};
return serialized("config:merge-data", (() => new Promise((s => {
Logger("Opening data-merging dialog", LOG_LEVEL_VERBOSE);
const r = stripAllPrefixes(m.path.split("/").slice(-1).join("/"));
new JsonResolveModal(this.app, r, [ m, b ], (async (r, u) => {
if (null == u) return s(false);
try {
s(await this.applyData(o, u));
} catch (r) {
Logger("Could not apply merged file");
Logger(r, LOG_LEVEL_VERBOSE);
s(false);
}
}), "📡", "🛰️", "B").open();
}))));
}
async applyData(s, r) {
Logger(`Applying ${s.displayName || s.name}..`);
const o = this.app.vault.configDir;
try {
if (!s.documentPath) throw "InternalError: Document path not exist";
const u = await this.localDatabase.getDBEntry(s.documentPath);
if (false == u) throw "Not found on database";
const g = deserialize(getDocData(u.data), {});
for (const u of g.files) {
Logger(`Applying ${u.filename} of ${s.displayName || s.name}..`);
try {
const g = `${o}/${u.filename}`;
await this.vaultAccess.ensureDirectory(g);
if (!r) {
const s = decodeBinary(u.data);
await this.vaultAccess.adapterWrite(g, s);
} else await this.vaultAccess.adapterWrite(g, r);
Logger(`Applying ${u.filename} of ${s.displayName || s.name}.. Done`);
} catch (r) {
Logger(`Applying ${u.filename} of ${s.displayName || s.name}.. Failed`);
Logger(r, LOG_LEVEL_VERBOSE);
}
}
const _ = `${o}/${g.files[0].filename}`;
await this.storeCustomizationFiles(_);
await this.updatePluginList(true, _);
await delay(100);
Logger(`Config ${s.displayName || s.name} has been applied`, LOG_LEVEL_NOTICE);
if ("PLUGIN_DATA" == s.category || "PLUGIN_MAIN" == s.category) {
const r = Object.values(this.app.plugins.manifests), u = this.app.plugins.enabledPlugins, g = r.find((r => u.has(r.id) && r.dir == `${o}/plugins/${s.name}`));
if (g) {
Logger(`Unloading plugin: ${g.name}`, LOG_LEVEL_NOTICE, "plugin-reload-" + g.id);
await this.app.plugins.unloadPlugin(g.id);
await this.app.plugins.loadPlugin(g.id);
Logger(`Plugin reloaded: ${g.name}`, LOG_LEVEL_NOTICE, "plugin-reload-" + g.id);
}
} else if ("CONFIG" == s.category) scheduleTask("configReload", 250, (async () => {
if ("yes" == await askYesNo(this.app, "Do you want to restart and reload Obsidian now?")) this.app.commands.executeCommandById("app:reload");
}));
return true;
} catch (r) {
Logger(`Applying ${s.displayName || s.name}.. Failed`);
Logger(r, LOG_LEVEL_VERBOSE);
return false;
}
}
async deleteData(s) {
try {
if (s.documentPath) {
await this.deleteConfigOnDatabase(s.documentPath);
await this.updatePluginList(false, s.documentPath);
Logger(`Delete: ${s.documentPath}`, LOG_LEVEL_NOTICE);
}
return true;
} catch (r) {
Logger(`Failed to delete: ${s.documentPath}`, LOG_LEVEL_NOTICE);
return false;
}
}
async parseReplicationResultItem(s) {
if (s._id.startsWith(ICXHeader)) {
if (this.plugin.settings.usePluginSync) await this.updatePluginList(false, s.path ? s.path : this.getPath(s));
if (this.plugin.settings.usePluginSync && this.plugin.settings.notifyPluginOrSettingUpdated) if (!this.pluginDialog || this.pluginDialog && !this.pluginDialog.isOpened()) {
const s = createFragment((s => {
s.createEl("span", void 0, (s => {
s.appendText("Some configuration has been arrived, Press ");
s.appendChild(s.createEl("a", void 0, (s => {
s.text = "HERE";
s.addEventListener("click", (() => {
this.showPluginSyncModal();
}));
})));
s.appendText(" to open the config sync dialog , or press elsewhere to dismiss this message.");
}));
})), r = "popupUpdated-plugins";
scheduleTask(r, 1e3, (async () => {
var o;
const u = await memoIfNotExist(r, (() => new import_obsidian.Notice(s, 0)));
if (!(null == (o = null == u ? void 0 : u.noticeEl) ? void 0 : o.isShown())) memoObject(r, new import_obsidian.Notice(s, 0));
scheduleTask(r + "-close", 2e4, (() => {
var s;
const o = retrieveMemoObject(r);
if (o) {
if (null == (s = null == o ? void 0 : o.noticeEl) ? void 0 : s.isShown()) o.hide();
disposeMemoObject(r);
}
}));
}));
}
return true;
}
return false;
}
async realizeSettingSyncMode() {
var s;
null == (s = this.periodicPluginSweepProcessor) || s.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(s) {
const r = await this.vaultAccess.adapterStat(s);
let o, u;
if (!r) return false;
const g = await this.vaultAccess.adapterReadBinary(s);
let _;
try {
_ = await arrayBufferToBase64(g);
if (s.toLowerCase().endsWith("/manifest.json")) {
const r = readString(new Uint8Array(g));
try {
const s = JSON.parse(r);
if ("version" in s) o = `${s.version}`;
if ("name" in s) u = `${s.name}`;
} catch (r) {
Logger(`Configuration sync data: ${s} looks like manifest, but could not read the version`, LOG_LEVEL_INFO);
}
}
} catch (r) {
Logger(`The file ${s} could not be encoded`);
Logger(r, LOG_LEVEL_VERBOSE);
return false;
}
const m = r.mtime;
return {
filename: s.substring(this.app.vault.configDir.length + 1),
data: _,
mtime: m,
size: r.size,
version: o,
displayName: u
};
}
filenameToUnifiedKey(s, r) {
const o = r || this.plugin.deviceAndVaultName, u = this.getFileCategory(s), g = "CONFIG" == u || "SNIPPET" == u ? s.split("/").slice(-1)[0] : "PLUGIN_ETC" == u ? s.split("/").slice(-2).join("/") : s.split("/").slice(-2)[0];
return `${ICXHeader}${o}/${u}/${g}.md`;
}
async storeCustomizationFiles(s, r) {
const o = r || this.plugin.deviceAndVaultName;
if ("" == o) {
Logger("We have to configure the device name", LOG_LEVEL_NOTICE);
return;
}
const u = this.filenameToUnifiedKey(s, o);
return await serialized(`plugin-${u}`, (async () => {
const r = this.getFileCategory(s);
let u = 0, g = [];
const _ = "CONFIG" == r || "SNIPPET" == r ? s.split("/").reverse()[0] : s.split("/").reverse()[1], m = s.split("/").slice(0, -1).join("/"), b = this.filenameToUnifiedKey(s, o), E = await this.path2id(b), w = {
category: r,
files: [],
name: _,
mtime: 0,
term: o
};
if ("CONFIG" == r || "SNIPPET" == r || "PLUGIN_ETC" == r || "PLUGIN_DATA" == r) {
g = [ s ];
if ("PLUGIN_ETC" == r) w.displayName = s.split("/").slice(-1).join("/");
} else if ("PLUGIN_MAIN" == r) g = [ "manifest.json", "main.js", "styles.css" ].map((s => `${m}/${s}`)); else if ("THEME" == r) g = [ "manifest.json", "theme.css" ].map((s => `${m}/${s}`));
for (const s of g) {
const r = await this.makeEntryFromFile(s);
if (false != r) {
if (r.version) w.version = r.version;
if (r.displayName) w.displayName = r.displayName;
u = 0 == u ? r.mtime : (r.mtime + u) / 2;
w.files.push(r);
}
}
w.mtime = u;
if (0 == w.files.length) {
Logger(`Nothing left: deleting.. ${s}`);
await this.deleteConfigOnDatabase(b);
await this.updatePluginList(false, b);
return;
}
const S = createTextBlob(serialize(w));
try {
const s = await this.localDatabase.getDBEntryMeta(b, void 0, false);
let r;
if (false === s) r = {
_id: E,
path: b,
data: S,
mtime: u,
ctime: u,
datatype: "newnote",
size: S.size,
children: [],
deleted: false,
type: "newnote"
}; else {
if (s.mtime == u) return true;
const o = await this.localDatabase.getDBEntryFromMeta(s, {}, false, false);
if (o) {
const s = (await deserialize(getDocData(o.data), {})).files.map((s => ({
prev: s,
curr: w.files.find((r => r.filename == s.filename))
}))).map((async s => {
var r, o;
try {
return await isDocContentSame(null != (o = null == (r = s.curr) ? void 0 : r.data) ? o : [], s.prev.data);
} catch (s) {
return false;
}
}));
if ((await Promise.all(s)).every((s => true == s))) {
Logger(`STORAGE --\x3e DB:${b}: (config) Skipped (Same content)`, LOG_LEVEL_VERBOSE);
return true;
}
}
r = {
...s,
data: S,
mtime: u,
size: S.size,
datatype: "newnote",
children: [],
deleted: false,
type: "newnote"
};
}
const o = await this.localDatabase.putDBEntry(r);
await this.updatePluginList(false, r.path);
Logger(`STORAGE --\x3e DB:${b}: (config) Done`);
return o;
} catch (s) {
Logger(`STORAGE --\x3e DB:${b}: (config) Failed`);
Logger(s, LOG_LEVEL_VERBOSE);
return false;
}
}));
}
async watchVaultRawEventsAsync(s) {
if (!this.settings.usePluginSync) return false;
if (!this.isTargetPath(s)) return false;
const r = await this.vaultAccess.adapterStat(s);
if (r && "file" != r.type) return false;
const o = normalizePath(this.app.vault.configDir);
if (Object.values(this.settings.pluginSyncExtendedSetting).filter((s => s.mode != MODE_SELECTIVE)).map((s => s.files)).flat().map((s => `${o}/${s}`.toLowerCase())).some((r => r.startsWith(s.toLowerCase())))) {
Logger(`Customization file skipped: ${s}`, LOG_LEVEL_VERBOSE);
return;
}
const u = ~~((r && r.mtime || 0) / 1e3), g = `${s}-${u}`;
if (this.recentProcessedInternalFiles.contains(g)) return true;
this.recentProcessedInternalFiles = [ g, ...this.recentProcessedInternalFiles ].slice(0, 100);
this.storeCustomizationFiles(s).then((() => {}));
}
async scanAllConfigFiles(s) {
var r;
Logger("Scanning customizing files.", s ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO, "scan-all-config");
const o = this.plugin.deviceAndVaultName;
if ("" == o) {
Logger("We have to configure the device name", LOG_LEVEL_NOTICE);
return;
}
const u = (await this.scanInternalFiles()).filter((s => this.isTargetPath(s))).map((s => ({
key: this.filenameToUnifiedKey(s),
file: s
}))), g = [ ...new Set(u.map((s => s.key))) ];
let _ = (await this.localDatabase.allDocsRaw({
startkey: ICXHeader + "",
endkey: `${ICXHeader}`,
include_docs: true
})).rows.map((s => s.doc)).filter((s => !s.deleted)).map((s => this.getPath(s))).filter((s => s.startsWith(`${ICXHeader}${o}/`)));
for (const s of g) {
const o = null == (r = u.find((r => r.key == s))) ? void 0 : r.file;
if (o) {
await this.storeCustomizationFiles(o);
_ = _.filter((r => r != s));
} else Logger(`scanAllConfigFiles - File not found: ${s}`, LOG_LEVEL_VERBOSE);
}
for (const s of _) await this.deleteConfigOnDatabase(s);
this.updatePluginList(false).then();
}
async deleteConfigOnDatabase(s, r = false) {
const o = (new Date).getTime();
await serialized("file-x-" + s, (async () => {
try {
const r = await this.localDatabase.getDBEntryMeta(s, void 0, false);
let u;
if (false === r) {
Logger(`STORAGE -x> DB:${s}: (config) already deleted (Not found on database)`);
return;
} else {
if (r.deleted) {
Logger(`STORAGE -x> DB:${s}: (config) already deleted`);
return;
}
u = {
...r,
mtime: o,
size: 0,
children: [],
deleted: true,
type: "newnote"
};
}
await this.localDatabase.putRaw(u);
await this.updatePluginList(false, s);
Logger(`STORAGE -x> DB:${s}: (config) Done`);
} catch (r) {
Logger(`STORAGE -x> DB:${s}: (config) Failed`);
Logger(r, LOG_LEVEL_VERBOSE);
return false;
}
}));
}
async scanInternalFiles() {
return (await this.getFiles(this.app.vault.configDir, 2)).filter((s => s.startsWith("."))).filter((s => !s.startsWith(".trash")));
}
async getFiles(s, r) {
if (-1 == r) return [];
let o;
try {
o = await this.app.vault.adapter.list(s);
} catch (r) {
Logger(`Could not traverse(ConfigSync):${s}`, LOG_LEVEL_INFO);
Logger(r, LOG_LEVEL_VERBOSE);
return [];
}
let u = [ ...o.files ];
for (const s of o.folders) u = u.concat(await this.getFiles(s, r - 1));
return u;
}
};
function add_css2(s) {
append_styles(s, "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(s, r, o) {
const u = s.slice();
u[30] = r[o];
return u;
}
function create_else_block_3(s) {
let r, o, u, g, _, m, b;
return {
c() {
r = element("span");
o = space();
u = element("span");
u.textContent = "All the same or non-existent";
g = space();
_ = element("button");
m = space();
b = element("button");
attr(r, "class", "spacer svelte-tsbdtg");
attr(u, "class", "message even svelte-tsbdtg");
_.disabled = true;
attr(_, "class", "svelte-tsbdtg");
b.disabled = true;
attr(b, "class", "svelte-tsbdtg");
},
m(s, E) {
insert(s, r, E);
insert(s, o, E);
insert(s, u, E);
insert(s, g, E);
insert(s, _, E);
insert(s, m, E);
insert(s, b, E);
},
p: noop,
d(s) {
if (s) {
detach(r);
detach(o);
detach(u);
detach(g);
detach(_);
detach(m);
detach(b);
}
}
};
}
function create_if_block2(s) {
let r, o, u, g = !s[0] && create_if_block_12(s);
return {
c() {
r = element("span");
o = space();
if (g) g.c();
u = empty();
attr(r, "class", "spacer svelte-tsbdtg");
},
m(s, _) {
insert(s, r, _);
insert(s, o, _);
if (g) g.m(s, _);
insert(s, u, _);
},
p(s, r) {
if (!s[0]) if (g) g.p(s, r); else {
g = create_if_block_12(s);
g.c();
g.m(u.parentNode, u);
} else if (g) {
g.d(1);
g = null;
}
},
d(s) {
if (s) {
detach(r);
detach(o);
detach(u);
}
if (g) g.d(s);
}
};
}
function create_if_block_12(s) {
let r, o, u, g, _, m, b, E, w, S, L, O, D, k, C, T, I, A, R = ensure_array_like(s[8]), x = [];
for (let r = 0; r < R.length; r += 1) x[r] = create_each_block2(get_each_context2(s, R, r));
function select_block_type_1(s, r) {
if (s[6] || s[1] && "" != s[2]) return create_if_block_42; else return create_else_block_2;
}
let P = select_block_type_1(s), N = P(s), B = s[1] && create_if_block_22(s);
return {
c() {
r = element("span");
o = element("span");
u = text(s[3]);
g = space();
_ = element("span");
m = text(s[4]);
b = space();
E = element("span");
w = text(s[5]);
S = space();
L = element("select");
O = element("option");
O.textContent = "-";
for (let s = 0; s < x.length; s += 1) x[s].c();
k = space();
N.c();
C = space();
if (B) B.c();
T = empty();
attr(o, "class", "message svelte-tsbdtg");
attr(_, "class", "message svelte-tsbdtg");
attr(E, "class", "message svelte-tsbdtg");
attr(r, "class", "messages svelte-tsbdtg");
O.__value = D = "";
set_input_value(O, O.__value);
if (void 0 === s[2]) add_render_callback((() => s[24].call(L)));
},
m(D, R) {
insert(D, r, R);
append(r, o);
append(o, u);
append(r, g);
append(r, _);
append(_, m);
append(r, b);
append(r, E);
append(E, w);
insert(D, S, R);
insert(D, L, R);
append(L, O);
for (let s = 0; s < x.length; s += 1) if (x[s]) x[s].m(L, null);
select_option(L, s[2], true);
insert(D, k, R);
N.m(D, R);
insert(D, C, R);
if (B) B.m(D, R);
insert(D, T, R);
if (!I) {
A = listen(L, "change", s[24]);
I = true;
}
},
p(s, r) {
if (8 & r[0]) set_data(u, s[3]);
if (16 & r[0]) set_data(m, s[4]);
if (32 & r[0]) set_data(w, s[5]);
if (256 & r[0]) {
R = ensure_array_like(s[8]);
let o;
for (o = 0; o < R.length; o += 1) {
const u = get_each_context2(s, R, o);
if (x[o]) x[o].p(u, r); else {
x[o] = create_each_block2(u);
x[o].c();
x[o].m(L, null);
}
}
for (;o < x.length; o += 1) x[o].d(1);
x.length = R.length;
}
if (260 & r[0]) select_option(L, s[2]);
if (P === (P = select_block_type_1(s)) && N) N.p(s, r); else {
N.d(1);
N = P(s);
if (N) {
N.c();
N.m(C.parentNode, C);
}
}
if (s[1]) if (B) B.p(s, r); else {
B = create_if_block_22(s);
B.c();
B.m(T.parentNode, T);
} else if (B) {
B.d(1);
B = null;
}
},
d(s) {
if (s) {
detach(r);
detach(S);
detach(L);
detach(k);
detach(C);
detach(T);
}
destroy_each(x, s);
N.d(s);
if (B) B.d(s);
I = false;
A();
}
};
}
function create_each_block2(s) {
let r, o, u, g = s[30] + "";
return {
c() {
r = element("option");
o = text(g);
r.__value = u = s[30];
set_input_value(r, r.__value);
},
m(s, u) {
insert(s, r, u);
append(r, o);
},
p(s, _) {
if (256 & _[0] && g !== (g = s[30] + "")) set_data(o, g);
if (256 & _[0] && u !== (u = s[30])) {
r.__value = u;
set_input_value(r, r.__value);
}
},
d(s) {
if (s) detach(r);
}
};
}
function create_else_block_2(s) {
let r, o, u;
return {
c() {
r = element("button");
o = space();
u = element("button");
r.disabled = true;
attr(r, "class", "svelte-tsbdtg");
u.disabled = true;
attr(u, "class", "svelte-tsbdtg");
},
m(s, g) {
insert(s, r, g);
insert(s, o, g);
insert(s, u, g);
},
p: noop,
d(s) {
if (s) {
detach(r);
detach(o);
detach(u);
}
}
};
}
function create_if_block_42(s) {
let r, o, u, g;
function select_block_type_2(s, r) {
if (s[7]) return create_if_block_5; else return create_else_block_12;
}
let _ = select_block_type_2(s), m = _(s);
return {
c() {
m.c();
r = space();
o = element("button");
o.textContent = "✓";
attr(o, "class", "svelte-tsbdtg");
},
m(_, b) {
m.m(_, b);
insert(_, r, b);
insert(_, o, b);
if (!u) {
g = listen(o, "click", s[9]);
u = true;
}
},
p(s, o) {
if (_ === (_ = select_block_type_2(s)) && m) m.p(s, o); else {
m.d(1);
m = _(s);
if (m) {
m.c();
m.m(r.parentNode, r);
}
}
},
d(s) {
if (s) {
detach(r);
detach(o);
}
m.d(s);
u = false;
g();
}
};
}
function create_else_block_12(s) {
let r;
return {
c() {
r = element("button");
r.disabled = true;
attr(r, "class", "svelte-tsbdtg");
},
m(s, o) {
insert(s, r, o);
},
p: noop,
d(s) {
if (s) detach(r);
}
};
}
function create_if_block_5(s) {
let r, o, u;
return {
c() {
r = element("button");
r.textContent = "🔍";
attr(r, "class", "svelte-tsbdtg");
},
m(g, _) {
insert(g, r, _);
if (!o) {
u = listen(r, "click", s[10]);
o = true;
}
},
p: noop,
d(s) {
if (s) detach(r);
o = false;
u();
}
};
}
function create_if_block_22(s) {
let r;
function select_block_type_3(s, r) {
if ("" != s[2]) return create_if_block_32; else return create_else_block2;
}
let o = select_block_type_3(s), u = o(s);
return {
c() {
u.c();
r = empty();
},
m(s, o) {
u.m(s, o);
insert(s, r, o);
},
p(s, g) {
if (o === (o = select_block_type_3(s)) && u) u.p(s, g); else {
u.d(1);
u = o(s);
if (u) {
u.c();
u.m(r.parentNode, r);
}
}
},
d(s) {
if (s) detach(r);
u.d(s);
}
};
}
function create_else_block2(s) {
let r, o, u;
return {
c() {
r = element("button");
r.textContent = "📑";
attr(r, "class", "svelte-tsbdtg");
},
m(g, _) {
insert(g, r, _);
if (!o) {
u = listen(r, "click", s[12]);
o = true;
}
},
p: noop,
d(s) {
if (s) detach(r);
o = false;
u();
}
};
}
function create_if_block_32(s) {
let r, o, u;
return {
c() {
r = element("button");
r.textContent = "🗑️";
attr(r, "class", "svelte-tsbdtg");
},
m(g, _) {
insert(g, r, _);
if (!o) {
u = listen(r, "click", s[11]);
o = true;
}
},
p: noop,
d(s) {
if (s) detach(r);
o = false;
u();
}
};
}
function create_fragment2(s) {
let r;
function select_block_type(s, r) {
if (s[8].length > 0) return create_if_block2; else return create_else_block_3;
}
let o = select_block_type(s), u = o(s);
return {
c() {
u.c();
r = empty();
},
m(s, o) {
u.m(s, o);
insert(s, r, o);
},
p(s, g) {
if (o === (o = select_block_type(s)) && u) u.p(s, g); else {
u.d(1);
u = o(s);
if (u) {
u.c();
u.m(r.parentNode, r);
}
}
},
i: noop,
o: noop,
d(s) {
if (s) detach(r);
u.d(s);
}
};
}
function instance2(s, r, o) {
let {list: u = []} = r, {thisTerm: g = ""} = r, {hideNotApplicable: _ = false} = r, {selectNewest: m = 0} = r, {applyAllPluse: b = 0} = r, {applyData: E} = r, {compareData: w} = r, {deleteData: S} = r, {hidden: L} = r, {plugin: O} = r, {isMaintenanceMode: D = false} = r;
const k = O.addOnConfigSync;
let C = "", T = "", I = "", A = "", R = false, x = false, P = 0, N = 0, B = [];
async function comparePlugin(s, r) {
var o, u;
let g = "", _ = "", m = false, b = false;
if (!s && !r) g = ""; else if (s && !r) g = "⚠ Local only"; else if (r && !s) {
g = "✓ Remote only";
b = true;
} else {
const _ = (null !== (o = null == s ? void 0 : s.mtime) && void 0 !== o ? o : 0) - (null !== (u = null == r ? void 0 : r.mtime) && void 0 !== u ? u : 0);
if (_ / 1e3 < -10) {
g = "✓ Newer";
b = true;
m = true;
} else if (_ / 1e3 > 10) {
g = "⚠ Older";
b = true;
m = true;
} else {
g = "⚖️ Same old";
b = false;
m = true;
}
}
const E = (null == s ? void 0 : s.version) || "0.0.0", w = (null == r ? void 0 : r.version) || "0.0.0";
if ((null == s ? void 0 : s.version) || (null == r ? void 0 : r.version)) {
const s = versionNumberString2Number(E), r = versionNumberString2Number(w);
if (s == r) _ = "⚖️ Same ver."; else if (s > r) _ = `⚠ Lower ${E} > ${w}`; else if (s < r) _ = `✓ Higher ${E} < ${w}`;
}
if (m) {
const {canApply: o, equivalency: u, canCompare: m} = await async function checkEquivalency(s, r) {
let o = "", u = false, g = false;
const _ = [ ...new Set([ ...s.files.map((s => s.filename)), ...r.files.map((s => s.filename)) ]) ].map((o => {
const u = s.files.find((s => s.filename == o)), g = r.files.find((s => s.filename == o));
if (!u && !g) return 0; else if (u && !g) return 2; else if (!u && g) return 8; else if (getDocData(u.data) == getDocData(g.data)) return 4; else return 16;
})).reduce(((s, r) => s | r), 0);
if (4 == _) {
o = "⚖️ Same";
u = false;
} else if (_ <= 4) {
o = "Same or local only";
u = false;
} else if (16 == _) {
u = true;
g = true;
o = "≠ Different";
} else {
u = true;
g = true;
o = "≠ Different";
}
return {
equivalency: o,
canApply: u,
canCompare: g
};
}(s, r);
return {
canApply: o,
freshness: g,
equivalency: u,
version: _,
canCompare: m
};
}
return {
canApply: b,
freshness: g,
equivalency: "",
version: _,
canCompare: false
};
}
async function applySelected() {
const s = u.find((s => s.term == g)), r = u.find((s => s.term == C));
if (r && await E(r)) k.updatePluginList(true, null == s ? void 0 : s.documentPath);
}
s.$$set = s => {
if ("list" in s) o(13, u = s.list);
if ("thisTerm" in s) o(14, g = s.thisTerm);
if ("hideNotApplicable" in s) o(15, _ = s.hideNotApplicable);
if ("selectNewest" in s) o(16, m = s.selectNewest);
if ("applyAllPluse" in s) o(17, b = s.applyAllPluse);
if ("applyData" in s) o(18, E = s.applyData);
if ("compareData" in s) o(19, w = s.compareData);
if ("deleteData" in s) o(20, S = s.deleteData);
if ("hidden" in s) o(0, L = s.hidden);
if ("plugin" in s) o(21, O = s.plugin);
if ("isMaintenanceMode" in s) o(1, D = s.isMaintenanceMode);
};
s.$$.update = () => {
if (4268034 & s.$$.dirty[0]) {
const s = m != P;
o(22, P = m);
(async function updateTerms(s, r, u) {
const m = s.find((s => s.term == g));
o(2, C = "");
if (u) o(8, B = [ ...new Set(s.map((s => s.term))) ]); else if (_) {
const r = [], u = [ ...new Set(s.map((s => s.term))) ];
for (const o of u) {
const u = s.find((s => s.term == o));
if ((await comparePlugin(m, u)).canApply) r.push(o);
}
o(8, B = [ ...r ]);
} else o(8, B = [ ...new Set(s.map((s => s.term))) ].filter((s => s != g)));
let b = m;
if (r) {
for (const r of B) {
const o = s.find((s => s.term == r));
if (o && o.mtime && ((null == b ? void 0 : b.mtime) || 0) < o.mtime) b = o;
}
if (b && b.term != g) o(2, C = b.term);
}
})(u, s, D);
}
if (8519685 & s.$$.dirty[0]) {
const s = b != N;
o(23, N = b);
if (s && C) if (!L) applySelected();
}
if (24580 & s.$$.dirty[0]) {
o(3, T = "");
o(4, I = "");
o(5, A = "");
o(6, R = false);
if ("" == C) ; else if (C == g) {
o(3, T = "This device");
o(6, R = false);
} else (async function performCompare(s, r) {
var u, g, _;
const m = await comparePlugin(s, r);
o(6, R = m.canApply);
o(3, T = m.freshness);
o(4, I = m.equivalency);
o(5, A = m.version);
o(7, x = m.canCompare);
if (1 != (null == s ? void 0 : s.files.length) || !(null === (_ = null === (g = null === (u = null == s ? void 0 : s.files) || void 0 === u ? void 0 : u.first()) || void 0 === g ? void 0 : g.filename) || void 0 === _ ? void 0 : _.endsWith(".json"))) o(7, x = false);
})(u.find((s => s.term == g)), u.find((s => s.term == C)));
}
};
return [ L, D, C, T, I, A, R, x, B, applySelected, async function compareSelected() {
const s = u.find((s => s.term == g)), r = u.find((s => s.term == C));
if (s && r && await w(s, r)) k.updatePluginList(true, s.documentPath);
}, async function deleteSelected() {
const s = u.find((s => s.term == C));
if (s && await S(s)) k.reloadPluginList(true);
}, async function duplicateItem() {
const s = u.find((s => s.term == g)), r = await askString(O.app, "Duplicate", "device name", "");
if (r) {
if (r.contains("/")) {
Logger('We can not use "/" to the device name', LOG_LEVEL_NOTICE);
return;
}
const o = `${O.app.vault.configDir}/${s.files[0].filename}`;
await k.storeCustomizationFiles(o, r);
await k.updatePluginList(false, k.filenameToUnifiedKey(o, r));
}
}, u, g, _, m, b, E, w, S, O, P, N, function select_change_handler() {
C = select_value(this);
o(2, C);
o(8, B);
} ];
}
var PluginCombo = class extends SvelteComponent {
constructor(s) {
super();
init2(this, s, 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(s) {
append_styles(s, "svelte-664idh", "h3.svelte-664idh.svelte-664idh{position:sticky;top:0;background-color:var(--modal-background)}.labelrow.svelte-664idh.svelte-664idh{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-664idh.svelte-664idh{margin-left:1.25em;display:flex;justify-content:flex-start;align-items:center;padding-right:4px;flex-wrap:wrap}.filerow.hideeven.svelte-664idh.svelte-664idh:has(.even),.labelrow.hideeven.svelte-664idh.svelte-664idh:has(.even){display:none}.noterow.svelte-664idh.svelte-664idh{min-height:2em;display:flex}button.status.svelte-664idh.svelte-664idh{flex-grow:0;margin:2px 4px;min-width:3em;max-width:4em}.statusnote.svelte-664idh.svelte-664idh{display:flex;justify-content:flex-end;padding-right:var(--size-4-12);align-items:center;min-width:10em;flex-grow:1}.title.svelte-664idh.svelte-664idh{color:var(--text-normal);font-size:var(--font-ui-medium);line-height:var(--line-height-tight);margin-right:auto}.filetitle.svelte-664idh.svelte-664idh{color:var(--text-normal);font-size:var(--font-ui-medium);line-height:var(--line-height-tight);margin-right:auto}.buttons.svelte-664idh.svelte-664idh{display:flex;flex-direction:row;justify-content:flex-end;margin-top:8px;flex-wrap:wrap}.buttons.svelte-664idh>button.svelte-664idh{margin-left:4px;width:auto}label.svelte-664idh.svelte-664idh{display:flex;justify-content:center;align-items:center}label.svelte-664idh>span.svelte-664idh{margin-right:0.25em}.is-mobile .title.svelte-664idh.svelte-664idh,.is-mobile .filetitle.svelte-664idh.svelte-664idh{width:100%}.center.svelte-664idh.svelte-664idh{display:flex;justify-content:center;align-items:center;min-height:3em}.maintenancerow.svelte-664idh.svelte-664idh{display:flex;justify-content:flex-end;align-items:center}.maintenancerow.svelte-664idh label.svelte-664idh{margin-right:0.5em;margin-left:0.5em}");
}
function get_each_context3(s, r, o) {
const u = s.slice();
u[53] = r[o];
return u;
}
function get_each_context_12(s, r, o) {
var u, g, _;
const m = s.slice();
m[56] = r[o][0];
m[57] = r[o][1];
const b = `${PREFIX_PLUGIN_ALL}/${m[56]}`;
m[58] = b;
const E = null != (u = m[5].get(m[58])) ? u : MODE_SELECTIVE;
m[59] = E;
const w = `${PREFIX_PLUGIN_MAIN}/${m[56]}`;
m[60] = w;
const S = null != (g = m[5].get(m[60])) ? g : MODE_SELECTIVE;
m[61] = S;
const L = `${PREFIX_PLUGIN_DATA}/${m[56]}`;
m[62] = L;
const O = null != (_ = m[5].get(m[62])) ? _ : MODE_SELECTIVE;
m[63] = O;
return m;
}
function get_each_context_2(s, r, o) {
const u = s.slice();
u[66] = r[o][0];
u[67] = r[o][1];
return u;
}
function get_each_context_3(s, r, o) {
var u;
const g = s.slice();
g[56] = r[o];
const _ = `${g[66]}/${g[56]}`;
g[70] = _;
const m = null != (u = g[5].get(g[70])) ? u : MODE_SELECTIVE;
g[71] = m;
return g;
}
function create_if_block_8(s) {
let r, o, u;
return {
c() {
r = element("button");
r.textContent = "Reload";
attr(r, "class", "svelte-664idh");
},
m(g, _) {
insert(g, r, _);
if (!o) {
u = listen(r, "click", s[28]);
o = true;
}
},
p: noop,
d(s) {
if (s) detach(r);
o = false;
u();
}
};
}
function create_if_block_7(s) {
let r;
return {
c() {
r = element("div");
r.innerHTML = "Updating list...";
},
m(s, o) {
insert(s, r, o);
},
d(s) {
if (s) detach(r);
}
};
}
function create_else_block3(s) {
let r, o, u, g, _, m = ensure_array_like(Object.entries(s[11]).filter(s[31])), b = [];
for (let r = 0; r < m.length; r += 1) b[r] = create_each_block_2(get_each_context_2(s, m, r));
const out = s => transition_out(b[s], 1, 1, (() => {
b[s] = null;
}));
let E = ensure_array_like(groupBy(filterList(s[0], [ "PLUGIN_MAIN", "PLUGIN_DATA", "PLUGIN_ETC" ]), "name")), w = [];
for (let r = 0; r < E.length; r += 1) w[r] = create_each_block_12(get_each_context_12(s, E, r));
const out_1 = s => transition_out(w[s], 1, 1, (() => {
w[s] = null;
}));
return {
c() {
for (let s = 0; s < b.length; s += 1) b[s].c();
r = space();
o = element("div");
u = element("h3");
u.textContent = "Plugins";
g = space();
for (let s = 0; s < w.length; s += 1) w[s].c();
attr(u, "class", "svelte-664idh");
},
m(s, m) {
for (let r = 0; r < b.length; r += 1) if (b[r]) b[r].m(s, m);
insert(s, r, m);
insert(s, o, m);
append(o, u);
append(o, g);
for (let s = 0; s < w.length; s += 1) if (w[s]) w[s].m(o, null);
_ = true;
},
p(s, u) {
if (461157 & u[0]) {
m = ensure_array_like(Object.entries(s[11]).filter(s[31]));
let o;
for (o = 0; o < m.length; o += 1) {
const g = get_each_context_2(s, m, o);
if (b[o]) {
b[o].p(g, u);
transition_in(b[o], 1);
} else {
b[o] = create_each_block_2(g);
b[o].c();
transition_in(b[o], 1);
b[o].m(r.parentNode, r);
}
}
group_outros();
for (o = m.length; o < b.length; o += 1) out(o);
check_outros();
}
if (459045 & u[0]) {
E = ensure_array_like(groupBy(filterList(s[0], [ "PLUGIN_MAIN", "PLUGIN_DATA", "PLUGIN_ETC" ]), "name"));
let r;
for (r = 0; r < E.length; r += 1) {
const g = get_each_context_12(s, E, r);
if (w[r]) {
w[r].p(g, u);
transition_in(w[r], 1);
} else {
w[r] = create_each_block_12(g);
w[r].c();
transition_in(w[r], 1);
w[r].m(o, null);
}
}
group_outros();
for (r = E.length; r < w.length; r += 1) out_1(r);
check_outros();
}
},
i(s) {
if (!_) {
for (let s = 0; s < m.length; s += 1) transition_in(b[s]);
for (let s = 0; s < E.length; s += 1) transition_in(w[s]);
_ = true;
}
},
o(s) {
b = b.filter(Boolean);
for (let s = 0; s < b.length; s += 1) transition_out(b[s]);
w = w.filter(Boolean);
for (let s = 0; s < w.length; s += 1) transition_out(w[s]);
_ = false;
},
d(s) {
if (s) {
detach(r);
detach(o);
}
destroy_each(b, s);
destroy_each(w, s);
}
};
}
function create_if_block_13(s) {
let r;
return {
c() {
r = element("div");
r.textContent = "No Items.";
attr(r, "class", "center svelte-664idh");
},
m(s, o) {
insert(s, r, o);
},
p: noop,
i: noop,
o: noop,
d(s) {
if (s) detach(r);
}
};
}
function create_else_block_4(s) {
let r, o, u = s[17][s[71]] + "";
return {
c() {
r = element("div");
o = text(u);
attr(r, "class", "statusnote svelte-664idh");
},
m(s, u) {
insert(s, r, u);
append(r, o);
},
p(s, r) {
if (96 & r[0] && u !== (u = s[17][s[71]] + "")) set_data(o, u);
},
i: noop,
o: noop,
d(s) {
if (s) detach(r);
}
};
}
function create_if_block_6(s) {
let r, o;
function func_1(...r) {
return s[33](s[66], s[56], ...r);
}
const u = [ s[8], {
list: s[0].filter(func_1)
}, {
hidden: false
} ];
let g = {};
for (let s = 0; s < u.length; s += 1) g = assign(g, u[s]);
r = new PluginCombo_default({
props: g
});
return {
c() {
create_component(r.$$.fragment);
},
m(s, u) {
mount_component(r, s, u);
o = true;
},
p(o, g) {
s = o;
const _ = 2369 & g[0] ? get_spread_update(u, [ 256 & g[0] && get_spread_object(s[8]), 2113 & g[0] && {
list: s[0].filter(func_1)
}, u[2] ]) : {};
r.$set(_);
},
i(s) {
if (!o) {
transition_in(r.$$.fragment, s);
o = true;
}
},
o(s) {
transition_out(r.$$.fragment, s);
o = false;
},
d(s) {
destroy_component(r, s);
}
};
}
function create_each_block_3(s) {
let r, o, u, g, _, m, b, E, w, S, L, O, D, k, C = s[18](s[71]) + "", T = s[56] + "";
function click_handler_6(...r) {
return s[32](s[66], s[56], s[70], ...r);
}
const I = [ create_if_block_6, create_else_block_4 ], A = [];
function select_block_type_1(s, r) {
if (s[71] == MODE_SELECTIVE) return 0; else return 1;
}
w = select_block_type_1(s);
S = A[w] = I[w](s);
return {
c() {
r = element("div");
o = element("div");
u = element("button");
g = text(C);
_ = space();
m = element("span");
b = text(T);
E = space();
S.c();
attr(u, "class", "status svelte-664idh");
attr(m, "class", "name");
attr(o, "class", "title svelte-664idh");
attr(r, "class", L = "labelrow " + (s[2] ? "hideeven" : "") + " svelte-664idh");
},
m(s, S) {
insert(s, r, S);
append(r, o);
append(o, u);
append(u, g);
append(o, _);
append(o, m);
append(m, b);
append(r, E);
A[w].m(r, null);
O = true;
if (!D) {
k = listen(u, "click", click_handler_6);
D = true;
}
},
p(o, u) {
s = o;
if ((!O || 96 & u[0]) && C !== (C = s[18](s[71]) + "")) set_data(g, C);
if ((!O || 64 & u[0]) && T !== (T = s[56] + "")) set_data(b, T);
let _ = w;
w = select_block_type_1(s);
if (w === _) A[w].p(s, u); else {
group_outros();
transition_out(A[_], 1, 1, (() => {
A[_] = null;
}));
check_outros();
S = A[w];
if (!S) {
S = A[w] = I[w](s);
S.c();
} else S.p(s, u);
transition_in(S, 1);
S.m(r, null);
}
if (!O || 4 & u[0] && L !== (L = "labelrow " + (s[2] ? "hideeven" : "") + " svelte-664idh")) attr(r, "class", L);
},
i(s) {
if (!O) {
transition_in(S);
O = true;
}
},
o(s) {
transition_out(S);
O = false;
},
d(s) {
if (s) detach(r);
A[w].d();
D = false;
k();
}
};
}
function create_each_block_2(s) {
let r, o, u, g, _, m = s[67] + "", b = ensure_array_like(s[6][s[66]]), E = [];
for (let r = 0; r < b.length; r += 1) E[r] = create_each_block_3(get_each_context_3(s, b, r));
const out = s => transition_out(E[s], 1, 1, (() => {
E[s] = null;
}));
return {
c() {
r = element("div");
o = element("h3");
u = text(m);
g = space();
for (let s = 0; s < E.length; s += 1) E[s].c();
attr(o, "class", "svelte-664idh");
},
m(s, m) {
insert(s, r, m);
append(r, o);
append(o, u);
append(r, g);
for (let s = 0; s < E.length; s += 1) if (E[s]) E[s].m(r, null);
_ = true;
},
p(s, o) {
if ((!_ || 64 & o[0]) && m !== (m = s[67] + "")) set_data(u, m);
if (461157 & o[0]) {
b = ensure_array_like(s[6][s[66]]);
let u;
for (u = 0; u < b.length; u += 1) {
const g = get_each_context_3(s, b, u);
if (E[u]) {
E[u].p(g, o);
transition_in(E[u], 1);
} else {
E[u] = create_each_block_3(g);
E[u].c();
transition_in(E[u], 1);
E[u].m(r, null);
}
}
group_outros();
for (u = b.length; u < E.length; u += 1) out(u);
check_outros();
}
},
i(s) {
if (!_) {
for (let s = 0; s < b.length; s += 1) transition_in(E[s]);
_ = true;
}
},
o(s) {
E = E.filter(Boolean);
for (let s = 0; s < E.length; s += 1) transition_out(E[s]);
_ = false;
},
d(s) {
if (s) detach(r);
destroy_each(E, s);
}
};
}
function create_if_block_52(s) {
let r, o;
const u = [ s[8], {
list: s[57]
}, {
hidden: true
} ];
let g = {};
for (let s = 0; s < u.length; s += 1) g = assign(g, u[s]);
r = new PluginCombo_default({
props: g
});
return {
c() {
create_component(r.$$.fragment);
},
m(s, u) {
mount_component(r, s, u);
o = true;
},
p(s, o) {
const g = 257 & o[0] ? get_spread_update(u, [ 256 & o[0] && get_spread_object(s[8]), 1 & o[0] && {
list: s[57]
}, u[2] ]) : {};
r.$set(g);
},
i(s) {
if (!o) {
transition_in(r.$$.fragment, s);
o = true;
}
},
o(s) {
transition_out(r.$$.fragment, s);
o = false;
},
d(s) {
destroy_component(r, s);
}
};
}
function create_else_block_32(s) {
let r, o, u, g, _ = s[17][s[59]] + "";
return {
c() {
r = element("div");
o = element("div");
u = text(_);
g = space();
attr(o, "class", "statusnote svelte-664idh");
attr(r, "class", "noterow svelte-664idh");
},
m(s, _) {
insert(s, r, _);
append(r, o);
append(o, u);
append(r, g);
},
p(s, r) {
if (33 & r[0] && _ !== (_ = s[17][s[59]] + "")) set_data(u, _);
},
i: noop,
o: noop,
d(s) {
if (s) detach(r);
}
};
}
function create_if_block_23(s) {
let r, o, u, g, _, m, b, E, w, S, L, O, D, k, C, T, I, A, R, x, P, N, B, F, M, V = s[18](s[61]) + "", G = s[18](s[63]) + "";
function click_handler_8(...r) {
return s[35](s[56], s[60], ...r);
}
const j = [ create_if_block_43, create_else_block_22 ], q = [];
function select_block_type_3(s, r) {
if (s[61] == MODE_SELECTIVE) return 0; else return 1;
}
E = select_block_type_3(s);
w = q[E] = j[E](s);
function click_handler_9(...r) {
return s[36](s[56], s[62], ...r);
}
const U = [ create_if_block_33, create_else_block_13 ], z = [];
function select_block_type_4(s, r) {
if (s[63] == MODE_SELECTIVE) return 0; else return 1;
}
R = select_block_type_4(s);
x = z[R] = U[R](s);
return {
c() {
r = element("div");
o = element("div");
u = element("button");
g = text(V);
_ = space();
m = element("span");
m.textContent = "MAIN";
b = space();
w.c();
L = space();
O = element("div");
D = element("div");
k = element("button");
C = text(G);
T = space();
I = element("span");
I.textContent = "DATA";
A = space();
x.c();
P = space();
attr(u, "class", "status svelte-664idh");
attr(m, "class", "name");
attr(o, "class", "filetitle svelte-664idh");
attr(r, "class", S = "filerow " + (s[2] ? "hideeven" : "") + " svelte-664idh");
attr(k, "class", "status svelte-664idh");
attr(I, "class", "name");
attr(D, "class", "filetitle svelte-664idh");
attr(O, "class", N = "filerow " + (s[2] ? "hideeven" : "") + " svelte-664idh");
},
m(s, w) {
insert(s, r, w);
append(r, o);
append(o, u);
append(u, g);
append(o, _);
append(o, m);
append(r, b);
q[E].m(r, null);
insert(s, L, w);
insert(s, O, w);
append(O, D);
append(D, k);
append(k, C);
append(D, T);
append(D, I);
append(O, A);
z[R].m(O, null);
append(O, P);
B = true;
if (!F) {
M = [ listen(u, "click", click_handler_8), listen(k, "click", click_handler_9) ];
F = true;
}
},
p(o, u) {
s = o;
if ((!B || 33 & u[0]) && V !== (V = s[18](s[61]) + "")) set_data(g, V);
let _ = E;
E = select_block_type_3(s);
if (E === _) q[E].p(s, u); else {
group_outros();
transition_out(q[_], 1, 1, (() => {
q[_] = null;
}));
check_outros();
w = q[E];
if (!w) {
w = q[E] = j[E](s);
w.c();
} else w.p(s, u);
transition_in(w, 1);
w.m(r, null);
}
if (!B || 4 & u[0] && S !== (S = "filerow " + (s[2] ? "hideeven" : "") + " svelte-664idh")) attr(r, "class", S);
if ((!B || 33 & u[0]) && G !== (G = s[18](s[63]) + "")) set_data(C, G);
let m = R;
R = select_block_type_4(s);
if (R === m) z[R].p(s, u); else {
group_outros();
transition_out(z[m], 1, 1, (() => {
z[m] = null;
}));
check_outros();
x = z[R];
if (!x) {
x = z[R] = U[R](s);
x.c();
} else x.p(s, u);
transition_in(x, 1);
x.m(O, P);
}
if (!B || 4 & u[0] && N !== (N = "filerow " + (s[2] ? "hideeven" : "") + " svelte-664idh")) attr(O, "class", N);
},
i(s) {
if (!B) {
transition_in(w);
transition_in(x);
B = true;
}
},
o(s) {
transition_out(w);
transition_out(x);
B = false;
},
d(s) {
if (s) {
detach(r);
detach(L);
detach(O);
}
q[E].d();
z[R].d();
F = false;
run_all(M);
}
};
}
function create_else_block_22(s) {
let r, o, u = s[17][s[61]] + "";
return {
c() {
r = element("div");
o = text(u);
attr(r, "class", "statusnote svelte-664idh");
},
m(s, u) {
insert(s, r, u);
append(r, o);
},
p(s, r) {
if (33 & r[0] && u !== (u = s[17][s[61]] + "")) set_data(o, u);
},
i: noop,
o: noop,
d(s) {
if (s) detach(r);
}
};
}
function create_if_block_43(s) {
let r, o;
const u = [ s[8], {
list: filterList(s[57], [ "PLUGIN_MAIN" ])
}, {
hidden: false
} ];
let g = {};
for (let s = 0; s < u.length; s += 1) g = assign(g, u[s]);
r = new PluginCombo_default({
props: g
});
return {
c() {
create_component(r.$$.fragment);
},
m(s, u) {
mount_component(r, s, u);
o = true;
},
p(s, o) {
const g = 257 & o[0] ? get_spread_update(u, [ 256 & o[0] && get_spread_object(s[8]), 1 & o[0] && {
list: filterList(s[57], [ "PLUGIN_MAIN" ])
}, u[2] ]) : {};
r.$set(g);
},
i(s) {
if (!o) {
transition_in(r.$$.fragment, s);
o = true;
}
},
o(s) {
transition_out(r.$$.fragment, s);
o = false;
},
d(s) {
destroy_component(r, s);
}
};
}
function create_else_block_13(s) {
let r, o, u = s[17][s[63]] + "";
return {
c() {
r = element("div");
o = text(u);
attr(r, "class", "statusnote svelte-664idh");
},
m(s, u) {
insert(s, r, u);
append(r, o);
},
p(s, r) {
if (33 & r[0] && u !== (u = s[17][s[63]] + "")) set_data(o, u);
},
i: noop,
o: noop,
d(s) {
if (s) detach(r);
}
};
}
function create_if_block_33(s) {
let r, o;
const u = [ s[8], {
list: filterList(s[57], [ "PLUGIN_DATA" ])
}, {
hidden: false
} ];
let g = {};
for (let s = 0; s < u.length; s += 1) g = assign(g, u[s]);
r = new PluginCombo_default({
props: g
});
return {
c() {
create_component(r.$$.fragment);
},
m(s, u) {
mount_component(r, s, u);
o = true;
},
p(s, o) {
const g = 257 & o[0] ? get_spread_update(u, [ 256 & o[0] && get_spread_object(s[8]), 1 & o[0] && {
list: filterList(s[57], [ "PLUGIN_DATA" ])
}, u[2] ]) : {};
r.$set(g);
},
i(s) {
if (!o) {
transition_in(r.$$.fragment, s);
o = true;
}
},
o(s) {
transition_out(r.$$.fragment, s);
o = false;
},
d(s) {
destroy_component(r, s);
}
};
}
function create_each_block_12(s) {
let r, o, u, g, _, m, b, E, w, S, L, O, D, k, C, T, I = s[18](s[59]) + "", A = s[56] + "";
function click_handler_7(...r) {
return s[34](s[56], s[58], ...r);
}
let R = s[59] == MODE_SELECTIVE && create_if_block_52(s);
const x = [ create_if_block_23, create_else_block_32 ], P = [];
function select_block_type_2(s, r) {
if (s[59] == MODE_SELECTIVE) return 0; else return 1;
}
L = select_block_type_2(s);
O = P[L] = x[L](s);
return {
c() {
r = element("div");
o = element("div");
u = element("button");
g = text(I);
_ = space();
m = element("span");
b = text(A);
E = space();
if (R) R.c();
S = space();
O.c();
D = empty();
attr(u, "class", "status svelte-664idh");
attr(m, "class", "name");
attr(o, "class", "title svelte-664idh");
attr(r, "class", w = "labelrow " + (s[2] ? "hideeven" : "") + " svelte-664idh");
},
m(s, w) {
insert(s, r, w);
append(r, o);
append(o, u);
append(u, g);
append(o, _);
append(o, m);
append(m, b);
append(r, E);
if (R) R.m(r, null);
insert(s, S, w);
P[L].m(s, w);
insert(s, D, w);
k = true;
if (!C) {
T = listen(u, "click", click_handler_7);
C = true;
}
},
p(o, u) {
s = o;
if ((!k || 33 & u[0]) && I !== (I = s[18](s[59]) + "")) set_data(g, I);
if ((!k || 1 & u[0]) && A !== (A = s[56] + "")) set_data(b, A);
if (s[59] == MODE_SELECTIVE) if (R) {
R.p(s, u);
if (33 & u[0]) transition_in(R, 1);
} else {
R = create_if_block_52(s);
R.c();
transition_in(R, 1);
R.m(r, null);
} else if (R) {
group_outros();
transition_out(R, 1, 1, (() => {
R = null;
}));
check_outros();
}
if (!k || 4 & u[0] && w !== (w = "labelrow " + (s[2] ? "hideeven" : "") + " svelte-664idh")) attr(r, "class", w);
let _ = L;
L = select_block_type_2(s);
if (L === _) P[L].p(s, u); else {
group_outros();
transition_out(P[_], 1, 1, (() => {
P[_] = null;
}));
check_outros();
O = P[L];
if (!O) {
O = P[L] = x[L](s);
O.c();
} else O.p(s, u);
transition_in(O, 1);
O.m(D.parentNode, D);
}
},
i(s) {
if (!k) {
transition_in(R);
transition_in(O);
k = true;
}
},
o(s) {
transition_out(R);
transition_out(O);
k = false;
},
d(s) {
if (s) {
detach(r);
detach(S);
detach(D);
}
if (R) R.d();
P[L].d(s);
C = false;
T();
}
};
}
function create_if_block3(s) {
let r, o, u, g, _, m, b, E, w, S, L, O, D = ensure_array_like(s[4]), k = [];
for (let r = 0; r < D.length; r += 1) k[r] = create_each_block3(get_each_context3(s, D, r));
return {
c() {
r = element("div");
o = element("div");
u = element("h3");
u.textContent = "Maintenance Commands";
g = space();
_ = element("div");
m = element("label");
m.textContent = "Delete All of";
b = space();
E = element("select");
for (let s = 0; s < k.length; s += 1) k[s].c();
w = space();
S = element("button");
S.textContent = "🗑️";
attr(u, "class", "svelte-664idh");
attr(m, "for", "");
attr(m, "class", "svelte-664idh");
if (void 0 === s[7]) add_render_callback((() => s[37].call(E)));
attr(S, "class", "status svelte-664idh");
attr(_, "class", "maintenancerow svelte-664idh");
attr(r, "class", "list");
},
m(D, C) {
insert(D, r, C);
append(r, o);
append(o, u);
append(o, g);
append(o, _);
append(_, m);
append(_, b);
append(_, E);
for (let s = 0; s < k.length; s += 1) if (k[s]) k[s].m(E, null);
select_option(E, s[7], true);
append(_, w);
append(_, S);
if (!L) {
O = [ listen(E, "change", s[37]), listen(S, "click", s[38]) ];
L = true;
}
},
p(s, r) {
if (16 & r[0]) {
D = ensure_array_like(s[4]);
let o;
for (o = 0; o < D.length; o += 1) {
const u = get_each_context3(s, D, o);
if (k[o]) k[o].p(u, r); else {
k[o] = create_each_block3(u);
k[o].c();
k[o].m(E, null);
}
}
for (;o < k.length; o += 1) k[o].d(1);
k.length = D.length;
}
if (144 & r[0]) select_option(E, s[7]);
},
d(s) {
if (s) detach(r);
destroy_each(k, s);
L = false;
run_all(O);
}
};
}
function create_each_block3(s) {
let r, o, u, g = s[53] + "";
return {
c() {
r = element("option");
o = text(g);
r.__value = u = s[53];
set_input_value(r, r.__value);
},
m(s, u) {
insert(s, r, u);
append(r, o);
},
p(s, _) {
if (16 & _[0] && g !== (g = s[53] + "")) set_data(o, g);
if (16 & _[0] && u !== (u = s[53])) {
r.__value = u;
set_input_value(r, r.__value);
}
},
d(s) {
if (s) detach(r);
}
};
}
function create_fragment3(s) {
let r, o, u, g, _, m, b, E, w, S, L, O, D, k, C, T, I, A, R, x, P, N, B, F, M, V, G, j, q, U, z, W, H, K = s[1] && create_if_block_8(s), Q = s[3] && create_if_block_7(s);
const J = [ create_if_block_13, create_else_block3 ], Y = [];
function select_block_type(s, r) {
if (0 == s[0].length) return 0; else return 1;
}
A = select_block_type(s);
R = Y[A] = J[A](s);
let X = s[1] && create_if_block3(s);
return {
c() {
r = element("div");
o = element("div");
u = element("div");
g = element("button");
g.textContent = "Scan changes";
_ = space();
m = element("button");
m.textContent = "Sync once";
b = space();
E = element("button");
E.textContent = "Refresh";
w = space();
if (K) K.c();
S = space();
L = element("button");
L.textContent = "Select All Shiny";
O = space();
D = element("div");
k = element("button");
k.textContent = "Apply All";
C = space();
if (Q) Q.c();
T = space();
I = element("div");
R.c();
x = space();
if (X) X.c();
P = space();
N = element("div");
B = element("label");
F = element("span");
F.textContent = "Hide not applicable items";
M = element("input");
V = space();
G = element("div");
j = element("label");
q = element("span");
q.textContent = "Maintenance mode";
U = element("input");
attr(g, "class", "svelte-664idh");
attr(m, "class", "svelte-664idh");
attr(E, "class", "svelte-664idh");
attr(L, "class", "svelte-664idh");
attr(u, "class", "buttons svelte-664idh");
attr(k, "class", "svelte-664idh");
attr(D, "class", "buttons svelte-664idh");
attr(I, "class", "list");
attr(F, "class", "svelte-664idh");
attr(M, "type", "checkbox");
attr(B, "class", "svelte-664idh");
attr(N, "class", "buttons svelte-664idh");
attr(q, "class", "svelte-664idh");
attr(U, "type", "checkbox");
attr(j, "class", "svelte-664idh");
attr(G, "class", "buttons svelte-664idh");
},
m(R, J) {
insert(R, r, J);
append(r, o);
append(o, u);
append(u, g);
append(u, _);
append(u, m);
append(u, b);
append(u, E);
append(u, w);
if (K) K.m(u, null);
append(u, S);
append(u, L);
append(o, O);
append(o, D);
append(D, k);
append(r, C);
if (Q) Q.m(r, null);
append(r, T);
append(r, I);
Y[A].m(I, null);
append(r, x);
if (X) X.m(r, null);
append(r, P);
append(r, N);
append(N, B);
append(B, F);
append(B, M);
M.checked = s[2];
append(r, V);
append(r, G);
append(G, j);
append(j, q);
append(j, U);
U.checked = s[1];
z = true;
if (!W) {
H = [ listen(g, "click", s[25]), listen(m, "click", s[26]), listen(E, "click", s[27]), listen(L, "click", s[29]), listen(k, "click", s[30]), listen(M, "change", s[39]), listen(U, "change", s[40]) ];
W = true;
}
},
p(s, o) {
if (s[1]) if (K) K.p(s, o); else {
K = create_if_block_8(s);
K.c();
K.m(u, S);
} else if (K) {
K.d(1);
K = null;
}
if (s[3]) if (Q) ; else {
Q = create_if_block_7(s);
Q.c();
Q.m(r, T);
} else if (Q) {
Q.d(1);
Q = null;
}
let g = A;
A = select_block_type(s);
if (A === g) Y[A].p(s, o); else {
group_outros();
transition_out(Y[g], 1, 1, (() => {
Y[g] = null;
}));
check_outros();
R = Y[A];
if (!R) {
R = Y[A] = J[A](s);
R.c();
} else R.p(s, o);
transition_in(R, 1);
R.m(I, null);
}
if (s[1]) if (X) X.p(s, o); else {
X = create_if_block3(s);
X.c();
X.m(r, P);
} else if (X) {
X.d(1);
X = null;
}
if (4 & o[0]) M.checked = s[2];
if (2 & o[0]) U.checked = s[1];
},
i(s) {
if (!z) {
transition_in(R);
z = true;
}
},
o(s) {
transition_out(R);
z = false;
},
d(s) {
if (s) detach(r);
if (K) K.d();
if (Q) Q.d();
Y[A].d();
if (X) X.d();
W = false;
run_all(H);
}
};
}
var PREFIX_PLUGIN_ALL = "PLUGIN_ALL", PREFIX_PLUGIN_DATA = "PLUGIN_DATA", PREFIX_PLUGIN_MAIN = "PLUGIN_MAIN";
function filterList(s, r) {
return s.filter((s => -1 !== r.indexOf(s.category))).sort(((s, r) => `${s.category}-${s.name}`.localeCompare(`${r.category}-${r.name}`)));
}
function groupBy(s, r) {
let o = {};
for (const u of s) {
const s = r in u ? u[r] : "";
o[s] = o[s] || [];
o[s].push(u);
}
for (const s in o) o[s] = o[s].sort(((s, r) => `${s.category}-${s.name}`.localeCompare(`${r.category}-${r.name}`)));
return Object.entries(o).sort((([s], [r]) => `${s}`.localeCompare(`${r}`)));
}
function instance3(s, r, o) {
let u, g, _, {plugin: m} = r;
const b = m.addOnConfigSync;
let E = [], w = 0, S = false, L = false, O = 0, D = false;
async function requestUpdate() {
await b.updatePluginList(true);
}
async function requestReload() {
await b.reloadPluginList(true);
}
let k = [];
pluginList.subscribe((s => {
o(0, E = s);
o(4, k = unique(E.map((s => s.term))));
}));
pluginIsEnumerating.subscribe((s => {
o(3, L = s);
}));
onMount((async () => {
requestUpdate();
}));
async function scanAgain() {
await b.scanAllConfigFiles(true);
await requestUpdate();
}
async function replicate2() {
await m.replicate(true);
}
function selectAllNewest() {
o(21, w++, w);
}
function applyAll() {
o(22, O++, O);
}
async function applyData(s) {
return await b.applyData(s);
}
async function compareData(s, r) {
return await b.compareUsingDisplayData(s, r);
}
async function deleteData(s) {
return await b.deleteData(s);
}
function askMode(s, r, o) {
var u;
const g = new import_obsidian3.Menu;
g.addItem((s => s.setTitle(r).setIsLabel(true)));
g.addSeparator();
const _ = null !== (u = I.get(o)) && void 0 !== u ? u : MODE_SELECTIVE;
for (const r of [ MODE_SELECTIVE, MODE_AUTOMATIC, MODE_PAUSED ]) g.addItem((u => {
u.setTitle(`${getIcon(r)}:${T[r]}`).onClick((u => {
if (r === MODE_AUTOMATIC) askOverwriteModeForAutomatic(s, o); else setMode(o, r);
})).setChecked(_ == r).setDisabled(_ == r);
}));
g.showAtMouseEvent(s);
}
function applyAutomaticSync(s, r) {
var o, u;
setMode(s, MODE_AUTOMATIC);
const g = normalizePath(m.app.vault.configDir), _ = (null !== (u = null === (o = m.settings.pluginSyncExtendedSetting[s]) || void 0 === o ? void 0 : o.files) && void 0 !== u ? u : []).map((s => `${g}/${s}`));
m.addOnHiddenFileSync.syncInternalFilesAndDatabase(r, true, false, _);
}
function askOverwriteModeForAutomatic(s, r) {
const o = new import_obsidian3.Menu;
o.addItem((s => s.setTitle("Initial Action").setIsLabel(true)));
o.addSeparator();
o.addItem((s => {
s.setTitle("↑: Overwrite Remote").onClick((s => {
applyAutomaticSync(r, "pushForce");
}));
})).addItem((s => {
s.setTitle("↓: Overwrite Local").onClick((s => {
applyAutomaticSync(r, "pullForce");
}));
})).addItem((s => {
s.setTitle("⇅: Use newer").onClick((s => {
applyAutomaticSync(r, "safe");
}));
}));
o.showAtMouseEvent(s);
}
const C = {
[MODE_SELECTIVE]: "🔀",
[MODE_PAUSED]: "⛔",
[MODE_AUTOMATIC]: "✨"
}, T = {
[MODE_SELECTIVE]: "Selective",
[MODE_PAUSED]: "Ignore",
[MODE_AUTOMATIC]: "Automatic"
};
function setMode(s, r) {
if (s.startsWith(PREFIX_PLUGIN_ALL + "/")) {
setMode(PREFIX_PLUGIN_DATA + s.substring(PREFIX_PLUGIN_ALL.length), r);
setMode(PREFIX_PLUGIN_MAIN + s.substring(PREFIX_PLUGIN_ALL.length), r);
}
const u = unique(E.filter((r => `${r.category}/${r.name}` == s)).map((s => s.files)).flat().map((s => s.filename)));
I.set(s, r);
o(5, A = I);
if (!(s in m.settings.pluginSyncExtendedSetting)) o(20, m.settings.pluginSyncExtendedSetting[s] = {
key: s,
mode: r,
files: []
}, m);
o(20, m.settings.pluginSyncExtendedSetting[s].files = u, m);
o(20, m.settings.pluginSyncExtendedSetting[s].mode = r, m);
m.saveSettingData();
}
function getIcon(s) {
if (s in C) return C[s];
}
let I = new Map, A = new Map;
for (const {key: s, mode: r} of Object.values(m.settings.pluginSyncExtendedSetting)) I.set(s, r);
A = I;
let R = {}, x = "";
async function deleteAllItems(s) {
const r = E.filter((r => r.term == s));
for (const s of r) await deleteData(s);
b.reloadPluginList(true);
}
s.$$set = s => {
if ("plugin" in s) o(20, m = s.plugin);
};
s.$$.update = () => {
if (1048576 & s.$$.dirty[0]) o(24, g = m.deviceAndVaultName);
if (32505858 & s.$$.dirty[0]) o(8, _ = {
thisTerm: g,
hideNotApplicable: u,
selectNewest: w,
applyAllPluse: O,
applyData,
compareData,
deleteData,
plugin: m,
isMaintenanceMode: D
});
if (1048577 & s.$$.dirty[0]) {
const s = Object.keys(m.settings.pluginSyncExtendedSetting);
o(6, R = [ ...E, ...s.map((s => `${s}///`.split("/"))).filter((s => s[0] && s[1])).map((s => ({
category: s[0],
name: s[1],
displayName: s[1]
}))) ].sort(((s, r) => {
var o, u;
return (null !== (o = s.displayName) && void 0 !== o ? o : s.name).localeCompare(null !== (u = r.displayName) && void 0 !== u ? u : r.name);
})).reduce(((s, r) => {
var o, u;
return {
...s,
[r.category]: unique(r.category in s ? [ ...s[r.category], null !== (o = r.displayName) && void 0 !== o ? o : r.name ] : [ null !== (u = r.displayName) && void 0 !== u ? u : r.name ])
};
}), {}));
}
};
o(23, u = false);
return [ E, D, S, L, k, A, R, x, _, requestUpdate, requestReload, {
CONFIG: "Configuration",
THEME: "Themes",
SNIPPET: "Snippets"
}, scanAgain, replicate2, selectAllNewest, applyAll, askMode, T, getIcon, deleteAllItems, m, w, O, u, g, () => scanAgain(), () => replicate2(), () => requestUpdate(), () => requestReload(), () => selectAllNewest(), () => applyAll(), ([s, r]) => s in R, (s, r, o, u) => askMode(u, `${s}/${r}`, o), (s, r, o) => o.category == s && o.name == r, (s, r, o) => askMode(o, `${PREFIX_PLUGIN_ALL}/${s}`, r), (s, r, o) => askMode(o, `${PREFIX_PLUGIN_MAIN}/${s}/MAIN`, r), (s, r, o) => askMode(o, `${PREFIX_PLUGIN_DATA}/${s}`, r), function select_change_handler() {
x = select_value(this);
o(7, x);
o(4, k);
}, s => {
deleteAllItems(x);
}, function input0_change_handler() {
S = this.checked;
o(2, S);
}, function input1_change_handler() {
D = this.checked;
o(1, D);
} ];
}
var PluginPane = class extends SvelteComponent {
constructor(s) {
super();
init2(this, s, 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(s, r) {
super(s);
this.plugin = r;
}
onOpen() {
const {contentEl: s} = this;
this.titleEl.setText("Customization Sync (Beta2)");
if (!this.component) this.component = new PluginPane_default({
target: s,
props: {
plugin: this.plugin
}
});
}
onClose() {
if (this.component) {
this.component.$destroy();
this.component = void 0;
}
}
}, InputStringDialog = class extends import_obsidian.Modal {
constructor(s, r, o, u, g, _) {
super(s);
this.result = false;
this.isManuallyClosed = false;
this.isPassword = false;
this.onSubmit = _;
this.title = r;
this.placeholder = u;
this.key = o;
this.isPassword = g;
}
onOpen() {
const {contentEl: s} = this;
this.titleEl.setText(this.title);
const r = s.createDiv();
new import_obsidian.Setting(r).setName(this.key).setClass(this.isPassword ? "password-input" : "normal-input").addText((s => s.onChange((s => {
this.result = s;
}))));
new import_obsidian.Setting(r).addButton((s => s.setButtonText("Ok").setCta().onClick((() => {
this.isManuallyClosed = true;
this.close();
})))).addButton((s => s.setButtonText("Cancel").setCta().onClick((() => {
this.close();
}))));
}
onClose() {
const {contentEl: s} = this;
s.empty();
if (this.isManuallyClosed) this.onSubmit(this.result); else this.onSubmit(false);
}
}, PopoverSelectString = class extends import_obsidian.FuzzySuggestModal {
constructor(s, r, o, u, g) {
super(s);
this.callback = () => {};
this.getItemsFun = () => [ "yes", "no" ];
this.app = s;
this.setPlaceholder((null != o ? o : "y/n) ") + r);
if (u) this.getItemsFun = u;
this.callback = g;
}
getItems() {
return this.getItemsFun();
}
getItemText(s) {
return s;
}
onChooseItem(s, r) {
var o;
null == (o = this.callback) || o.call(this, s);
this.callback = void 0;
}
onClose() {
setTimeout((() => {
if (this.callback) {
this.callback("");
this.callback = void 0;
}
}), 100);
}
}, MessageBox = class extends import_obsidian.Modal {
constructor(s, r, o, u, g, _, m) {
super(s.app);
this.result = false;
this.isManuallyClosed = false;
this.timer = void 0;
this.plugin = s;
this.title = r;
this.contentMd = o;
this.buttons = u;
this.onSubmit = m;
this.defaultAction = g;
this.timeout = _;
if (this.timeout) this.timer = setInterval((() => {
var s;
if (void 0 !== this.timeout) {
this.timeout--;
if (this.timeout < 0) {
if (this.timer) {
clearInterval(this.timer);
this.timer = void 0;
}
this.result = g;
this.isManuallyClosed = true;
this.close();
} else null == (s = this.defaultButtonComponent) || s.setButtonText(`( ${this.timeout} ) ${g}`);
}
}), 1e3);
}
onOpen() {
const {contentEl: s} = this;
this.titleEl.setText(this.title);
s.addEventListener("click", (() => {
if (this.timer) {
clearInterval(this.timer);
this.timer = void 0;
}
}));
const r = s.createDiv();
import_obsidian.MarkdownRenderer.render(this.plugin.app, this.contentMd, r, "/", this.plugin);
const o = new import_obsidian.Setting(s);
o.controlEl.style.flexWrap = "wrap";
for (const s of this.buttons) o.addButton((r => {
r.setButtonText(s).onClick((() => {
this.isManuallyClosed = true;
this.result = s;
if (this.timer) {
clearInterval(this.timer);
this.timer = void 0;
}
this.close();
}));
if (s == this.defaultAction) this.defaultButtonComponent = r;
return r;
}));
}
onClose() {
const {contentEl: s} = this;
s.empty();
if (this.timer) {
clearInterval(this.timer);
this.timer = void 0;
}
if (this.isManuallyClosed) this.onSubmit(this.result); else this.onSubmit(false);
}
};
function confirmWithMessage(s, r, o, u, g, _) {
return new Promise((m => {
new MessageBox(s, r, o, u, g, _, (s => m(s))).open();
}));
}
var __save, _save_fn, __load, _load_fn, __queueSave, _queueSave_fn, sameChangePairs, YieldOperationNumbers = 100, PersistentMap = class {
constructor(s, r) {
__privateAdd(this, __save);
__privateAdd(this, __load);
__privateAdd(this, __queueSave);
this._setCount = YieldOperationNumbers;
this._key = s;
this._map = new Map(null != r ? r : []);
__privateMethod(this, __load, _load_fn).call(this, r);
}
flush() {
__privateMethod(this, __save, _save_fn).call(this);
}
delete(s) {
const r = this._map.delete(s);
__privateMethod(this, __queueSave, _queueSave_fn).call(this);
return r;
}
has(s) {
return this._map.has(s);
}
set(s, r) {
this._map.set(s, r);
__privateMethod(this, __queueSave, _queueSave_fn).call(this);
return this;
}
clear() {
this._map = new Map;
__privateMethod(this, __save, _save_fn).call(this);
}
get(s, r) {
const o = this._map.get(s);
if (void 0 === o) return r; else return o;
}
};
__save = new WeakSet;
_save_fn = function() {
localStorage.setItem(this._key, JSON.stringify([ ...this._map.entries() ]));
};
__load = new WeakSet;
_load_fn = function(s = []) {
var r;
try {
const o = null != (r = localStorage.getItem(this._key)) ? r : "", u = "" === o ? "[]" : o, g = JSON.parse(u);
this._map = new Map([ ...g, ...s ]);
} catch (r) {
console.log(`Map read error : ${this._key}`);
console.dir(r);
this._map = new Map([ ...s ]);
}
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(s) {
sameChangePairs = new PersistentMap(`ls-persist-same-changes-${s}`);
}
async function path2id(s, r) {
const o = s.split(":"), u = o.pop(), g = normalizePath(u);
o.push(g);
const _ = o.join(":");
return await path2id_base(_, r);
}
function id2path(s, r) {
const o = id2path_base(s, r).split(":"), u = o.pop(), g = normalizePath(u);
o.push(g);
return o.join(":");
}
function getPath2(s) {
return id2path(s._id, s);
}
function getPathWithoutPrefix(s) {
return stripAllPrefixes(getPath2(s));
}
function getPathFromTFile(s) {
return s.path;
}
var memos = {};
function memoObject(s, r) {
memos[s] = r;
return memos[s];
}
async function memoIfNotExist(s, r) {
if (!(s in memos)) {
const o = r(), u = o instanceof Promise ? await o : o;
memos[s] = u;
}
return memos[s];
}
function retrieveMemoObject(s) {
if (s in memos) return memos[s]; else return false;
}
function disposeMemoObject(s) {
delete memos[s];
}
function isSensibleMargeApplicable(s) {
if (s.endsWith(".md")) return true; else return false;
}
function isObjectMargeApplicable(s) {
if (s.endsWith(".canvas")) return true;
if (s.endsWith(".json")) return true; else return false;
}
function tryParseJSON(s, r) {
try {
return JSON.parse(s);
} catch (s) {
return r;
}
}
var MARK_OPERATOR = "", MARK_DELETED = `${MARK_OPERATOR}__DELETED`, MARK_ISARRAY = `${MARK_OPERATOR}__ARRAY`, MARK_SWAPPED = `${MARK_OPERATOR}__SWAP`;
function unorderedArrayToObject(s) {
return s.map((s => ({
[s.id]: s
}))).reduce(((s, r) => ({
...s,
...r
})), {});
}
function objectToUnorderedArray(s) {
const r = Object.entries(s);
if (r.some((s => {
var r;
return s[0] != (null == (r = s[1]) ? void 0 : r.id);
}))) throw new Error("Item looks like not unordered array");
return r.map((s => s[1]));
}
function generatePatchUnorderedArray(s, r) {
if (s.every((s => "object" == typeof s && "id" in s)) && r.every((s => "object" == typeof s && "id" in s))) {
const o = generatePatchObj(unorderedArrayToObject(s), unorderedArrayToObject(r));
if (Object.keys(o).length > 0) return {
[MARK_ISARRAY]: o
}; else return {};
}
return {
[MARK_SWAPPED]: r
};
}
function generatePatchObj(s, r) {
const o = Object.entries(s), u = new Map(o), g = {}, _ = Object.entries(r);
for (const [s, r] of _) if (!u.has(s)) {
g[s] = r;
u.delete(s);
} else {
const o = u.get(s);
if (typeof o != typeof r || Array.isArray(o) !== Array.isArray(r)) g[s] = {
[MARK_SWAPPED]: r
}; else if ("object" == typeof o && "object" == typeof r && !Array.isArray(o) && !Array.isArray(r)) {
const u = generatePatchObj(o, r);
if (Object.keys(u).length > 0) g[s] = u;
} else if ("object" == typeof o && "object" == typeof r && Array.isArray(o) && Array.isArray(r)) {
const u = generatePatchUnorderedArray(o, r);
if (Object.keys(u).length > 0) g[s] = u;
} else if ("object" != typeof o && "object" != typeof r) {
if (JSON.stringify(u.get(s)) !== JSON.stringify(r)) g[s] = r;
} else if (JSON.stringify(u.get(s)) !== JSON.stringify(r)) g[s] = {
[MARK_SWAPPED]: r
};
u.delete(s);
}
for (const [s] of u) g[s] = MARK_DELETED;
return g;
}
function applyPatch(s, r) {
const o = s, u = Object.entries(r);
for (const [s, r] of u) if (r != MARK_DELETED) if ("object" == typeof r) {
if (MARK_SWAPPED in r) {
o[s] = r[MARK_SWAPPED];
continue;
}
if (MARK_ISARRAY in r) {
if (!(s in o)) o[s] = [];
if (!Array.isArray(o[s])) throw new Error("Patch target type is mismatched (array to something)");
const u = objectToUnorderedArray(applyPatch(unorderedArrayToObject(o[s]), r[MARK_ISARRAY]));
o[s] = [ ...u ];
} else {
if (!(s in o)) {
o[s] = r;
continue;
}
o[s] = applyPatch(o[s], r);
}
} else o[s] = r; else delete o[s];
return o;
}
function mergeObject(s, r) {
const o = Object.entries(r), u = {
...s
};
if (typeof s != typeof r || Array.isArray(s) !== Array.isArray(r)) return r;
for (const [s, r] of o) if (s in u) {
const o = u[s];
if (typeof r != typeof o || Array.isArray(r) !== Array.isArray(o)) u[s] = r; else if ("object" == typeof r && "object" == typeof o && !Array.isArray(r) && !Array.isArray(o)) u[s] = mergeObject(r, o); else if ("object" == typeof r && "object" == typeof o && Array.isArray(r) && Array.isArray(o)) u[s] = [ ...new Set([ ...r, ...o ]) ]; else u[s] = r;
} else u[s] = r;
const g = Object.fromEntries(Object.entries(u).sort(((s, r) => s[0] < r[0] ? -1 : s[0] > r[0] ? 1 : 0)));
if (Array.isArray(s) && Array.isArray(r)) return Object.values(g); else return g;
}
function flattenObject(s, r = []) {
if ("object" != typeof s) return [ [ r.join("."), s ] ];
if (Array.isArray(s)) return [ [ r.join("."), JSON.stringify(s) ] ];
const o = Object.entries(s), u = [];
for (const [s, g] of o) {
const o = flattenObject(g, [ ...r, s ]);
u.push(...o);
}
return u;
}
function isValidPath(s) {
if (import_obsidian.Platform.isDesktop) {
if ("darwin" == process.platform) return isValidFilenameInDarwin(s);
if ("linux" == process.platform) return isValidFilenameInLinux(s); else return isValidFilenameInWidows(s);
}
if (import_obsidian.Platform.isAndroidApp) return isValidFilenameInAndroid(s);
if (import_obsidian.Platform.isIosApp) return isValidFilenameInDarwin(s);
Logger("Could not determine platform for checking filename", LOG_LEVEL_VERBOSE);
return isValidFilenameInWidows(s);
}
function isInternalMetadata(s) {
return s.startsWith(ICHeader);
}
function stripInternalMetadataPrefix(s) {
return s.substring(ICHeaderLength);
}
function isChunk(s) {
return s.startsWith(CHeader);
}
function isPluginMetadata(s) {
return s.startsWith(PSCHeader);
}
function isCustomisationSyncMetadata(s) {
return s.startsWith(ICXHeader);
}
var askYesNo = (s, r) => new Promise((o => {
new PopoverSelectString(s, r, void 0, void 0, (s => o(s))).open();
})), askSelectString = (s, r, o) => {
const getItemsFun = () => o;
return new Promise((o => {
new PopoverSelectString(s, r, "", getItemsFun, (s => o(s))).open();
}));
}, askString = (s, r, o, u, g = false) => new Promise((_ => {
new InputStringDialog(s, r, o, u, g, (s => _(s))).open();
})), PeriodicProcessor = class {
constructor(s, r) {
this._plugin = s;
this._process = r;
}
async process() {
try {
await this._process();
} catch (s) {
Logger(s);
}
}
enable(s) {
this.disable();
if (0 != s) {
this._timer = window.setInterval((() => fireAndForget((async () => {
await this.process();
if (this._plugin._unloaded) this.disable();
}))), s);
this._plugin.registerInterval(this._timer);
}
}
disable() {
if (void 0 !== this._timer) {
window.clearInterval(this._timer);
this._timer = void 0;
}
}
}, _requestToCouchDB = async (s, r, o, u, g, _, m) => {
const b = String.fromCharCode.apply(null, [ ...writeString(`${r}:${o}`) ]), E = {
url: `${s}/${g}`,
method: m || (_ ? "PUT" : "GET"),
headers: {
authorization: "Basic " + window.btoa(b),
origin: u
},
contentType: "application/json",
body: _ ? JSON.stringify(_) : void 0
};
return await (0, import_obsidian.requestUrl)(E);
}, requestToCouchDB = async (s, r, o, u = "", g, _, m) => {
const b = "_node/_local/_config" + (g ? "/" + g : "");
return await _requestToCouchDB(s, r, o, u, b, _, m);
};
async function performRebuildDB(s, r) {
if ("localOnly" == r) await s.addOnSetup.fetchLocal();
if ("localOnlyWithChunks" == r) await s.addOnSetup.fetchLocal(true);
if ("remoteOnly" == r) await s.addOnSetup.rebuildRemote();
if ("rebuildBothByThisDevice" == r) await s.addOnSetup.rebuildEverything();
}
var BASE_IS_NEW = Symbol("base"), TARGET_IS_NEW = Symbol("target"), EVEN = Symbol("even"), resolution = 2e3;
function compareMTime(s, r) {
const o = ~~(s / resolution) * resolution, u = ~~(r / resolution) * resolution;
if (o == u) return EVEN;
if (o > u) return BASE_IS_NEW;
if (o < u) return TARGET_IS_NEW;
throw new Error("Unexpected error");
}
function markChangesAreSame(s, r, o) {
var u;
if (r === o) return true;
const g = "string" == typeof s ? s : s instanceof import_obsidian.TFile ? s.path : null != (u = s.path) ? u : s._id, _ = sameChangePairs.get(g, []) || [];
if (_.some((s => s == r || s == o))) sameChangePairs.set(g, [ ...new Set([ ..._, r, o ]) ]); else sameChangePairs.set(g, [ r, o ]);
}
function isMarkedAsSameChanges(s, r) {
var o;
const u = "string" == typeof s ? s : s instanceof import_obsidian.TFile ? s.path : null != (o = s.path) ? o : s._id, g = sameChangePairs.get(u, []) || [];
if (r.every((s => -1 !== g.indexOf(s)))) return EVEN;
}
function compareFileFreshness(s, r) {
var o, u, g, _, m, b;
if (void 0 === s && null == r) return EVEN;
if (null == s) return TARGET_IS_NEW;
if (null == r) return BASE_IS_NEW;
const E = s instanceof import_obsidian.TFile ? null != (u = null == (o = null == s ? void 0 : s.stat) ? void 0 : o.mtime) ? u : 0 : null != (g = null == s ? void 0 : s.mtime) ? g : 0, w = r instanceof import_obsidian.TFile ? null != (m = null == (_ = null == r ? void 0 : r.stat) ? void 0 : _.mtime) ? m : 0 : null != (b = null == r ? void 0 : r.mtime) ? b : 0;
if (E && w && isMarkedAsSameChanges(s, [ E, w ])) return EVEN; else return compareMTime(E, w);
}
var import_obsidian5 = require("obsidian"), ObsidianLiveSyncSettingTab = class extends import_obsidian.PluginSettingTab {
constructor(s, r) {
super(s, r);
this.selectedScreen = "";
this.plugin = r;
}
async testConnection() {
const s = await this.plugin.replicator.connectRemoteCouchDBWithSetting(this.plugin.settings, this.plugin.isMobile, true);
if ("string" != typeof s) this.plugin.addLog(`Connected to ${s.info.db_name}`, LOG_LEVEL_NOTICE); else this.plugin.addLog(`could not connect to ${this.plugin.settings.couchDB_URI} : ${this.plugin.settings.couchDB_DBNAME} \n(${s})`, LOG_LEVEL_NOTICE);
}
askReload() {
scheduleTask("configReload", 250, (async () => {
if ("yes" == await askYesNo(this.app, "Do you want to restart and reload Obsidian now?")) this.app.commands.executeCommandById("app:reload");
}));
}
closeSetting() {
this.plugin.app.setting.close();
}
display() {
var s;
const {containerEl: r} = this;
let o = this.plugin.settings.encrypt, u = this.plugin.settings.passphrase, g = this.plugin.settings.useDynamicIterationCount;
r.empty();
r.createEl("h2", {
text: "Settings for Self-hosted LiveSync."
});
r.addClass("sls-setting");
r.removeClass("isWizard");
const _ = r.createDiv(""), m = {}, addScreenElement = (s, r) => {
if (!(s in m)) m[s] = [];
m[s].push(r);
};
_.addClass("sls-setting-menu");
_.innerHTML = "\n\n\n\n\n\n\n\n\n ";
const b = _.querySelectorAll(".sls-setting-label"), changeDisplay = s => {
for (const r in m) if (r == s) m[r].forEach((s => s.removeClass("setting-collapsed"))); else m[r].forEach((s => s.addClass("setting-collapsed")));
_.querySelectorAll(".sls-setting-label").forEach((s => {
s.removeClass("selected");
s.querySelector("input[type=radio]").checked = false;
}));
_.querySelectorAll(`.sls-setting-label.c-${s}`).forEach((s => {
s.addClass("selected");
s.querySelector("input[type=radio]").checked = true;
}));
this.selectedScreen = s;
};
b.forEach((s => {
const r = s.querySelector(".sls-setting-tab");
if (r) r.addEventListener("change", (r => {
b.forEach((s => s.removeClass("selected")));
changeDisplay(r.currentTarget.value);
s.addClass("selected");
}));
}));
const E = r.createDiv(), w = E.createEl("h3", {
text: "Updates"
}), S = E.createEl("div", {
text: ""
}), L = "0.22.16", O = ~~(versionNumberString2Number(L) / 1e3), D = createSpan();
D.addClass("sls-header-button");
D.innerHTML = "";
if (O > this.plugin.settings.lastReadUpdates) {
const r = w.appendChild(D);
null == (s = r.querySelector("button")) || s.addEventListener("click", (async () => {
this.plugin.settings.lastReadUpdates = O;
await this.plugin.saveSettings();
r.remove();
}));
}
import_obsidian.MarkdownRenderer.render(this.plugin.app, "### 0.22.0\nA few years passed since Self-hosted LiveSync was born, and our codebase had been very complicated. This could be patient now, but it should be a tremendous hurt.\nTherefore at v0.22.0, for future maintainability, I refined task scheduling logic totally.\n\nOf course, I think this would be our suffering in some cases. However, I would love to ask you for your cooperation and contribution.\n\nSorry for being absent so much long. And thank you for your patience!\n\nNote: we got a very performance improvement.\nNote at 0.22.2: **Now, to rescue mobile devices, Maximum file size is set to 50 by default**. Please configure the limit as you need. If you do not want to limit the sizes, set zero manually, please.\n\n#### Version history\n- 0.22.16:\n - Fixed:\n - Fixed the issue that binary files were sometimes corrupted.\n - Fixed customisation sync data could be corrupted.\n - Improved:\n - Now the remote database costs lower memory.\n - This release requires a brief wait on the first synchronisation, to track the latest changeset again.\n - Description added for the `Device name`.\n - Refactored:\n - Many type-errors have been resolved.\n - Obsolete file has been deleted.\n- 0.22.15:\n - Improved:\n - Faster start-up by removing too many logs which indicates normality\n - By streamlined scanning of customised synchronisation extra phases have been deleted.\n- 0.22.14:\n - New feature:\n - We can disable the status bar in the setting dialogue.\n - Improved:\n - Now some files are handled as correct data type.\n - Customisation sync now uses the digest of each file for better performance.\n - The status in the Editor now works performant.\n - Refactored:\n - Common functions have been ready and the codebase has been organised.\n - Stricter type checking following TypeScript updates.\n - Remove old iOS workaround for simplicity and performance.\n- 0.22.13:\n - Improved:\n - Now using HTTP for the remote database URI warns of an error (on mobile) or notice (on desktop).\n - Refactored:\n - Dependencies have been polished.\n- 0.22.12:\n - Changed:\n - The default settings has been changed.\n - Improved:\n - Default and preferred settings are applied on completion of the wizard.\n - Fixed:\n - Now Initialisation `Fetch` will be performed smoothly and there will be fewer conflicts.\n - No longer stuck while Handling transferred or initialised documents.\n... To continue on to `updates_old.md`.", S, "/", this.plugin);
addScreenElement("100", E);
const isAnySyncEnabled = () => {
if (this.plugin.settings.liveSync) return true;
if (this.plugin.settings.periodicReplication) return true;
if (this.plugin.settings.syncOnFileOpen) return true;
if (this.plugin.settings.syncOnSave) return true;
if (this.plugin.settings.syncOnEditorSave) return true;
if (this.plugin.settings.syncOnStart) return true;
if (this.plugin.settings.syncAfterMerge) return true;
if ("CONNECTED" == this.plugin.replicator.syncStatus) return true;
if ("PAUSED" == this.plugin.replicator.syncStatus) return true; else return false;
};
let k = false;
const C = r.createDiv();
C.createEl("h3", {
text: "Setup wizard"
});
new import_obsidian.Setting(C).setName("Use the copied setup URI").setDesc("To setup Self-hosted LiveSync, this method is the most preferred one.").addButton((s => {
s.setButtonText("Use").onClick((async () => {
this.closeSetting();
await this.plugin.addOnSetup.command_openSetupURI();
}));
}));
if (this.plugin.settings.isConfigured) new import_obsidian.Setting(C).setName("Copy current settings as a new setup URI").addButton((s => {
s.setButtonText("Copy").onClick((async () => {
await this.plugin.addOnSetup.command_copySetupURI();
}));
}));
new import_obsidian.Setting(C).setName("Minimal setup").addButton((s => {
s.setButtonText("Start").onClick((async () => {
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;
this.plugin.replicator.closeReplication();
await this.plugin.saveSettings();
r.addClass("isWizard");
applyDisplayEnabled();
k = true;
changeDisplay("0");
}));
}));
if (!this.plugin.settings.isConfigured) new import_obsidian.Setting(C).setName("Enable LiveSync on this device as the set-up was completed manually").addButton((s => {
s.setButtonText("Enable").onClick((async () => {
this.plugin.settings.isConfigured = true;
await this.plugin.saveSettings();
this.askReload();
}));
}));
if (this.plugin.settings.isConfigured) new import_obsidian.Setting(C).setName("Discard exist settings and databases").addButton((s => {
s.setButtonText("Discard").onClick((async () => {
if ("yes" == await askYesNo(this.plugin.app, "Do you really want to discard exist settings and databases?")) {
this.plugin.settings = {
...DEFAULT_SETTINGS
};
await this.plugin.saveSettingData();
await this.plugin.resetLocalDatabase();
this.askReload();
}
})).setWarning();
}));
C.createEl("h3", {
text: "Online Tips"
});
const T = "vrtmrz/obsidian-livesync", I = "/docs/troubleshooting.md", A = `https://raw.githubusercontent.com/${T}/main`;
C.createEl("div", "", (s => s.innerHTML = `Open in browser`));
const R = C.createEl("div", {
text: "",
cls: "sls-troubleshoot-preview"
}), loadMarkdownPage = async (s, r = "") => {
var o, u;
R.style.minHeight = R.clientHeight + "px";
R.empty();
const g = (s.startsWith("/") ? s : `${r}/${s}`).split("/"), _ = g.pop(), m = g.join("/");
let b = "";
try {
b = await (0, import_obsidian5.request)(`${A}${m}/${_}`);
} catch (s) {
b = "Error Occurred!!\n" + s.toString();
}
const E = b.replace(/\((.*?(.png)|(.jpg))\)/g, `(${A}${m}/$1)`);
await import_obsidian.MarkdownRenderer.render(this.plugin.app, ` [Tips and Troubleshooting](${I}) [PageTop](${_})\n\n${E}`, R, `${A}`, this.plugin);
null == (u = null == (o = R.querySelector(".sls-troubleshoot-anchor")) ? void 0 : o.parentElement) || u.setCssStyles({
position: "sticky",
top: "-1em",
backgroundColor: "var(--modal-background)"
});
R.querySelectorAll("a.internal-link").forEach((s => {
s.addEventListener("click", (async r => {
const o = s.getAttr("data-href");
if (o) if (o.startsWith("#")) {
r.preventDefault();
const s = Array.from(R.querySelectorAll("[data-heading]")).find((s => {
var r;
return (null == (r = s.getAttr("data-heading")) ? void 0 : r.toLowerCase().split(" ").join("-")) == o.substring(1).toLowerCase();
}));
if (s) {
s.setCssStyles({
scrollMargin: "3em"
});
s.scrollIntoView({
behavior: "instant",
block: "start"
});
}
} else {
r.preventDefault();
await loadMarkdownPage(o, m);
R.setCssStyles({
scrollMargin: "1em"
});
R.scrollIntoView({
behavior: "instant",
block: "start"
});
}
}));
}));
R.style.minHeight = "";
};
loadMarkdownPage(I);
addScreenElement("110", C);
const x = r.createDiv();
x.createEl("h3", {
text: "Remote Database configuration"
});
const P = x.createEl("div", {
text: 'These settings are kept locked while any synchronization options are enabled. Disable these options in the "Sync Settings" tab to unlock.'
});
if (this.plugin.settings.couchDB_URI.startsWith("http://")) if (this.plugin.isMobile) x.createEl("div", {
text: "Configured as using plain HTTP. We cannot connect to the remote. Please set up the credentials and use HTTPS for the remote URI."
}).addClass("op-warn"); else x.createEl("div", {
text: "Configured as using plain HTTP. We might fail on mobile devices."
}).addClass("op-warn-info");
P.addClass("op-warn-info");
P.addClass("sls-hidden");
const applyDisplayEnabled = () => {
if (isAnySyncEnabled()) {
N.forEach((s => {
s.setDisabled(true).setTooltip("Could not change this while any synchronization options are enabled.");
}));
P.removeClass("sls-hidden");
} else {
N.forEach((s => {
s.setDisabled(false).setTooltip("");
}));
P.addClass("sls-hidden");
}
if (this.plugin.settings.liveSync) {
Z.forEach((s => {
s.setDisabled(true).setTooltip("");
}));
X.forEach((s => {
s.setDisabled(false).setTooltip("");
}));
} else if (this.plugin.settings.syncOnFileOpen || this.plugin.settings.syncOnSave || this.plugin.settings.syncOnEditorSave || this.plugin.settings.syncOnStart || this.plugin.settings.periodicReplication || this.plugin.settings.syncAfterMerge) {
Z.forEach((s => {
s.setDisabled(false).setTooltip("");
}));
X.forEach((s => {
s.setDisabled(true).setTooltip("");
}));
} else {
Z.forEach((s => {
s.setDisabled(false).setTooltip("");
}));
X.forEach((s => {
s.setDisabled(false).setTooltip("");
}));
}
}, N = [];
N.push(new import_obsidian.Setting(x).setName("URI").addText((s => s.setPlaceholder("https://........").setValue(this.plugin.settings.couchDB_URI).onChange((async s => {
this.plugin.settings.couchDB_URI = s;
await this.plugin.saveSettings();
})))), new import_obsidian.Setting(x).setName("Username").setDesc("username").addText((s => s.setPlaceholder("").setValue(this.plugin.settings.couchDB_USER).onChange((async s => {
this.plugin.settings.couchDB_USER = s;
await this.plugin.saveSettings();
})))), new import_obsidian.Setting(x).setName("Password").setDesc("password").addText((s => {
s.setPlaceholder("").setValue(this.plugin.settings.couchDB_PASSWORD).onChange((async s => {
this.plugin.settings.couchDB_PASSWORD = s;
await this.plugin.saveSettings();
}));
s.inputEl.setAttribute("type", "password");
})), new import_obsidian.Setting(x).setName("Database name").addText((s => s.setPlaceholder("").setValue(this.plugin.settings.couchDB_DBNAME).onChange((async s => {
this.plugin.settings.couchDB_DBNAME = s;
await this.plugin.saveSettings();
})))));
new import_obsidian.Setting(x).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((s => s.setButtonText("Test").setDisabled(false).onClick((async () => {
await this.testConnection();
}))));
new import_obsidian.Setting(x).setName("Check and Fix database configuration").setDesc("Check the database configuration, and fix if there are any problems.").addButton((s => s.setButtonText("Check").setDisabled(false).onClick((async () => {
const checkConfig = async () => {
var s, r, o, u, g, _, m, b, E, w, S;
Logger("Checking database configuration", LOG_LEVEL_INFO);
const L = createDiv();
L.innerHTML = "";
B.replaceChildren(L);
const addResult2 = (s, r) => {
const o = createDiv();
o.addClass("ob-btn-config-fix");
if (r) o.addClasses(r);
o.innerHTML = `${s}`;
B.appendChild(o);
};
try {
if (isCloudantURI(this.plugin.settings.couchDB_URI)) {
Logger("This feature cannot be used with IBM Cloudant.", LOG_LEVEL_NOTICE);
return;
}
const L = (await requestToCouchDB(this.plugin.settings.couchDB_URI, this.plugin.settings.couchDB_USER, this.plugin.settings.couchDB_PASSWORD, window.origin)).json, addConfigFixButton = (s, r, o) => {
var u;
const g = createDiv();
g.addClass("ob-btn-config-fix");
g.innerHTML = ``;
const _ = B.appendChild(g);
null == (u = _.querySelector("button")) || u.addEventListener("click", (async () => {
Logger(`CouchDB Configuration: ${s} -> Set ${r} to ${o}`);
const u = await requestToCouchDB(this.plugin.settings.couchDB_URI, this.plugin.settings.couchDB_USER, this.plugin.settings.couchDB_PASSWORD, void 0, r, o);
if (200 == u.status) {
Logger(`CouchDB Configuration: ${s} successfully updated`, LOG_LEVEL_NOTICE);
B.removeChild(_);
checkConfig();
} else {
Logger(`CouchDB Configuration: ${s} failed`, LOG_LEVEL_NOTICE);
Logger(u.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.plugin.settings.couchDB_USER in L.admins)) addResult2("⚠ You do not have administrative privileges."); else addResult2("✔ You have administrative privileges.");
if ("true" != (null == (s = null == L ? void 0 : L.chttpd) ? void 0 : s.require_valid_user)) {
addResult2("❗ chttpd.require_valid_user looks like wrong.");
addConfigFixButton("Set chttpd.require_valid_user = true", "chttpd/require_valid_user", "true");
} else addResult2("✔ chttpd.require_valid_user is ok.");
if ("true" != (null == (r = null == L ? void 0 : L.chttpd_auth) ? void 0 : r.require_valid_user)) {
addResult2("❗ chttpd_auth.require_valid_user looks like 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 == L ? void 0 : L.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 == (o = null == L ? void 0 : L.httpd) ? void 0 : o.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.plugin.settings.couchDB_URI)) {
if (Number(null != (g = null == (u = null == L ? void 0 : L.chttpd) ? void 0 : u.max_http_request_size) ? g : 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 != (m = null == (_ = null == L ? void 0 : L.couchdb) ? void 0 : _.max_document_size) ? m : 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 == (b = null == L ? void 0 : L.cors) ? void 0 : b.credentials)) {
addResult2("❗ cors.credentials is wrong");
addConfigFixButton("Set cors.credentials", "cors/credentials", "true");
} else addResult2("✔ cors.credentials is ok.");
const O = ((null != (w = null == (E = null == L ? void 0 : L.cors) ? void 0 : E.origins) ? w : "") + "").split(",");
if ("*" == (null == (S = null == L ? void 0 : L.cors) ? void 0 : S.origins) || -1 !== O.indexOf("app://obsidian.md") && -1 !== O.indexOf("capacitor://localhost") && -1 !== O.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 D = [ "app://obsidian.md", "capacitor://localhost", "http://localhost" ];
for (const s of D) {
const r = await requestToCouchDB(this.plugin.settings.couchDB_URI, this.plugin.settings.couchDB_USER, this.plugin.settings.couchDB_PASSWORD, s), o = Object.fromEntries(Object.entries(r.headers).map((s => {
s[0] = `${s[0]}`.toLowerCase();
return s;
})));
addResult2(`Origin check:${s}`);
if ("true" != o["access-control-allow-credentials"]) addResult2("❗ CORS is not allowing credential"); else addResult2("✔ CORS credential OK");
if (o["access-control-allow-origin"] != s) addResult2(`❗ CORS Origin is unmatched:${origin}->${o["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 (s) {
if (401 == (null == s ? void 0 : s.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(s);
}
}
};
await checkConfig();
}))));
const B = x.createEl("div", {
text: ""
});
x.createEl("h4", {
text: "Confidentiality"
});
const F = new import_obsidian.Setting(x).setName("End to End Encryption").setDesc("Encrypt contents on the remote database. If you use the plugin's synchronization feature, enabling this is recommend.").addToggle((s => s.setValue(o).onChange((async s => {
if (k) {
this.plugin.settings.encrypt = s;
o = s;
await this.plugin.saveSettings();
updateE2EControls();
} else {
o = s;
updateE2EControls();
}
}))));
let M = this.plugin.settings.usePathObfuscation;
const updateE2EControls = () => {
F.controlEl.toggleClass("sls-item-dirty", o != this.plugin.settings.encrypt);
if (o) {
V.settingEl.removeClass("sls-setting-hidden");
j.settingEl.removeClass("sls-setting-hidden");
G.settingEl.removeClass("sls-setting-hidden");
null == V || V.controlEl.toggleClass("sls-item-dirty", u != this.plugin.settings.passphrase);
null == j || j.controlEl.toggleClass("sls-item-dirty", g != this.plugin.settings.useDynamicIterationCount);
null == G || G.controlEl.toggleClass("sls-item-dirty", M != this.plugin.settings.usePathObfuscation);
} else {
V.settingEl.addClass("sls-setting-hidden");
j.settingEl.addClass("sls-setting-hidden");
G.settingEl.addClass("sls-setting-hidden");
}
if (o != this.plugin.settings.encrypt || u != this.plugin.settings.passphrase || g != this.plugin.settings.useDynamicIterationCount || M != this.plugin.settings.usePathObfuscation) q.settingEl.removeClass("sls-setting-hidden"); else q.settingEl.addClass("sls-setting-hidden");
}, V = new import_obsidian.Setting(x).setName("Passphrase").setDesc("Encrypting passphrase. If you change the passphrase of a existing database, overwriting the remote database is strongly recommended.").addText((s => {
s.setPlaceholder("").setValue(u).onChange((async s => {
if (k) {
this.plugin.settings.passphrase = s;
await this.plugin.saveSettings();
} else {
u = s;
await this.plugin.saveSettings();
updateE2EControls();
}
}));
s.inputEl.setAttribute("type", "password");
})), G = new import_obsidian.Setting(x).setName("Path Obfuscation").setDesc("Obfuscate paths of files. If we configured, we should rebuild the database.").addToggle((s => s.setValue(M).onChange((async s => {
if (k) {
this.plugin.settings.usePathObfuscation = s;
await this.plugin.saveSettings();
} else {
M = s;
await this.plugin.saveSettings();
updateE2EControls();
}
})))), j = new import_obsidian.Setting(x).setName("Use dynamic iteration count (experimental)").setDesc("Balancing the encryption/decryption load against the length of the passphrase if toggled.").addToggle((s => {
s.setValue(g).onChange((async s => {
if (k) {
this.plugin.settings.useDynamicIterationCount = s;
await this.plugin.saveSettings();
} else {
g = s;
await this.plugin.saveSettings();
updateE2EControls();
}
}));
})).setClass("wizardHidden"), q = new import_obsidian.Setting(x).setName("Apply").setDesc("Apply encryption settings").setClass("wizardHidden").addButton((s => s.setButtonText("Just apply").setWarning().setDisabled(false).onClick((async () => {
await applyEncryption(false);
})))).addButton((s => s.setButtonText("Apply and Fetch").setWarning().setDisabled(false).onClick((async () => {
await rebuildDB("localOnly");
})))).addButton((s => s.setButtonText("Apply and Rebuild").setWarning().setDisabled(false).onClick((async () => {
await rebuildDB("rebuildBothByThisDevice");
}))));
updateE2EControls();
const checkWorkingPassphrase = async () => {
const s = {
...this.plugin.settings,
encrypt: o,
passphrase: u,
useDynamicIterationCount: g
};
console.dir(s);
const r = await this.plugin.replicator.connectRemoteCouchDBWithSetting(s, this.plugin.isMobile, true);
if ("string" == typeof r) {
Logger("Could not connect to the database.", LOG_LEVEL_NOTICE);
return false;
} else if (await checkSyncInfo(r.db)) return true; else {
Logger("Failed to read remote database", LOG_LEVEL_NOTICE);
return false;
}
}, applyEncryption = async s => {
if (!o || "" != u) if (!o || await testCrypt()) {
if (await checkWorkingPassphrase() || s) {
if (!o) u = "";
this.plugin.addOnSetup.suspendAllSync();
this.plugin.addOnSetup.suspendExtraSync();
this.plugin.settings.encrypt = o;
this.plugin.settings.passphrase = u;
this.plugin.settings.useDynamicIterationCount = g;
this.plugin.settings.usePathObfuscation = M;
this.plugin.settings.isConfigured = true;
await this.plugin.saveSettings();
updateE2EControls();
if (s) await this.plugin.addOnSetup.rebuildRemote(); else {
await this.plugin.markRemoteResolved();
await this.plugin.replicate(true);
}
}
} else Logger("WARNING! Your device would not support encryption.", LOG_LEVEL_NOTICE); else Logger("If you enable encryption, you have to set the passphrase", LOG_LEVEL_NOTICE);
}, rebuildDB = async s => {
if (!o || "" != u) if (!o || await testCrypt()) {
if (!o) u = "";
this.plugin.addOnSetup.suspendAllSync();
this.plugin.addOnSetup.suspendExtraSync();
this.plugin.settings.encrypt = o;
this.plugin.settings.passphrase = u;
this.plugin.settings.useDynamicIterationCount = g;
this.plugin.settings.usePathObfuscation = M;
this.plugin.settings.isConfigured = true;
Logger("All synchronization have been temporarily disabled. Please enable them after the fetching, if you need them.", LOG_LEVEL_NOTICE);
await this.plugin.saveSettings();
updateE2EControls();
applyDisplayEnabled();
this.closeSetting();
await delay(2e3);
await performRebuildDB(this.plugin, s);
} else Logger("WARNING! Your device would not support encryption.", LOG_LEVEL_NOTICE); else Logger("If you enable encryption, you have to set the passphrase", LOG_LEVEL_NOTICE);
};
new import_obsidian.Setting(x).setClass("wizardOnly").addButton((s => s.setButtonText("Next").setCta().setDisabled(false).onClick((() => {
if (!this.plugin.settings.encrypt) this.plugin.settings.passphrase = "";
if (isCloudantURI(this.plugin.settings.couchDB_URI)) this.plugin.settings = {
...this.plugin.settings,
...PREFERRED_SETTING_CLOUDANT
}; else this.plugin.settings = {
...this.plugin.settings,
...PREFERRED_SETTING_SELF_HOSTED
};
changeDisplay("30");
}))));
addScreenElement("0", x);
const U = r.createDiv();
U.createEl("h3", {
text: "General Settings"
});
U.createEl("h4", {
text: "Appearance"
});
new import_obsidian.Setting(U).setName("Show status inside the editor").setDesc("Reflected after reboot").addToggle((s => s.setValue(this.plugin.settings.showStatusOnEditor).onChange((async s => {
this.plugin.settings.showStatusOnEditor = s;
await this.plugin.saveSettings();
this.display();
}))));
if (this.plugin.settings.showStatusOnEditor) new import_obsidian.Setting(U).setName("Show status as icons only").setDesc("").addToggle((s => s.setValue(this.plugin.settings.showOnlyIconsOnEditor).onChange((async s => {
this.plugin.settings.showOnlyIconsOnEditor = s;
await this.plugin.saveSettings();
}))));
new import_obsidian.Setting(U).setName("Show status on the status bar").setDesc("Reflected after reboot.").addToggle((s => s.setValue(this.plugin.settings.showStatusOnStatusbar).onChange((async s => {
this.plugin.settings.showStatusOnStatusbar = s;
await this.plugin.saveSettings();
this.display();
}))));
U.createEl("h4", {
text: "Logging"
});
new import_obsidian.Setting(U).setName("Show only notifications").setDesc("Prevent logging and show only notification").addToggle((s => s.setValue(this.plugin.settings.lessInformationInLog).onChange((async s => {
this.plugin.settings.lessInformationInLog = s;
await this.plugin.saveSettings();
this.display();
}))));
if (!this.plugin.settings.lessInformationInLog) new import_obsidian.Setting(U).setName("Verbose Log").setDesc("Show verbose log").addToggle((s => s.setValue(this.plugin.settings.showVerboseLog).onChange((async s => {
this.plugin.settings.showVerboseLog = s;
await this.plugin.saveSettings();
}))));
U.createEl("h4", {
text: "Performance tweaks"
});
new import_obsidian.Setting(U).setName("Memory cache size (by total items)").setDesc("").addText((s => {
s.setPlaceholder("").setValue(this.plugin.settings.hashCacheMaxCount + "").onChange((async s => {
let r = Number(s);
if (isNaN(r) || r < 10) r = 10;
this.plugin.settings.hashCacheMaxCount = r;
await this.plugin.saveSettings();
}));
s.inputEl.setAttribute("type", "number");
}));
new import_obsidian.Setting(U).setName("Memory cache size (by total characters)").setDesc("(Mega chars)").addText((s => {
s.setPlaceholder("").setValue(this.plugin.settings.hashCacheMaxAmount + "").onChange((async s => {
let r = Number(s);
if (isNaN(r) || r < 1) r = 1;
this.plugin.settings.hashCacheMaxAmount = r;
await this.plugin.saveSettings();
}));
s.inputEl.setAttribute("type", "number");
}));
U.createEl("h4", {
text: "Share settings via markdown"
});
let z, W = this.plugin.settings.settingSyncFile;
new import_obsidian.Setting(U).setName("Filename").setDesc("If you set this, all settings are saved in a markdown file. You will also be notified when new settings were arrived. You can set different files by the platform.").addText((s => {
s.setPlaceholder("livesync/setting.md").setValue(W).onChange((s => {
W = s;
if (W == this.plugin.settings.settingSyncFile) {
z.removeCta();
z.setDisabled(true);
} else {
z.setCta();
z.setDisabled(false);
}
}));
})).addButton((s => {
s.setButtonText("Apply").onClick((async () => {
this.plugin.settings.settingSyncFile = W;
await this.plugin.saveSettings();
this.display();
}));
z = s;
}));
new import_obsidian.Setting(U).setName("Write credentials in the file").setDesc("(Not recommended) If set, credentials will be stored in the file.").addToggle((s => {
s.setValue(this.plugin.settings.writeCredentialsForSettingSync).onChange((async s => {
this.plugin.settings.writeCredentialsForSettingSync = s;
await this.plugin.saveSettings();
}));
}));
new import_obsidian.Setting(U).setName("Notify all setting files").addToggle((s => {
s.setValue(this.plugin.settings.notifyAllSettingSyncFile).onChange((async s => {
this.plugin.settings.notifyAllSettingSyncFile = s;
await this.plugin.saveSettings();
}));
}));
U.createEl("h4", {
text: "Advanced Confidentiality"
});
const H = {
"": "Default",
LOCALSTORAGE: "Use a custom passphrase",
ASK_AT_LAUNCH: "Ask an passphrase at every launch"
};
new import_obsidian.Setting(U).setName("Encrypting sensitive configuration items").addDropdown((s => s.addOptions(H).setValue(this.plugin.settings.configPassphraseStore).onChange((async s => {
this.plugin.settings.configPassphraseStore = s;
this.plugin.usedPassphrase = "";
Q.setDisabled("LOCALSTORAGE" != this.plugin.settings.configPassphraseStore);
await this.plugin.saveSettings();
})))).setClass("wizardHidden");
const K = localStorage.getItem("ls-setting-passphrase") || "", Q = new import_obsidian.Setting(U).setName("Passphrase of sensitive configuration items").setDesc("This passphrase will not be copied to another device. It will be set to `Default` until you configure it again.").addText((s => {
s.setPlaceholder("").setValue(K).onChange((async s => {
this.plugin.usedPassphrase = "";
localStorage.setItem("ls-setting-passphrase", s);
await this.plugin.saveSettings();
updateE2EControls();
}));
s.inputEl.setAttribute("type", "password");
})).setClass("wizardHidden");
Q.setDisabled("LOCALSTORAGE" != this.plugin.settings.configPassphraseStore);
addScreenElement("20", U);
const J = r.createDiv();
J.createEl("h3", {
text: "Sync Settings"
});
if ("" != this.plugin.settings.versionUpFlash) {
const s = J.createEl("div", {
text: this.plugin.settings.versionUpFlash
});
s.createEl("button", {
text: "I got it and updated."
}, (r => {
r.addClass("mod-cta");
r.addEventListener("click", (async () => {
this.plugin.settings.versionUpFlash = "";
await this.plugin.saveSettings();
applyDisplayEnabled();
s.remove();
}));
}));
s.addClass("op-warn");
}
let Y = "NONE";
J.createEl("div", {
text: "Please select any preset to complete wizard."
}).addClasses([ "op-warn-info", "wizardOnly" ]);
new import_obsidian.Setting(J).setName("Presets").setDesc("Apply preset configuration").addDropdown((s => s.addOptions({
NONE: "",
LIVESYNC: "LiveSync",
PERIODIC: "Periodic w/ batch",
DISABLE: "Disable all automatic"
}).setValue(Y).onChange((s => Y = s)))).addButton((s => s.setButtonText("Apply").setDisabled(false).setCta().onClick((async () => {
if ("" == Y) {
Logger("Select any preset.", LOG_LEVEL_NOTICE);
return;
}
const s = {
batchSave: false,
liveSync: false,
periodicReplication: false,
syncOnSave: false,
syncOnEditorSave: false,
syncOnStart: false,
syncOnFileOpen: false,
syncAfterMerge: false
}, r = {
...s,
liveSync: true
}, o = {
...s,
batchSave: true,
periodicReplication: true,
syncOnSave: false,
syncOnEditorSave: false,
syncOnStart: true,
syncOnFileOpen: true,
syncAfterMerge: true
};
if ("LIVESYNC" == Y) {
this.plugin.settings = {
...this.plugin.settings,
...r
};
Logger("Synchronization setting configured as LiveSync.", LOG_LEVEL_NOTICE);
} else if ("PERIODIC" == Y) {
this.plugin.settings = {
...this.plugin.settings,
...o
};
Logger("Synchronization setting configured as Periodic sync with batch database update.", LOG_LEVEL_NOTICE);
} else {
Logger("All synchronization disabled.", LOG_LEVEL_NOTICE);
this.plugin.settings = {
...this.plugin.settings,
...s
};
}
await this.plugin.saveSettings();
this.display();
await this.plugin.realizeSettingSyncMode();
if (k) {
this.closeSetting();
if (!this.plugin.settings.isConfigured) {
this.plugin.settings.isConfigured = true;
await this.plugin.saveSettings();
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.askReload();
}
}))));
J.createEl("h4", {
text: "Synchronization Methods"
}).addClass("wizardHidden");
const X = [], Z = [];
let ee, te = "";
if (this.plugin.settings.liveSync) te = "LIVESYNC"; else if (this.plugin.settings.periodicReplication) te = "PERIODIC";
new import_obsidian.Setting(J).setName("Sync Mode").setClass("wizardHidden").addDropdown((s => s.addOptions({
"": "On events",
PERIODIC: "Periodic and On events",
LIVESYNC: "LiveSync"
}).setValue(te).onChange((async s => {
this.plugin.settings.liveSync = false;
this.plugin.settings.periodicReplication = false;
if ("LIVESYNC" == s) this.plugin.settings.liveSync = true; else if ("PERIODIC" == s) this.plugin.settings.periodicReplication = true;
await this.plugin.saveSettings();
applyDisplayEnabled();
await this.plugin.realizeSettingSyncMode();
this.display();
}))));
if (!this.plugin.settings.liveSync) {
if (this.plugin.settings.periodicReplication) new import_obsidian.Setting(J).setName("Periodic Sync interval").setDesc("Interval (sec)").setClass("wizardHidden").addText((s => {
s.setPlaceholder("").setValue(this.plugin.settings.periodicReplicationInterval + "").onChange((async s => {
let r = Number(s);
if (isNaN(r) || r > 5e3) r = 0;
this.plugin.settings.periodicReplicationInterval = r;
await this.plugin.saveSettings();
applyDisplayEnabled();
}));
s.inputEl.setAttribute("type", "number");
}));
new import_obsidian.Setting(J).setName("Sync on Save").setDesc("When you save file, sync automatically").setClass("wizardHidden").addToggle((s => s.setValue(this.plugin.settings.syncOnSave).onChange((async s => {
this.plugin.settings.syncOnSave = s;
await this.plugin.saveSettings();
applyDisplayEnabled();
}))));
new import_obsidian.Setting(J).setName("Sync on Editor Save").setDesc("When you save file on the editor, sync automatically").setClass("wizardHidden").addToggle((s => s.setValue(this.plugin.settings.syncOnEditorSave).onChange((async s => {
this.plugin.settings.syncOnEditorSave = s;
await this.plugin.saveSettings();
applyDisplayEnabled();
}))));
new import_obsidian.Setting(J).setName("Sync on File Open").setDesc("When you open file, sync automatically").setClass("wizardHidden").addToggle((s => s.setValue(this.plugin.settings.syncOnFileOpen).onChange((async s => {
this.plugin.settings.syncOnFileOpen = s;
await this.plugin.saveSettings();
applyDisplayEnabled();
}))));
new import_obsidian.Setting(J).setName("Sync on Start").setDesc("Start synchronization after launching Obsidian.").setClass("wizardHidden").addToggle((s => s.setValue(this.plugin.settings.syncOnStart).onChange((async s => {
this.plugin.settings.syncOnStart = s;
await this.plugin.saveSettings();
applyDisplayEnabled();
}))));
new import_obsidian.Setting(J).setName("Sync after merging file").setDesc("Sync automatically after merging files").setClass("wizardHidden").addToggle((s => s.setValue(this.plugin.settings.syncAfterMerge).onChange((async s => {
this.plugin.settings.syncAfterMerge = s;
await this.plugin.saveSettings();
applyDisplayEnabled();
}))));
}
J.createEl("h4", {
text: "Deletions propagation"
}).addClass("wizardHidden");
new import_obsidian.Setting(J).setName("Use the trash bin").setDesc("Do not delete files that are deleted in remote, just move to trash.").setClass("wizardHidden").addToggle((s => s.setValue(this.plugin.settings.trashInsteadDelete).onChange((async s => {
this.plugin.settings.trashInsteadDelete = s;
await this.plugin.saveSettings();
}))));
new import_obsidian.Setting(J).setName("Keep empty folder").setDesc("Normally, a folder is deleted when it becomes empty after a synchronization. Enabling this will prevent it from getting deleted").setClass("wizardHidden").addToggle((s => s.setValue(this.plugin.settings.doNotDeleteFolder).onChange((async s => {
this.plugin.settings.doNotDeleteFolder = s;
await this.plugin.saveSettings();
}))));
J.createEl("h4", {
text: "Conflict resolution"
}).addClass("wizardHidden");
new import_obsidian.Setting(J).setName("Always overwrite with a newer file (beta)").setDesc("(Def off) Resolve conflicts by newer files automatically.").setClass("wizardHidden").addToggle((s => s.setValue(this.plugin.settings.resolveConflictsByNewerFile).onChange((async s => {
this.plugin.settings.resolveConflictsByNewerFile = s;
await this.plugin.saveSettings();
}))));
new import_obsidian.Setting(J).setName("Postpone resolution of inactive files").setClass("wizardHidden").addToggle((s => s.setValue(this.plugin.settings.checkConflictOnlyOnOpen).onChange((async s => {
this.plugin.settings.checkConflictOnlyOnOpen = s;
await this.plugin.saveSettings();
}))));
new import_obsidian.Setting(J).setName("Postpone manual resolution of inactive files").setClass("wizardHidden").addToggle((s => s.setValue(this.plugin.settings.showMergeDialogOnlyOnActive).onChange((async s => {
this.plugin.settings.showMergeDialogOnlyOnActive = s;
await this.plugin.saveSettings();
}))));
J.createEl("h4", {
text: "Compatibility"
}).addClass("wizardHidden");
new import_obsidian.Setting(J).setName("Always resolve conflict manually").setDesc("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)").setClass("wizardHidden").addToggle((s => s.setValue(this.plugin.settings.disableMarkdownAutoMerge).onChange((async s => {
this.plugin.settings.disableMarkdownAutoMerge = s;
await this.plugin.saveSettings();
}))));
new import_obsidian.Setting(J).setName("Always reflect synchronized changes even if the note has a conflict").setDesc("Turn on to previous behavior").setClass("wizardHidden").addToggle((s => s.setValue(this.plugin.settings.writeDocumentsIfConflicted).onChange((async s => {
this.plugin.settings.writeDocumentsIfConflicted = s;
await this.plugin.saveSettings();
}))));
J.createEl("h4", {
text: "Hidden files"
}).addClass("wizardHidden");
new import_obsidian.Setting(J).setName("Hidden file synchronization").setClass("wizardHidden").settingEl.createDiv("").innerText = this.plugin.settings.syncInternalFiles ? "🔁 : Enabled" : "⏹️ : Disabled";
if (this.plugin.settings.syncInternalFiles) new import_obsidian.Setting(J).setName("Disable Hidden files sync").setClass("wizardHidden").addButton((s => {
s.setButtonText("Disable").onClick((async () => {
this.plugin.settings.syncInternalFiles = false;
await this.plugin.saveSettings();
this.display();
}));
})); else new import_obsidian.Setting(J).setName("Enable Hidden files sync").setClass("wizardHidden").addButton((s => {
s.setButtonText("Merge").onClick((async () => {
this.closeSetting();
await this.plugin.addOnSetup.configureHiddenFileSync("MERGE");
}));
})).addButton((s => {
s.setButtonText("Fetch").onClick((async () => {
this.closeSetting();
await this.plugin.addOnSetup.configureHiddenFileSync("FETCH");
}));
})).addButton((s => {
s.setButtonText("Overwrite").onClick((async () => {
this.closeSetting();
await this.plugin.addOnSetup.configureHiddenFileSync("OVERWRITE");
}));
}));
if (!this.plugin.settings.watchInternalFileChanges) new import_obsidian.Setting(J).setName("Scan for hidden files before replication").setClass("wizardHidden").addToggle((s => s.setValue(this.plugin.settings.syncInternalFilesBeforeReplication).onChange((async s => {
this.plugin.settings.syncInternalFilesBeforeReplication = s;
await this.plugin.saveSettings();
}))));
new import_obsidian.Setting(J).setName("Scan hidden files periodically").setDesc("Seconds, 0 to disable").setClass("wizardHidden").addText((s => {
s.setPlaceholder("").setValue(this.plugin.settings.syncInternalFilesInterval + "").onChange((async s => {
let r = Number(s);
if (0 !== r && (isNaN(r) || r < 10)) r = 10;
this.plugin.settings.syncInternalFilesInterval = r;
await this.plugin.saveSettings();
}));
s.inputEl.setAttribute("type", "number");
}));
const ne = "\\/node_modules\\/, \\/\\.git\\/, \\/obsidian-livesync\\/", ie = ne + ",\\/workspace$ ,\\/workspace.json$,\\/workspace-mobile.json$";
new import_obsidian.Setting(J).setName("Folders and files to ignore").setDesc("Regular expression, If you use hidden file sync between desktop and mobile, adding `workspace$` is recommended.").setClass("wizardHidden").addTextArea((s => {
s.setValue(this.plugin.settings.syncInternalFilesIgnorePatterns).setPlaceholder("\\/node_modules\\/, \\/\\.git\\/").onChange((async s => {
this.plugin.settings.syncInternalFilesIgnorePatterns = s;
await this.plugin.saveSettings();
}));
ee = s;
return s;
}));
new import_obsidian.Setting(J).setName("Restore the skip pattern to default").setClass("wizardHidden").addButton((s => {
s.setButtonText("Default").onClick((async () => {
ee.setValue(ne);
this.plugin.settings.syncInternalFilesIgnorePatterns = ne;
await this.plugin.saveSettings();
}));
})).addButton((s => {
s.setButtonText("Cross-platform").onClick((async () => {
ee.setValue(ie);
this.plugin.settings.syncInternalFilesIgnorePatterns = ie;
await this.plugin.saveSettings();
}));
}));
J.createEl("h4", {
text: "Performance tweaks"
}).addClass("wizardHidden");
new import_obsidian.Setting(J).setName("Batch database update").setDesc("Reducing the frequency with which on-disk changes are reflected into the DB").setClass("wizardHidden").addToggle((s => s.setValue(this.plugin.settings.batchSave).onChange((async s => {
this.plugin.settings.batchSave = s;
await this.plugin.saveSettings();
}))));
new import_obsidian.Setting(J).setName("Enhance chunk size").setDesc("Enhance chunk size for binary files (Ratio). This cannot be increased when using IBM Cloudant.").setClass("wizardHidden").addText((s => {
s.setPlaceholder("").setValue(this.plugin.settings.customChunkSize + "").onChange((async s => {
let r = Number(s);
if (isNaN(r) || r < 1) r = 0;
this.plugin.settings.customChunkSize = r;
await this.plugin.saveSettings();
}));
s.inputEl.setAttribute("type", "number");
}));
new import_obsidian.Setting(J).setName("Fetch chunks on demand").setDesc("(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.").setClass("wizardHidden").addToggle((s => {
s.setValue(this.plugin.settings.readChunksOnline).onChange((async s => {
this.plugin.settings.readChunksOnline = s;
await this.plugin.saveSettings();
}));
return s;
}));
J.createEl("h4", {
text: (0, import_obsidian.sanitizeHTMLToDom)("Targets")
}).addClass("wizardHidden");
new import_obsidian.Setting(J).setName("Synchronising files").setDesc("(RegExp) Empty to sync all files. set filter as a regular expression to limit synchronising files.").setClass("wizardHidden").addTextArea((s => {
s.setValue(this.plugin.settings.syncOnlyRegEx).setPlaceholder("\\.md$|\\.txt").onChange((async s => {
let r = false;
try {
new RegExp(s);
r = true;
} catch (s) {}
if (r || "" == s.trim()) {
this.plugin.settings.syncOnlyRegEx = s;
await this.plugin.saveSettings();
}
}));
return s;
}));
new import_obsidian.Setting(J).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").addTextArea((s => {
s.setValue(this.plugin.settings.syncIgnoreRegEx).setPlaceholder("\\.pdf$").onChange((async s => {
let r = false;
try {
new RegExp(s);
r = true;
} catch (s) {}
if (r || "" == s.trim()) {
this.plugin.settings.syncIgnoreRegEx = s;
await this.plugin.saveSettings();
}
}));
return s;
}));
new import_obsidian.Setting(J).setName("Maximum file size").setDesc("(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.").setClass("wizardHidden").addText((s => {
s.setPlaceholder("").setValue(this.plugin.settings.syncMaxSizeInMB + "").onChange((async s => {
let r = Number(s);
if (isNaN(r) || r < 1) r = 0;
this.plugin.settings.syncMaxSizeInMB = r;
await this.plugin.saveSettings();
}));
s.inputEl.setAttribute("type", "number");
}));
new import_obsidian.Setting(J).setName("(Beta) Use ignore files").setDesc("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.").setClass("wizardHidden").addToggle((s => {
s.setValue(this.plugin.settings.useIgnoreFiles).onChange((async s => {
this.plugin.settings.useIgnoreFiles = s;
await this.plugin.saveSettings();
this.display();
}));
return s;
}));
if (this.plugin.settings.useIgnoreFiles) new import_obsidian.Setting(J).setName("Ignore files").setDesc("We can use multiple ignore files, e.g.) `.gitignore, .dockerignore`").setClass("wizardHidden").addTextArea((s => {
s.setValue(this.plugin.settings.ignoreFiles).setPlaceholder(".gitignore, .dockerignore").onChange((async s => {
this.plugin.settings.ignoreFiles = s;
await this.plugin.saveSettings();
}));
return s;
}));
J.createEl("h4", {
text: (0, import_obsidian.sanitizeHTMLToDom)("Advanced settings")
}).addClass("wizardHidden");
J.createEl("div", {
text: "If you reached the payload size limit when using IBM Cloudant, please decrease batch size and batch limit to a lower value."
}).addClass("wizardHidden");
new import_obsidian.Setting(J).setName("Batch size").setDesc("Number of change feed items to process at a time. Defaults to 50. Minimum is 2.").setClass("wizardHidden").addText((s => {
s.setPlaceholder("").setValue(this.plugin.settings.batch_size + "").onChange((async s => {
let r = Number(s);
if (isNaN(r) || r < 2) r = 2;
this.plugin.settings.batch_size = r;
await this.plugin.saveSettings();
}));
s.inputEl.setAttribute("type", "number");
}));
new import_obsidian.Setting(J).setName("Batch limit").setDesc("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.").setClass("wizardHidden").addText((s => {
s.setPlaceholder("").setValue(this.plugin.settings.batches_limit + "").onChange((async s => {
let r = Number(s);
if (isNaN(r) || r < 2) r = 2;
this.plugin.settings.batches_limit = r;
await this.plugin.saveSettings();
}));
s.inputEl.setAttribute("type", "number");
}));
new import_obsidian.Setting(J).setName("Use timeouts instead of heartbeats").setDesc("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.").setClass("wizardHidden").addToggle((s => {
s.setValue(this.plugin.settings.useTimeouts).onChange((async s => {
this.plugin.settings.useTimeouts = s;
await this.plugin.saveSettings();
}));
return s;
}));
new import_obsidian.Setting(J).setName("Batch size of on-demand fetching").setDesc("").setClass("wizardHidden").addText((s => {
s.setPlaceholder("").setValue(this.plugin.settings.concurrencyOfReadChunksOnline + "").onChange((async s => {
let r = Number(s);
if (isNaN(r) || r < 10) r = 10;
this.plugin.settings.concurrencyOfReadChunksOnline = r;
await this.plugin.saveSettings();
}));
s.inputEl.setAttribute("type", "number");
}));
new import_obsidian.Setting(J).setName("The delay for consecutive on-demand fetches").setDesc("").setClass("wizardHidden").addText((s => {
s.setPlaceholder("").setValue(this.plugin.settings.minimumIntervalOfReadChunksOnline + "").onChange((async s => {
let r = Number(s);
if (isNaN(r) || r < 10) r = 10;
this.plugin.settings.minimumIntervalOfReadChunksOnline = r;
await this.plugin.saveSettings();
}));
s.inputEl.setAttribute("type", "number");
}));
addScreenElement("30", J);
const se = r.createDiv();
se.createEl("h3", {
text: "Hatch"
});
new import_obsidian.Setting(se).setName("Make report to inform the issue").addButton((s => s.setButtonText("Make report").setDisabled(false).onClick((async () => {
let s = {};
const r = "𝑅𝐸𝐷𝐴𝐶𝑇𝐸𝐷";
try {
const o = await requestToCouchDB(this.plugin.settings.couchDB_URI, this.plugin.settings.couchDB_USER, this.plugin.settings.couchDB_PASSWORD, window.origin);
Logger(JSON.stringify(o.json, null, 2));
s = o.json;
s["couch_httpd_auth"].secret = r;
s["couch_httpd_auth"].authentication_db = r;
s["couch_httpd_auth"].authentication_redirect = r;
s["couchdb"].uuid = r;
s["admins"] = r;
} catch (r) {
s = "Requesting information to the remote CouchDB has been failed. If you are using IBM Cloudant, it is the normal behaviour.";
}
const o = JSON.parse(JSON.stringify(this.plugin.settings));
o.couchDB_DBNAME = r;
o.couchDB_PASSWORD = r;
const u = o.couchDB_URI.startsWith("http:") ? "(HTTP)" : o.couchDB_URI.startsWith("https:") ? "(HTTPS)" : "";
o.couchDB_URI = isCloudantURI(o.couchDB_URI) ? "cloudant" : `self-hosted${u}`;
o.couchDB_USER = r;
o.passphrase = r;
o.encryptedPassphrase = r;
o.encryptedCouchDBConnection = r;
o.pluginSyncExtendedSetting = {};
const g = `---- Obsidian info ----\n${navigator.userAgent}\n---- remote config ----\n${(0,
import_obsidian.stringifyYaml)(s)}\n---- Plug-in config ---\nversion:${L}\n${(0,
import_obsidian.stringifyYaml)(o)}`;
console.log(g);
await navigator.clipboard.writeText(g);
Logger("Information has been copied to clipboard", LOG_LEVEL_NOTICE);
}))));
if (this.plugin.replicator.remoteLockedAndDeviceNotAccepted) {
const s = se.createEl("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 local database, and press 'Mark this device as resolved'. "
});
s.createEl("button", {
text: "I'm ready, mark this device 'resolved'"
}, (r => {
r.addClass("mod-warning");
r.addEventListener("click", (async () => {
await this.plugin.markRemoteResolved();
s.remove();
}));
}));
s.addClass("op-warn");
} else if (this.plugin.replicator.remoteLocked) {
const s = se.createEl("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."
});
s.createEl("button", {
text: "I'm ready, unlock the database"
}, (r => {
r.addClass("mod-warning");
r.addEventListener("click", (async () => {
await this.plugin.markRemoteUnlocked();
s.remove();
}));
}));
s.addClass("op-warn");
}
new import_obsidian.Setting(se).setName("Back to non-configured").addButton((s => s.setButtonText("Back").setDisabled(false).onClick((async () => {
this.plugin.settings.isConfigured = false;
await this.plugin.saveSettings();
this.askReload();
}))));
se.createEl("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 = (s, r, o) => {
ae.appendChild(ae.createEl("div", {}, (u => {
u.appendChild(u.createEl("h6", {
text: s
}));
u.appendChild(u.createEl("div", {}, (s => {
s.appendChild(s.createEl("div", {
text: "Storage : Modified: " + (!r ? "Missing:" : `${new Date(r.stat.mtime).toLocaleString()}, Size:${r.stat.size}`)
}));
s.appendChild(s.createEl("div", {
text: "Database: Modified: " + (!o ? "Missing:" : `${new Date(o.mtime).toLocaleString()}, Size:${o.size}`)
}));
})));
if (o && r) u.appendChild(u.createEl("button", {
text: "Show history"
}, (s => {
s.onClickEvent((() => {
this.plugin.showHistory(r, o._id);
}));
})));
if (r) u.appendChild(u.createEl("button", {
text: "Storage -> Database"
}, (s => {
s.onClickEvent((() => {
this.plugin.updateIntoDB(r, void 0, true);
u.remove();
}));
})));
if (o) u.appendChild(u.createEl("button", {
text: "Database -> Storage"
}, (s => {
s.onClickEvent((() => {
this.plugin.pullFile(this.plugin.getPath(o), [], true, void 0, false);
u.remove();
}));
})));
return u;
})));
}, checkBetweenStorageAndDatabase = async (s, r) => {
const o = readAsBlob(r), u = createBlob(await this.plugin.vaultAccess.vaultReadAuto(s));
if (await isDocContentSame(u, o)) Logger(`Compare: SAME: ${s.path}`); else {
Logger(`Compare: CONTENT IS NOT MATCHED! ${s.path}`, LOG_LEVEL_NOTICE);
addResult(s.path, s, r);
}
};
new import_obsidian.Setting(se).setName("Verify and repair all files").setDesc("Compare the content of files between on local database and storage. If not matched, you will asked which one want to keep.").addButton((s => s.setButtonText("Verify all").setDisabled(false).setWarning().onClick((async () => {
const s = this.app.vault.getFiles(), r = [], o = this.plugin.localDatabase.findAllNormalDocs();
for await (const s of o) r.push(this.plugin.getPath(s));
const u = [ ...new Set([ ...r, ...s.map((s => s.path)) ]) ];
let g = 0;
for (const r of u) {
g++;
Logger(`${g}/${s.length}\n${r}`, LOG_LEVEL_NOTICE, "verify");
if (shouldBeIgnored(r)) continue;
const o = this.plugin.vaultAccess.getAbstractFileByPath(r), u = o instanceof import_obsidian5.TFile ? o : false;
if (!await this.plugin.isTargetFile(r)) continue;
if (u && this.plugin.isFileSizeExceeded(u.stat.size)) continue;
const _ = await this.plugin.localDatabase.getDBEntry(r);
if (!_ || !this.plugin.isFileSizeExceeded(_.size)) if (_ || !u) if (!_ || u) {
if (u && _) await checkBetweenStorageAndDatabase(u, _);
} else {
Logger(`Compare: Not found on the storage: ${r}`, LOG_LEVEL_NOTICE);
addResult(r, false, _);
} else {
Logger(`Compare: Not found on the local database: ${r}`, LOG_LEVEL_NOTICE);
addResult(r, u, false);
}
}
Logger("done", LOG_LEVEL_NOTICE, "verify");
}))));
const ae = se.createDiv({
text: ""
});
new import_obsidian.Setting(se).setName("Check and convert non-path-obfuscated files").setDesc("").addButton((s => s.setButtonText("Perform").setDisabled(false).setWarning().onClick((async () => {
var s, r, o;
for await (const u of this.plugin.localDatabase.findAllDocNames()) if (!u.startsWith("f:")) {
const g = await this.plugin.path2id(u), _ = await this.plugin.localDatabase.getRaw(u);
if (!_) continue;
if ("newnote" != _.type && "plain" != _.type) continue;
if (null != (s = null == _ ? void 0 : _.deleted) ? s : false) continue;
const m = {
..._
};
m._id = g;
m.path = u;
delete m._rev;
try {
const s = await this.plugin.localDatabase.getRaw(g, {
revs_info: true
});
null == (r = s._revs_info) || r.shift();
const b = null == (o = s._revs_info) ? void 0 : o.shift();
if (b) m._rev = b.rev; else m._rev = "1-" + `00000000000000000000000000000000${~~(1e9 * Math.random())}${~~(1e9 * Math.random())}${~~(1e9 * Math.random())}${~~(1e9 * Math.random())}`.slice(-32);
const E = await this.plugin.localDatabase.putRaw(m, {
force: true
});
if (E.ok) {
Logger(`${u} has been converted as conflicted document`, LOG_LEVEL_NOTICE);
_._deleted = true;
if ((await this.plugin.localDatabase.putRaw(_)).ok) Logger(`Old ${u} has been deleted`, LOG_LEVEL_NOTICE);
await this.plugin.queueConflictCheck(u);
} else {
Logger(`Converting ${u} Failed!`, LOG_LEVEL_NOTICE);
Logger(E, LOG_LEVEL_VERBOSE);
}
} catch (s) {
if (404 == (null == s ? void 0 : s.status)) {
if ((await this.plugin.localDatabase.putRaw(m)).ok) {
Logger(`${u} has been converted`, LOG_LEVEL_NOTICE);
_._deleted = true;
if ((await this.plugin.localDatabase.putRaw(_)).ok) Logger(`Old ${u} has been deleted`, LOG_LEVEL_NOTICE);
}
} else {
Logger(`Something went wrong on converting ${u}`, LOG_LEVEL_NOTICE);
Logger(s, LOG_LEVEL_VERBOSE);
}
}
}
Logger("Converting finished", LOG_LEVEL_NOTICE);
}))));
new import_obsidian.Setting(se).setName("Delete all customization sync data").addButton((s => s.setButtonText("Delete").setDisabled(false).setWarning().onClick((async () => {
Logger("Deleting customization sync data", LOG_LEVEL_NOTICE);
const s = (await this.plugin.localDatabase.allDocsRaw({
startkey: "ix:",
endkey: "ix:",
include_docs: true
})).rows.map((s => ({
...s.doc,
_deleted: true
})));
Logger(`${(await this.plugin.localDatabase.bulkDocsRaw(s)).length} items have been removed, to confirm how many items are left, please perform it again.`, LOG_LEVEL_NOTICE);
}))));
new import_obsidian.Setting(se).setName("Suspend file watching").setDesc("Stop watching for file change.").addToggle((s => s.setValue(this.plugin.settings.suspendFileWatching).onChange((async s => {
this.plugin.settings.suspendFileWatching = s;
await this.plugin.saveSettings();
this.askReload();
}))));
new import_obsidian.Setting(se).setName("Suspend database reflecting").setDesc("Stop reflecting database changes to storage files.").addToggle((s => s.setValue(this.plugin.settings.suspendParseReplicationResult).onChange((async s => {
this.plugin.settings.suspendParseReplicationResult = s;
await this.plugin.saveSettings();
this.askReload();
}))));
new import_obsidian.Setting(se).setName("Write logs into the file").setDesc("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.").addToggle((s => s.setValue(this.plugin.settings.writeLogToTheFile).onChange((async s => {
this.plugin.settings.writeLogToTheFile = s;
await this.plugin.saveSettings();
}))));
se.createEl("h4", {
text: (0, import_obsidian.sanitizeHTMLToDom)("Compatibility"),
cls: "wizardHidden"
});
new import_obsidian.Setting(se).setName("Do not keep metadata of deleted files.").setClass("wizardHidden").addToggle((s => {
s.setValue(this.plugin.settings.deleteMetadataOfDeletedFiles).onChange((async s => {
this.plugin.settings.deleteMetadataOfDeletedFiles = s;
await this.plugin.saveSettings();
this.display();
}));
}));
if (this.plugin.settings.deleteMetadataOfDeletedFiles) new import_obsidian.Setting(se).setName("Delete old metadata of deleted files on start-up").setClass("wizardHidden").setDesc("(Days passed, 0 to disable automatic-deletion)").addText((s => {
s.setPlaceholder("").setValue(this.plugin.settings.automaticallyDeleteMetadataOfDeletedFiles + "").onChange((async s => {
let r = Number(s);
if (isNaN(r)) r = 0;
this.plugin.settings.automaticallyDeleteMetadataOfDeletedFiles = r;
await this.plugin.saveSettings();
}));
s.inputEl.setAttribute("type", "number");
}));
new import_obsidian.Setting(se).setName("Use an old adapter for compatibility").setDesc("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.").setClass("wizardHidden").addToggle((s => s.setValue(!this.plugin.settings.useIndexedDBAdapter).onChange((async s => {
this.plugin.settings.useIndexedDBAdapter = !s;
await this.plugin.saveSettings();
await rebuildDB("localOnly");
}))));
new import_obsidian.Setting(se).setName("Scan changes on customization sync").setDesc("Do not use internal API").addToggle((s => s.setValue(!this.plugin.settings.watchInternalFileChanges).onChange((async s => {
this.plugin.settings.watchInternalFileChanges = !s;
await this.plugin.saveSettings();
}))));
let re = this.plugin.settings.additionalSuffixOfDatabaseName + "";
new import_obsidian.Setting(se).setName("Database suffix").setDesc("LiveSync could not handle multiple vaults which have same name without different prefix, This should be automatically configured.").addText((s => {
s.setPlaceholder("").setValue(re).onChange((s => {
re = s;
}));
})).addButton((s => {
s.setButtonText("Change").onClick((async () => {
if (this.plugin.settings.additionalSuffixOfDatabaseName != re) {
this.plugin.settings.additionalSuffixOfDatabaseName = re;
await this.plugin.saveSettings();
Logger("Suffix has been changed. Reopening database...", LOG_LEVEL_NOTICE);
await this.plugin.initializeDatabase();
} else Logger("Suffix was not changed.", LOG_LEVEL_NOTICE);
}));
}));
new import_obsidian.Setting(se).setName("The Hash algorithm for chunk IDs").setDesc("xxhash64 is the current default.").setClass("wizardHidden").addDropdown((s => s.addOptions({
"": "Old Algorithm",
xxhash32: "xxhash32 (Fast)",
xxhash64: "xxhash64 (Fastest)",
sha1: "Fallback (Without WebAssembly)"
}).setValue(this.plugin.settings.hashAlg).onChange((async s => {
this.plugin.settings.hashAlg = s;
await this.plugin.saveSettings();
})))).setClass("wizardHidden");
new import_obsidian.Setting(se).setName("Fetch database with previous behaviour").setDesc("").addToggle((s => s.setValue(this.plugin.settings.doNotSuspendOnFetching).onChange((async s => {
this.plugin.settings.doNotSuspendOnFetching = s;
await this.plugin.saveSettings();
}))));
addScreenElement("50", se);
const oe = r.createDiv();
oe.createEl("h3", {
text: "Customization sync (beta)"
});
const le = new import_obsidian.Setting(oe).setName("Device name").setDesc("Unique name between all synchronized devices. To edit this setting, please disable customization sync once.").addText((s => {
s.setPlaceholder("desktop").setValue(this.plugin.deviceAndVaultName).onChange((async s => {
this.plugin.deviceAndVaultName = s;
await this.plugin.saveSettings();
}));
})), updateDisabledOfDeviceAndVaultName = () => {
le.setDisabled(this.plugin.settings.usePluginSync);
};
updateDisabledOfDeviceAndVaultName();
new import_obsidian.Setting(oe).setName("Enable customization sync").addToggle((s => s.setValue(this.plugin.settings.usePluginSync).onChange((async r => {
if (r && "" == this.plugin.deviceAndVaultName.trim()) {
Logger("We have to configure `Device name` to use this feature.", LOG_LEVEL_NOTICE);
s.setValue(false);
return false;
}
this.plugin.settings.usePluginSync = r;
this.display();
await this.plugin.saveSettings();
}))));
if (this.plugin.settings.usePluginSync) {
new import_obsidian.Setting(oe).setName("Scan customization automatically").setDesc("Scan customization before replicating.").addToggle((s => s.setValue(this.plugin.settings.autoSweepPlugins).onChange((async s => {
this.plugin.settings.autoSweepPlugins = s;
updateDisabledOfDeviceAndVaultName();
await this.plugin.saveSettings();
}))));
if (!this.plugin.settings.watchInternalFileChanges) new import_obsidian.Setting(oe).setName("Scan customization periodically").setDesc("Scan customization every 1 minute.").addToggle((s => s.setValue(this.plugin.settings.autoSweepPluginsPeriodic).onChange((async s => {
this.plugin.settings.autoSweepPluginsPeriodic = s;
updateDisabledOfDeviceAndVaultName();
await this.plugin.saveSettings();
}))));
new import_obsidian.Setting(oe).setName("Notify customized").setDesc("Notify when other device has newly customized.").addToggle((s => s.setValue(this.plugin.settings.notifyPluginOrSettingUpdated).onChange((async s => {
this.plugin.settings.notifyPluginOrSettingUpdated = s;
await this.plugin.saveSettings();
}))));
new import_obsidian.Setting(oe).setName("Open").setDesc("Open the dialog").addButton((s => {
s.setButtonText("Open").setDisabled(false).onClick((() => {
this.plugin.addOnConfigSync.showPluginSyncModal();
}));
}));
}
updateDisabledOfDeviceAndVaultName();
addScreenElement("60", oe);
const ce = r.createDiv();
ce.createEl("h3", {
text: "Maintain databases"
});
ce.createEl("h4", {
text: "The remote database"
});
new import_obsidian.Setting(ce).setName("Lock remote database").setDesc("Lock remote database to prevent synchronization with other devices.").addButton((s => s.setButtonText("Lock").setDisabled(false).setWarning().onClick((async () => {
await this.plugin.markRemoteLocked();
}))));
new import_obsidian.Setting(ce).setName("Overwrite remote database").setDesc("Overwrite remote database with local DB and passphrase.").addButton((s => s.setButtonText("Send").setWarning().setDisabled(false).onClick((async () => {
await rebuildDB("remoteOnly");
}))));
ce.createEl("h4", {
text: "The local database"
});
new import_obsidian.Setting(ce).setName("Fetch rebuilt DB").setDesc("Restore or reconstruct local database from remote database.").addButton((s => s.setButtonText("Fetch").setWarning().setDisabled(false).onClick((async () => {
await rebuildDB("localOnly");
}))));
new import_obsidian.Setting(ce).setName("Fetch rebuilt DB (Save local documents before)").setDesc("Restore or reconstruct local database from remote database but use local chunks.").addButton((s => s.setButtonText("Save and Fetch").setWarning().setDisabled(false).onClick((async () => {
await rebuildDB("localOnlyWithChunks");
}))));
new import_obsidian.Setting(ce).setName("Discard local database to reset or uninstall Self-hosted LiveSync").addButton((s => s.setButtonText("Discard").setWarning().setDisabled(false).onClick((async () => {
await this.plugin.resetLocalDatabase();
await this.plugin.initializeDatabase();
}))));
ce.createEl("h4", {
text: "Both databases"
});
new import_obsidian.Setting(ce).setName("(Beta2) Clean up databases").setDesc("Delete unused chunks to shrink the database. This feature requires disabling 'Use an old adapter for compatibility'").addButton((s => s.setButtonText("DryRun").setDisabled(false).onClick((async () => {
await this.plugin.dryRunGC();
})))).addButton((s => s.setButtonText("Perform cleaning").setDisabled(false).setWarning().onClick((async () => {
this.closeSetting();
await this.plugin.dbGC();
}))));
new import_obsidian.Setting(ce).setName("Rebuild everything").setDesc("Rebuild local and remote database with local files.").addButton((s => s.setButtonText("Rebuild").setWarning().setDisabled(false).onClick((async () => {
await rebuildDB("rebuildBothByThisDevice");
}))));
applyDisplayEnabled();
addScreenElement("70", ce);
applyDisplayEnabled();
if ("" == this.selectedScreen) if (O != this.plugin.settings.lastReadUpdates) if (this.plugin.settings.isConfigured) changeDisplay("100"); else changeDisplay("110"); else if (isAnySyncEnabled()) changeDisplay("20"); else changeDisplay("110"); else changeDisplay(this.selectedScreen);
}
};
function isImage(s) {
const r = s.split(".").splice(-1)[0].toLowerCase();
return [ "png", "jpg", "jpeg", "gif", "bmp", "webp" ].includes(r);
}
function isComparableText(s) {
const r = s.split(".").splice(-1)[0].toLowerCase();
return isPlainText(s) || [ "md", "mdx", "txt", "json" ].includes(r);
}
function isComparableTextDecode(s) {
const r = s.split(".").splice(-1)[0].toLowerCase();
return [ "json" ].includes(r);
}
function readDocument(s) {
if (0 == s.data.length) return "";
if (isImage(s.path)) return new Uint8Array(decodeBinary(s.data));
if ("plain" == s.type || "plain" == s.datatype) return getDocData(s.data);
if (isComparableTextDecode(s.path)) return readString(new Uint8Array(decodeBinary(s.data)));
if (isComparableText(s.path)) return getDocData(s.data);
try {
return readString(new Uint8Array(decodeBinary(s.data)));
} catch (s) {}
return getDocData(s.data);
}
var DocumentHistoryModal = class extends import_obsidian.Modal {
constructor(s, r, o, u, g) {
super(s);
this.showDiff = false;
this.revs_info = [];
this.currentText = "";
this.currentDeleted = false;
this.BlobURLs = new Map;
this.plugin = r;
this.file = o instanceof import_obsidian.TFile ? getPathFromTFile(o) : o;
this.id = u;
this.initialRev = g;
if (!o && u) this.file = this.plugin.id2path(u);
if ("1" == localStorage.getItem("ols-history-highlightdiff")) this.showDiff = true;
}
async loadFile(s) {
var r, o;
if (!this.id) this.id = await this.plugin.path2id(this.file);
const u = this.plugin.localDatabase;
try {
const g = await u.getRaw(this.id, {
revs_info: true
});
this.revs_info = null != (o = null == (r = g._revs_info) ? void 0 : r.filter((s => "available" == (null == s ? void 0 : s.status)))) ? o : [];
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(s);
} catch (s) {
if (isErrorOfMissingDoc(s)) {
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(s, LOG_LEVEL_VERBOSE);
}
}
}
async loadRevs(s) {
if (0 == this.revs_info.length) return;
if (s) {
const r = this.revs_info.findIndex((r => r.rev == s));
if (r >= 0) this.range.value = "" + (this.revs_info.length - 1 - r);
}
const r = this.revs_info.length - 1 - this.range.value / 1, o = this.revs_info[r];
await this.showExactRev(o.rev);
}
revokeURL(s) {
const r = this.BlobURLs.get(s);
if (r) URL.revokeObjectURL(r);
this.BlobURLs.delete(s);
}
generateBlobURL(s, r) {
this.revokeURL(s);
const o = URL.createObjectURL(new Blob([ r ], {
endings: "transparent",
type: "application/octet-stream"
}));
this.BlobURLs.set(s, o);
return o;
}
async showExactRev(s) {
const r = this.plugin.localDatabase, o = await r.getDBEntry(this.file, {
rev: s
}, false, false, true);
this.currentText = "";
this.currentDeleted = false;
if (false === o) {
this.currentDeleted = true;
this.info.innerHTML = "";
this.contentView.innerHTML = `Could not read this revision
(${s})`;
} else {
this.currentDoc = o;
this.info.innerHTML = `Modified:${new Date(o.mtime).toLocaleString()}`;
let s;
const u = readDocument(o);
this.currentDeleted = !!o.deleted;
if (this.showDiff) {
const o = this.revs_info.length - 1 - (this.range.value / 1 - 1);
if (o >= 0 && o < this.revs_info.length) {
const g = this.revs_info[o].rev, _ = await r.getDBEntry(this.file, {
rev: g
}, false, false, true);
if (false != _) if ("string" == typeof u) {
s = "";
const r = new import_diff_match_patch.diff_match_patch, o = readDocument(_), g = r.diff_main(o, u);
r.diff_cleanupSemantic(g);
for (const r of g) {
const o = r[0], u = r[1];
if (o == import_diff_match_patch.DIFF_DELETE) s += "" + escapeStringToHTML(u) + ""; else if (o == import_diff_match_patch.DIFF_EQUAL) s += "" + escapeStringToHTML(u) + ""; else if (o == import_diff_match_patch.DIFF_INSERT) s += "" + escapeStringToHTML(u) + "";
}
s = s.replace(/\n/g, "
");
} else if (isImage(this.file)) {
s = `